Add comprehensive MDC files for various technologies and frameworks

Generate a large set of Markdown Configuration (MDC) files covering best practices across multiple domains, including:
- AI/ML libraries (PyTorch, TensorFlow, scikit-learn)
- Backend frameworks (Django, FastAPI, Express, Spring Boot)
- Frontend frameworks (React, Vue, Angular)
- Cloud platforms (AWS, Azure, GCP)
- Development tools (Docker, Kubernetes, Terraform)
- State management libraries
- UI component libraries
- Web technologies and APIs

Enhance project documentation with detailed, standardized best practice guidelines for different technologies and frameworks
This commit is contained in:
sanjeed5
2025-02-27 16:58:58 +05:30
parent 676f3376bf
commit 5068ef1d22
88 changed files with 20037 additions and 0 deletions
@@ -0,0 +1,188 @@
---
description: This rule provides comprehensive best practices for developing with Turbopack, covering code organization, performance, security, testing, and tooling to ensure efficient and maintainable applications.
globs: **/*.{js,jsx,ts,tsx}
---
# Turbopack Best Practices
This document outlines best practices for developing with Turbopack, focusing on code organization, performance, security, testing, and tooling.
## 1. Core Principles
- **Leverage the Turbo Engine:** Turbopack's core strength lies in its Turbo engine for function-level caching. Understand and utilize this for incremental builds.
- **Embrace Incremental Computation:** Be mindful of how changes affect the build process. Design your application to maximize incremental computation benefits.
- **Use TypeScript:** Turbopack has built-in support for TypeScript and JSX, so use them to improve code quality and developer experience. Make full use of TypeScript's features like generics, interfaces and types.
- **Follow Next.js Conventions:** When using Turbopack within Next.js, adhere to Next.js's recommended patterns and practices.
- **Avoid direct webpack configurations:** Turbopack aims to abstract away webpack configurations, prefer using Next.js configurations to customize Turbopack.
## 2. Code Organization and Structure
- **Directory Structure:**
- **`src/`:** All application source code should reside within the `src/` directory.
- **`components/`:** Reusable UI components.
- **`pages/`:** (Next.js) Pages for routing.
- **`api/`:** (Next.js) API routes.
- **`lib/` or `utils/`:** Utility functions and shared logic.
- **`types/` or `interfaces/`:** TypeScript type definitions and interfaces.
- **`styles/` or `css/`:** Global styles and CSS modules.
- **`public/`:** Static assets (images, fonts, etc.).
- **File Naming Conventions:**
- Use descriptive names for files and directories.
- Component files: `ComponentName.jsx` or `ComponentName.tsx`.
- Style files: `ComponentName.module.css` or `ComponentName.module.scss`.
- Utility files: `utilityName.js` or `utilityName.ts`.
- **Module Organization:**
- Group related code into modules with clear responsibilities.
- Export only what is necessary from each module.
- Use ES modules (import/export) for modularity.
- **Component Architecture:**
- **Atomic Design:** Consider using Atomic Design principles to create a scalable and maintainable component architecture.
- **Composition:** Favor composition over inheritance for component reusability.
- **Separation of Concerns:** Separate UI logic, data fetching, and state management within components.
- **Keep components small:** Focus on single responsability principle.
- **Code Splitting Strategies:**
- **Dynamic Imports:** Use dynamic imports (`import()`) to split code into smaller chunks that are loaded on demand.
- **Route-Based Splitting:** (Next.js) Each page in the `pages/` directory is automatically code-split.
- **Component-Based Splitting:** Split large components into smaller, lazily loaded sub-components.
- **Vendor Splitting:** Turbopack automatically splits vendor code (third-party libraries) into separate chunks.
## 3. Common Patterns and Anti-patterns
- **Design Patterns:**
- **Higher-Order Components (HOCs):** Reusable logic for components (use with caution, consider hooks).
- **Render Props:** Sharing code between React components using a prop whose value is a function.
- **Hooks:** Reusable stateful logic for functional components.
- **Context API:** Share data that is considered "global" for a tree of React components.
- **Recommended Approaches:**
- **Data Fetching:** Use `getServerSideProps`, `getStaticProps`, or `getInitialProps` (Next.js) for data fetching depending on your requirements.
- **API Routes:** Use Next.js API routes to create serverless functions for handling API requests.
- **State Management:** Choose a state management library (Redux, Zustand, Jotai, Recoil) based on the complexity of your application.
- **Anti-patterns:**
- **Global State Mutation:** Avoid directly mutating global state, use reducers or state management libraries.
- **Over-Fetching:** Fetch only the data that is needed by a component.
- **Tight Coupling:** Reduce dependencies between modules to improve maintainability.
- **Long Component Files:** Avoid having components larger than 200-300 lines, break down them into smaller components.
- **State Management Best Practices:**
- **Centralized State:** Manage application state in a central store.
- **Immutability:** Treat state as immutable to prevent unexpected side effects.
- **Reducers:** Use reducers to update state based on actions.
- **Selectors:** Use selectors to derive data from the state.
- **Error Handling Patterns:**
- **Error Boundaries:** Use error boundaries to catch JavaScript errors anywhere in a component tree.
- **Centralized Error Logging:** Log errors to a central service for monitoring and debugging.
- **Graceful Degradation:** Handle errors gracefully and provide informative messages to the user.
- **Retry mechanisms:** Implement retry mechanisms for failed requests.
## 4. Performance Considerations
- **Optimization Techniques:**
- **Caching:** Leverage Turbopack's caching capabilities to avoid unnecessary re-builds.
- **Memoization:** Use `React.memo` or `useMemo` to memoize components and values.
- **Debouncing and Throttling:** Use debouncing and throttling to reduce the frequency of function calls.
- **Memory Management:**
- **Avoid Memory Leaks:** Be careful to clean up event listeners and timers when components unmount.
- **Garbage Collection:** Understand how JavaScript garbage collection works and avoid creating unnecessary objects.
- **Rendering Optimization:**
- **Virtualization:** Use virtualization libraries for rendering large lists.
- **Code Splitting:** Split the codebase into smaller chunks using dynamic imports for faster initial load times.
- **Image Optimization:** Optimize images using tools like `next/image` or `cloudinary`.
- **Bundle Size Optimization:**
- **Tree Shaking:** Remove unused code from the bundle by using ES modules and configuring your bundler correctly.
- **Minification:** Minify JavaScript and CSS code to reduce bundle size.
- **Compression:** Compress assets using gzip or Brotli.
- **Lazy Loading Strategies:**
- **Component-Level Lazy Loading:** Lazy load components that are not initially visible.
- **Image Lazy Loading:** Lazy load images that are not initially visible.
- **Route-Based Lazy Loading:** Lazy load routes that are not frequently visited.
## 5. Security Best Practices
- **Common Vulnerabilities:**
- **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input and using appropriate escaping techniques.
- **Cross-Site Request Forgery (CSRF):** Prevent CSRF attacks by using CSRF tokens.
- **SQL Injection:** Prevent SQL injection attacks by using parameterized queries or ORMs.
- **Authentication and Authorization Issues:** Secure your API endpoints with proper authentication and authorization mechanisms.
- **Input Validation:**
- **Validate all user input:** Sanitize and validate all user input on both the client and server.
- **Use appropriate data types:** Enforce data types to prevent unexpected values.
- **Authentication and Authorization Patterns:**
- **JSON Web Tokens (JWT):** Use JWTs for authentication and authorization.
- **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on user roles.
- **OAuth:** Use OAuth for third-party authentication.
- **Data Protection Strategies:**
- **Encryption:** Encrypt sensitive data at rest and in transit.
- **Data Masking:** Mask sensitive data in logs and reports.
- **Data Retention Policies:** Implement data retention policies to ensure compliance with regulations.
- **Secure API Communication:**
- **HTTPS:** Use HTTPS to encrypt communication between the client and server.
- **Rate Limiting:** Implement rate limiting to prevent abuse and denial-of-service attacks.
- **API Keys:** Use API keys for authentication.
## 6. Testing Approaches
- **Unit Testing Strategies:**
- **Test individual components and functions:** Write unit tests to verify the behavior of individual components and functions.
- **Use mocking and stubbing:** Use mocking and stubbing to isolate components from their dependencies.
- **Test edge cases:** Test edge cases and error conditions.
- **Integration Testing:**
- **Test the interaction between components:** Write integration tests to verify the interaction between components.
- **Test data flow:** Test the flow of data between components and services.
- **End-to-End Testing:**
- **Test the entire application flow:** Write end-to-end tests to verify the entire application flow.
- **Use browser automation tools:** Use browser automation tools like Cypress or Puppeteer.
- **Test Organization:**
- **Keep tests close to the code:** Organize tests in the same directory as the code they test.
- **Use descriptive test names:** Use descriptive test names that clearly describe what the test is verifying.
- **Mocking and Stubbing:**
- **Use mocking libraries:** Use mocking libraries like Jest or Sinon to create mocks and stubs.
- **Avoid over-mocking:** Mock only the dependencies that are necessary.
## 7. Common Pitfalls and Gotchas
- **Frequent Mistakes:**
- **Incorrectly configured `tsconfig.json`:** Ensure paths and baseUrl are correctly configured for absolute imports.
- **Misunderstanding caching:** Not utilizing Turbopack's caching efficiently, leading to slower builds.
- **Not using TypeScript features**: Not leveraging the benefits of Typescript and writing javascript code that misses out on typesafety.
- **Edge Cases:**
- **Complex dependencies:** Be aware of how complex dependencies can affect build times.
- **Large file sizes:** Optimize large file sizes to improve performance.
- **Version-Specific Issues:**
- **Breaking changes:** Be aware of breaking changes in Turbopack and Next.js releases.
- **Compatibility issues:** Ensure that your dependencies are compatible with the versions of Turbopack and Next.js that you are using.
- **Compatibility Concerns:**
- **Browser compatibility:** Test your application in different browsers to ensure compatibility.
- **Device compatibility:** Test your application on different devices to ensure compatibility.
- **Debugging Strategies:**
- **Use debugging tools:** Use browser developer tools and debugging tools to identify and fix issues.
- **Log statements:** Use log statements to track the flow of execution and identify errors.
- **Reproducible steps:** Create reproducible steps to help isolate and fix issues.
## 8. Tooling and Environment
- **Recommended Development Tools:**
- **VS Code:** A popular code editor with excellent support for JavaScript, TypeScript, and React.
- **ESLint:** A linter that helps you identify and fix code style issues.
- **Prettier:** A code formatter that automatically formats your code.
- **Chrome Developer Tools:** Powerful tools for debugging and profiling web applications.
- **Build Configuration:**
- **Configure `tsconfig.json`:** Configure `tsconfig.json` to enable TypeScript features and specify compiler options.
- **Configure ESLint:** Configure ESLint to enforce code style guidelines.
- **Configure Prettier:** Configure Prettier to automatically format code.
- **Linting and Formatting:**
- **Use ESLint and Prettier:** Use ESLint and Prettier to automatically lint and format your code.
- **Integrate with your editor:** Integrate ESLint and Prettier with your code editor to automatically lint and format code on save.
- **Deployment Best Practices:**
- **Use a CI/CD pipeline:** Use a CI/CD pipeline to automate the build, test, and deployment process.
- **Deploy to a CDN:** Deploy static assets to a CDN for faster delivery.
- **Monitor your application:** Monitor your application for errors and performance issues.
- **CI/CD Integration:**
- **Use GitHub Actions, GitLab CI, or CircleCI:** Use a CI/CD platform to automate the build, test, and deployment process.
- **Run tests in CI/CD:** Run tests in your CI/CD pipeline to ensure that code changes do not introduce new bugs.
- **Automate deployments:** Automate deployments to production and staging environments.
## 9. Additional Considerations
- **Experimentation:** Turbopack is rapidly evolving. Experiment with new features and configurations to optimize your build process.
- **Community Engagement:** Participate in the Turbopack community to share your experiences and learn from others.
- **Documentation:** Refer to the official Turbopack documentation for the latest information and guidance.
By following these best practices, you can leverage the full potential of Turbopack to build high-performance, maintainable, and secure applications.
@@ -0,0 +1,224 @@
---
description: This rule provides comprehensive best practices, coding standards, and guidelines for developing applications using Vite, covering aspects from code organization and performance to security and testing.
globs: **/*.{js,jsx,ts,tsx,vue,svelte}
---
- **Introduction:**
- This document outlines best practices for developing applications using Vite, a fast and opinionated build tool that aims to provide a better development experience.
- **Prerequisites:**
- Ensure Node.js and npm/yarn/pnpm are installed.
- Familiarity with JavaScript/TypeScript, HTML, and CSS.
- **Code Organization and Structure:**
- **Directory Structure:**
- Adopt a modular structure based on features or components.
src/
├── components/
│ ├── Button/
│ │ ├── Button.tsx
│ │ ├── Button.module.css
│ │ └── Button.test.tsx
│ ├── Input/
│ │ └── ...
├── pages/
│ ├── Home.tsx
│ ├── About.tsx
│ └── ...
├── services/
│ ├── api.ts
│ └── ...
├── utils/
│ ├── helpers.ts
│ └── ...
├── App.tsx
├── main.tsx
└── vite-env.d.ts
- **File Naming Conventions:**
- Use descriptive and consistent names.
- Component files: `ComponentName.tsx` or `component-name.tsx`.
- Style files: `ComponentName.module.css` or `component-name.module.css`.
- Test files: `ComponentName.test.tsx` or `component-name.test.tsx`.
- **Module Organization:**
- Group related files into modules or folders.
- Use `index.ts` (barrel files) to simplify imports.
typescript
// src/components/Button/index.ts
export { default as Button } from './Button';
- **Component Architecture:**
- Favor small, reusable components.
- Utilize functional components and hooks in React (or equivalent in Vue/Svelte).
- Separate concerns: presentational vs. container components.
- **Code Splitting Strategies:**
- Use dynamic imports (`import()`) for lazy loading.
- Split routes using `React.lazy` or Vue's dynamic component feature.
- Configure Vite's `rollupOptions.output.manualChunks` for fine-grained control.
- **Common Patterns and Anti-patterns:**
- **Design Patterns:**
- **Higher-Order Components (HOCs):** Carefully consider alternatives like render props or hooks for better composability.
- **Render Props:** Useful for sharing logic between components, but can lead to deeply nested structures.
- **Hooks:** Promote code reuse and simplify component logic.
- **Recommended Approaches:**
- Use environment variables for configuration.
- Implement a consistent API client for data fetching.
- Centralize state management using libraries like Redux, Zustand, or Vuex.
- **Anti-patterns:**
- Avoid deeply nested component trees without proper optimization.
- Don't mutate state directly; use setState or Vue's reactivity system.
- Overusing global styles; prefer CSS modules or styled components.
- **State Management:**
- Choose a state management solution based on application complexity.
- Use Redux for complex state management with predictable state transitions and time travel debugging.
- Consider Zustand or Jotai for simpler state management with a smaller bundle size.
- For Vue, Vuex or Pinia are popular choices.
- **Error Handling:**
- Implement global error boundaries to catch unhandled exceptions.
- Use try-catch blocks for local error handling.
- Log errors to a central error tracking service (e.g., Sentry, Rollbar).
- **Performance Considerations:**
- **Optimization Techniques:**
- Use production-ready code minification and bundling.
- Optimize images and other assets using tools like `imagemin` or Vite plugins.
- **Memory Management:**
- Avoid memory leaks by properly cleaning up event listeners and subscriptions.
- Use `useEffect` with a cleanup function in React (or `onUnmounted` in Vue).
- **Rendering Optimization:**
- Use memoization techniques (`React.memo`, `useMemo`, `shouldComponentUpdate`) to prevent unnecessary re-renders.
- Virtualize large lists using libraries like `react-window` or `react-virtualized`.
- **Bundle Size Optimization:**
- Analyze bundle size using `rollup-plugin-visualizer` or similar tools.
- Remove unused code using tree shaking.
- Use code splitting to load only necessary code.
- **Lazy Loading:**
- Lazy load components and images that are not immediately visible.
- Use `IntersectionObserver` to trigger loading when elements enter the viewport.
- **Security Best Practices:**
- **Common Vulnerabilities:**
- Cross-Site Scripting (XSS): Sanitize user input to prevent XSS attacks.
- Cross-Site Request Forgery (CSRF): Use CSRF tokens to protect against CSRF attacks.
- Injection Attacks: Validate and sanitize input to prevent SQL injection and other injection attacks.
- **Input Validation:**
- Validate all user input on both the client and server side.
- Use a library like `yup` or `joi` for schema validation.
- **Authentication and Authorization:**
- Use a secure authentication and authorization mechanism (e.g., OAuth 2.0, JWT).
- Store passwords securely using bcrypt or Argon2.
- **Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use HTTPS for all communication.
- **Secure API Communication:**
- Implement proper CORS configuration to prevent unauthorized access to your API.
- Rate limit API requests to prevent abuse.
- **Testing Approaches:**
- **Unit Testing:**
- Write unit tests for individual components and functions.
- Use testing libraries like Jest, Mocha, or Vitest.
- Mock dependencies to isolate units under test.
- **Integration Testing:**
- Test the interaction between different parts of your application.
- Use testing libraries like React Testing Library or Vue Test Utils.
- **End-to-End Testing:**
- Test the entire application from the user's perspective.
- Use tools like Cypress or Playwright.
- **Test Organization:**
- Organize tests into folders based on features or components.
- Use descriptive test names.
- **Mocking and Stubbing:**
- Use mocks and stubs to isolate units under test.
- Avoid over-mocking; test the actual implementation whenever possible.
- **Common Pitfalls and Gotchas:**
- **Frequent Mistakes:**
- Improperly handling asynchronous operations.
- Neglecting accessibility considerations.
- Using outdated dependencies.
- **Edge Cases:**
- Handling different screen sizes and devices.
- Supporting internationalization and localization.
- Dealing with slow network connections.
- **Version-Specific Issues:**
- Be aware of breaking changes in Vite and its plugins.
- Pin dependencies to specific versions to avoid unexpected issues.
- **Compatibility Concerns:**
- Test your application in different browsers and devices.
- Use polyfills to support older browsers.
- **Debugging Strategies:**
- Use browser developer tools to inspect the DOM, network requests, and console output.
- Use debugging tools like `debugger` or `console.log`.
- **Tooling and Environment:**
- **Recommended Tools:**
- VS Code with extensions like ESLint, Prettier, and TypeScript.
- Chrome DevTools or Firefox Developer Tools.
- npm/yarn/pnpm for package management.
- **Build Configuration:**
- Configure Vite using `vite.config.ts` or `vite.config.js`.
- Customize build options like `outDir`, `assetsDir`, and `rollupOptions`.
- **Linting and Formatting:**
- Use ESLint with recommended rulesets (e.g., `eslint:recommended`, `plugin:react/recommended`).
- Use Prettier for code formatting.
- Configure ESLint and Prettier to work together.
- **Deployment Best Practices:**
- Deploy to a CDN for optimal performance.
- Use environment variables for configuration.
- Set up proper caching headers.
- **CI/CD Integration:**
- Integrate with a CI/CD pipeline for automated testing and deployment.
- Use tools like GitHub Actions, GitLab CI, or CircleCI.
- **TypeScript Best Practices (when using TypeScript):**
- **Strict Type-Checking:**
- Enable strict type-checking options in `tsconfig.json` (e.g., `strict: true`, `noImplicitAny: true`, `strictNullChecks: true`).
- **Typing Props and State:**
- Use interfaces or types to define the shape of props and state.
typescript
interface ButtonProps {
label: string;
onClick: () => void;
}
const Button: React.FC<ButtonProps> = ({ label, onClick }) => {
return <button onClick={onClick}>{label}</button>;
};
- **ESLint Configuration (Example):**
javascript
module.exports = {
env: {
browser: true,
es2021: true,
node: true,
},
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 12,
sourceType: 'module',
},
plugins: ['react', '@typescript-eslint', 'prettier'],
rules: {
'prettier/prettier': 'error',
'react/react-in-jsx-scope': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'warn',
},
};
- **Conclusion:**
- Following these best practices will help you build efficient, maintainable, and secure applications with Vite. Continuously review and update your practices as the library and ecosystem evolve.
@@ -0,0 +1,281 @@
---
description: This rule provides comprehensive best practices for Webpack configuration, optimization, and usage within projects. It covers code organization, performance, security, testing, and common pitfalls to ensure robust and efficient builds.
globs: **/webpack.config.js
---
# Webpack Best Practices: A Comprehensive Guide
This guide provides a detailed set of best practices for using Webpack effectively, covering various aspects from project setup to production optimization. Following these guidelines will help you create robust, performant, and maintainable webpack configurations.
## 1. Code Organization and Structure
### Directory Structure Best Practices
A well-structured directory is crucial for maintainability and scalability. Here's a recommended directory structure:
project-name/
├── src/ # Source code directory
│ ├── components/ # Reusable UI components
│ ├── modules/ # Independent modules
│ ├── assets/ # Static assets (images, fonts, etc.)
│ │ ├── images/
│ │ ├── fonts/
│ │ └── styles/
│ ├── index.js # Entry point of the application
│ └── ...
├── dist/ # Output directory (generated by Webpack)
├── config/ # Webpack configuration files
│ ├── webpack.common.js # Common configuration for all environments
│ ├── webpack.dev.js # Development-specific configuration
│ └── webpack.prod.js # Production-specific configuration
├── node_modules/ # Node modules (dependencies)
├── package.json # Project metadata and dependencies
├── webpack.config.js # Main webpack configuration entry point (can delegate to config/)
├── .babelrc # Babel configuration file (if using Babel)
└── ...
### File Naming Conventions
* **JavaScript/JSX:** `ComponentName.js` or `ComponentName.jsx`
* **CSS/SCSS/LESS:** `ComponentName.module.css`, `ComponentName.module.scss`, or `ComponentName.module.less` (for CSS Modules)
* **Images:** `descriptive-name.jpg`, `descriptive-name.png`, `descriptive-name.svg`
* **Webpack Config:** `webpack.config.js`, `webpack.common.js`, `webpack.dev.js`, `webpack.prod.js`
### Module Organization
Organize modules based on functionality or feature. Use clear and descriptive names. For example:
javascript
// src/modules/api.js
export function fetchData(url) {
// ...
}
// src/modules/utils.js
export function formatDate(date) {
// ...
}
### Component Architecture
For UI frameworks like React, Vue, or Angular, adopt a component-based architecture. Separate concerns into reusable components. Use a clear folder structure within the `components` directory (e.g., `src/components/Button/Button.jsx`).
### Code Splitting Strategies
* **Entry Points:** Define multiple entry points in `webpack.config.js` for different pages or sections of your application. Useful for multi-page applications.
* **Dynamic Imports:** Use `import()` syntax for lazy-loading modules or components on demand. This can significantly reduce the initial bundle size.
javascript
// Example of dynamic import
async function loadComponent() {
const { default: Component } = await import('./MyComponent');
// ...
}
* **SplitChunksPlugin:** Use the `SplitChunksPlugin` to extract common dependencies into separate chunks, which can be cached by the browser. Configure it in `webpack.config.js`:
javascript
// webpack.config.js
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
Consider these `SplitChunksPlugin` options:
* `chunks`: `'all'` (recommended), `'async'`, or `'initial'`
* `cacheGroups`: Define rules for creating chunks (e.g., `vendor` for node_modules)
* `minSize`: Minimum size of a chunk to be created
## 2. Common Patterns and Anti-patterns
### Design Patterns Specific to Webpack
* **Environment-Specific Configurations:** Use separate configuration files for development and production (e.g., `webpack.dev.js`, `webpack.prod.js`). Use `webpack-merge` to combine common configurations with environment-specific settings.
* **Loader Chains:** Configure loaders to process files in a specific order (e.g., `sass-loader` -> `css-loader` -> `style-loader`).
* **Plugin Composition:** Use multiple plugins to achieve complex build processes.
### Recommended Approaches for Common Tasks
* **Handling CSS:** Use CSS Modules for component-level styling. Combine with `sass-loader` or `less-loader` for pre-processing.
* **Image Optimization:** Use `image-webpack-loader` to optimize images during the build process.
* **Environment Variables:** Use `DefinePlugin` to inject environment variables into your code.
### Anti-patterns and Code Smells to Avoid
* **Overly Complex Configurations:** Keep configurations as simple as possible. Break down complex logic into reusable modules.
* **Large Bundles:** Avoid large bundles by using code splitting and tree shaking.
* **Ignoring Warnings/Errors:** Always address warnings and errors reported by Webpack.
* **Over-relying on Global Styles:** Prefer CSS Modules to avoid naming conflicts.
### State Management Best Practices
* If using a state management library like Redux or Vuex, ensure that it is correctly integrated with Webpack.
* Consider using lazy-loading for state modules to improve initial load time.
### Error Handling Patterns
* Use try-catch blocks to handle errors in asynchronous operations.
* Implement error boundaries in UI components to prevent crashes.
* Configure Webpack to display meaningful error messages.
## 3. Performance Considerations
### Optimization Techniques
* **Tree Shaking:** Remove unused code by using ES modules and setting `optimization.usedExports: true` in `webpack.config.js`. Ensure that your code is written in ES module syntax (e.g., `import` and `export`).
* **Minification:** Use TerserPlugin (included by default in production mode) or other minification plugins to reduce bundle size.
* **Code Splitting:** Split your code into smaller chunks to improve initial load time (see Code Splitting Strategies above).
* **Compression:** Use Gzip or Brotli compression on your server to reduce the size of transferred files.
* **Caching:** Leverage browser caching by using content hashes in filenames (e.g., `[name].[contenthash].js`).
### Memory Management
* Be mindful of memory usage during the build process, especially when using loaders that perform complex transformations.
* Consider using `thread-loader` to offload expensive loaders to a worker pool.
### Rendering Optimization
* Optimize images and other assets to reduce their size.
* Use lazy-loading for images and components that are not immediately visible.
### Bundle Size Optimization
* Analyze your bundle size using `webpack-bundle-analyzer` to identify large dependencies.
* Remove unnecessary dependencies.
* Use smaller alternatives to large libraries when possible.
### Lazy Loading Strategies
* Implement lazy-loading for routes, components, and modules that are not critical for the initial load.
* Use the `React.lazy` or `Vue.component` with a dynamic `import()` to lazy load components.
## 4. Security Best Practices
### Common Vulnerabilities and How to Prevent Them
* **Dependency Vulnerabilities:** Use `npm audit` or `yarn audit` to identify and fix vulnerabilities in your dependencies. Consider using tools like Snyk or Dependabot for automated vulnerability scanning.
* **Cross-Site Scripting (XSS):** Sanitize user inputs to prevent XSS attacks. Be especially careful when using `dangerouslySetInnerHTML` in React.
* **Security Misconfiguration:** Ensure that your Webpack configuration does not expose sensitive information (e.g., API keys).
### Input Validation
* Validate user inputs on both the client and server sides.
* Use appropriate validation libraries to prevent injection attacks.
### Authentication and Authorization Patterns
* Implement secure authentication and authorization mechanisms.
* Use HTTPS to encrypt communication between the client and server.
* Store sensitive data securely using environment variables and secret management tools.
### Data Protection Strategies
* Encrypt sensitive data at rest and in transit.
* Use secure storage mechanisms to protect user data.
* Follow data privacy regulations (e.g., GDPR, CCPA).
### Secure API Communication
* Use HTTPS for all API communication.
* Implement proper authentication and authorization for API endpoints.
* Validate API responses to prevent data injection.
## 5. Testing Approaches
### Unit Testing Strategies
* Write unit tests for individual modules and components.
* Use testing frameworks like Jest, Mocha, or Jasmine.
* Mock external dependencies to isolate units under test.
### Integration Testing
* Write integration tests to verify the interaction between different modules and components.
* Use tools like Cypress or Puppeteer for end-to-end testing.
### End-to-end Testing
* Write end-to-end tests to simulate user interactions and verify the overall functionality of the application.
* Use testing frameworks like Selenium or Playwright.
### Test Organization
* Organize tests in a clear and consistent manner (e.g., `src/components/Button/Button.test.js`).
* Use descriptive test names.
### Mocking and Stubbing
* Use mocking and stubbing to isolate units under test and simulate external dependencies.
* Use mocking libraries like Jest's `jest.mock()` or Sinon.js.
## 6. Common Pitfalls and Gotchas
### Frequent Mistakes Developers Make
* **Incorrect Loader Configuration:** Double-check the order and configuration of loaders.
* **Missing Dependencies:** Ensure that all required dependencies are installed.
* **Ignoring Cache:** Leverage caching to speed up build times.
* **Not Understanding Context:** Ensure loaders and plugins are applied to the correct files by using `include` and `exclude` options.
### Edge Cases to Be Aware Of
* **Circular Dependencies:** Avoid circular dependencies, which can lead to unexpected behavior.
* **Large Files:** Optimize large files (e.g., images, videos) to reduce bundle size.
* **Conflicting Plugins:** Ensure that plugins do not conflict with each other.
### Version-Specific Issues
* Be aware of breaking changes in Webpack versions.
* Consult the Webpack documentation for version-specific information.
### Compatibility Concerns
* Test your application in different browsers and devices to ensure compatibility.
* Use Babel to transpile your code to older JavaScript versions.
### Debugging Strategies
* Use source maps to debug your code in the browser.
* Use the `console.log` statement to inspect variables and data structures.
* Use the Webpack Dev Server's hot module replacement (HMR) feature for faster development cycles.
## 7. Tooling and Environment
### Recommended Development Tools
* **Code Editor:** VS Code, Sublime Text, Atom
* **Browser:** Chrome, Firefox, Safari
* **Node.js:** Latest LTS version
* **NPM/Yarn:** Package managers
### Build Configuration
* Use separate configuration files for development and production (e.g., `webpack.dev.js`, `webpack.prod.js`).
* Use `webpack-merge` to combine common configurations with environment-specific settings.
### Linting and Formatting
* Use ESLint and Prettier to enforce code style and catch errors early.
* Integrate linting and formatting into your build process.
### Deployment Best Practices
* Use a CI/CD pipeline to automate the deployment process.
* Deploy your application to a production-ready environment (e.g., AWS, Azure, Google Cloud).
* Use a CDN to serve static assets.
### CI/CD Integration
* Integrate Webpack into your CI/CD pipeline to automate the build, test, and deployment processes.
* Use tools like Jenkins, Travis CI, or CircleCI.
* Automate dependency updates using tools like Dependabot.
By following these best practices, you can ensure that your Webpack configurations are robust, performant, and maintainable.
@@ -0,0 +1,261 @@
---
description: This rule provides comprehensive guidelines for GitHub Actions development, covering best practices, coding standards, performance, security, and testing. It aims to ensure efficient, reliable, secure, and maintainable workflows.
globs: .github/workflows/*.yml
---
# GitHub Actions Best Practices and Coding Standards
This guide provides comprehensive guidelines for developing efficient, reliable, secure, and maintainable GitHub Actions workflows. It covers various aspects of GitHub Actions development, including code organization, common patterns, performance considerations, security best practices, testing approaches, and tooling.
## 1. Code Organization and Structure
### 1.1 Directory Structure Best Practices
- **Workflows Directory:** Store all workflow files in the `.github/workflows` directory. This is the standard location recognized by GitHub.
- **Reusable Actions Directory (Optional):** If you create custom reusable actions, consider storing them in a dedicated directory like `actions/` within your repository.
- **Scripts Directory (Optional):** For complex workflows, you might have supporting scripts (e.g., shell scripts, Python scripts). Store these in a `scripts/` directory.
- **Example Directory Structure:**
.github/
└── workflows/
├── main.yml
├── deploy.yml
└── release.yml
actions/
├── my-custom-action/
│ ├── action.yml
│ └── index.js
scripts/
├── cleanup.sh
└── build.py
### 1.2 File Naming Conventions
- **Workflow Files:** Use descriptive and consistent names for workflow files (e.g., `deploy-staging.yml`, `code-analysis.yml`). Avoid generic names like `main.yml` if possible, especially in repositories with multiple workflows.
- **Action Files:** Name action files `action.yml` or `action.yaml` to clearly indicate their purpose.
- **Script Files:** Use appropriate extensions for scripts (e.g., `.sh` for shell scripts, `.py` for Python scripts).
### 1.3 Module Organization
- **Reusable Workflows:** Break down complex workflows into smaller, reusable workflows using the `uses:` syntax. This promotes modularity, reduces duplication, and improves maintainability.
- **Composite Actions:** For reusable steps within a workflow, consider creating composite actions. These group multiple steps into a single action.
- **Modular Scripts:** If you're using scripts, organize them into modules or functions for better readability and reusability.
### 1.4 Component Architecture
- **Workflow as a Component:** Treat each workflow as a self-contained component responsible for a specific task (e.g., building, testing, deploying).
- **Separation of Concerns:** Separate concerns within a workflow. For example, use different jobs for building, testing, and deploying.
- **Inputs and Outputs:** Define clear inputs and outputs for reusable workflows and composite actions to improve their composability.
### 1.5 Code Splitting Strategies
- **Job Splitting:** Divide a workflow into multiple jobs that run in parallel to reduce overall execution time.
- **Step Splitting:** Break down long-running steps into smaller, more manageable steps.
- **Conditional Execution:** Use `if:` conditions to conditionally execute jobs or steps based on specific criteria (e.g., branch name, file changes).
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns Specific to GitHub Actions
- **Fan-out/Fan-in:** Use matrix builds to parallelize testing across different environments, then aggregate the results in a subsequent job.
- **Workflow Orchestration:** Use reusable workflows to orchestrate complex processes involving multiple steps and dependencies.
- **Event-Driven Workflows:** Trigger workflows based on specific GitHub events (e.g., push, pull request, issue creation) to automate tasks.
- **Policy Enforcement:** Implement workflows that enforce coding standards, security policies, or other organizational guidelines.
### 2.2 Recommended Approaches for Common Tasks
- **Dependency Caching:** Use the `actions/cache` action to cache dependencies (e.g., npm packages, Maven artifacts) to speed up subsequent workflow runs.
- **Secret Management:** Store sensitive information (e.g., API keys, passwords) as GitHub Secrets and access them in your workflows using the `${{ secrets.SECRET_NAME }}` syntax. Never hardcode secrets in your workflow files.
- **Artifact Storage:** Use the `actions/upload-artifact` and `actions/download-artifact` actions to store and retrieve build artifacts (e.g., compiled binaries, test reports).
- **Environment Variables:** Use environment variables to configure workflows and steps. Set environment variables at the workflow, job, or step level.
- **Workflow Status Badges:** Add workflow status badges to your repository's README file to provide a visual indication of the workflow's health.
### 2.3 Anti-patterns and Code Smells to Avoid
- **Hardcoding Secrets:** Never hardcode secrets directly in your workflow files. Use GitHub Secrets instead.
- **Ignoring Errors:** Don't ignore errors or warnings in your workflows. Implement proper error handling to ensure workflows fail gracefully.
- **Overly Complex Workflows:** Avoid creating overly complex workflows that are difficult to understand and maintain. Break them down into smaller, reusable workflows.
- **Lack of Testing:** Don't skip testing your workflows. Implement unit tests, integration tests, and end-to-end tests to ensure they function correctly.
- **Unnecessary Dependencies:** Avoid including unnecessary dependencies in your workflows. This can increase build times and introduce security vulnerabilities.
- **Directly Modifying `GITHUB_PATH` or `GITHUB_ENV`:** While these environment variables exist, using the recommended step outputs is preferred for cleaner, more robust interaction with other steps.
### 2.4 State Management Best Practices
- **Artifacts:** Use artifacts for persisting files between jobs. Upload at the end of one job, download at the start of another.
- **Environment Variables:** Define environment variables at the workflow or job level to pass configuration settings between steps.
- **Outputs:** Use step outputs to pass data between steps within a job.
- **GitHub API:** Use the GitHub API to store and retrieve data related to your workflows (e.g., workflow run status, deployment information).
- **External Databases:** For more complex state management requirements, consider using an external database.
### 2.5 Error Handling Patterns
- **`if: always()`:** Ensures a step runs even if a previous step failed, useful for cleanup or notification tasks. `if: always()` should be used with caution, as it can mask underlying issues.
- **`continue-on-error: true`:** Allows a job to continue even if a step fails. This is useful for non-critical steps or when you want to collect information about multiple failures before failing the workflow.
- **`try...catch...finally` (within Scripts):** Use `try...catch...finally` blocks in your scripts to handle exceptions and ensure proper cleanup.
- **Notifications:** Send notifications (e.g., email, Slack) when workflows fail or succeed to keep stakeholders informed.
- **Workflow Retries:** Consider using the `retry:` keyword to automatically retry failed jobs.
## 3. Performance Considerations
### 3.1 Optimization Techniques
- **Caching:** Use the `actions/cache` action aggressively to cache dependencies and intermediate build artifacts.
- **Concurrency:** Use concurrency to prevent multiple workflows from running at the same time.
- **Parallel Execution:** Run jobs in parallel to reduce overall execution time.
- **Optimized Images:** Optimize images before uploading them to your repository to reduce their size.
- **Minify Code:** Minify JavaScript and CSS files to reduce their size.
### 3.2 Memory Management
- **Resource Limits:** Be aware of the resource limits imposed by GitHub Actions runners. Monitor memory and CPU usage to prevent workflows from exceeding these limits.
- **Garbage Collection:** Ensure that your scripts and actions properly manage memory and avoid memory leaks.
- **Large Datasets:** If you're processing large datasets, consider using streaming techniques or splitting the data into smaller chunks.
### 3.3 Rendering Optimization
- N/A - Not typically relevant for GitHub Actions workflows themselves, but may be applicable to applications built and deployed by workflows.
### 3.4 Bundle Size Optimization
- N/A - Not typically relevant for GitHub Actions workflows themselves, but may be applicable to applications built and deployed by workflows.
### 3.5 Lazy Loading Strategies
- N/A - Not typically relevant for GitHub Actions workflows themselves, but may be applicable to applications built and deployed by workflows.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities and How to Prevent Them
- **Code Injection:** Prevent code injection by validating all inputs and sanitizing data before using it in scripts or commands.
- **Secret Exposure:** Avoid exposing secrets in logs or error messages. Mask secrets using the `::add-mask::` command.
- **Third-Party Actions:** Carefully vet third-party actions before using them in your workflows. Pin actions to specific versions or commits to prevent unexpected changes.
- **Privilege Escalation:** Run workflows with the least privileges necessary to perform their tasks.
- **Workflow Command Injection:** Be cautious when dynamically constructing commands. If possible, use parameters or environment variables instead of concatenating strings.
### 4.2 Input Validation
- **Validate Inputs:** Validate all inputs to your workflows and actions to prevent malicious data from being processed.
- **Data Sanitization:** Sanitize data before using it in scripts or commands to prevent code injection vulnerabilities.
- **Regular Expressions:** Use regular expressions to validate the format of inputs.
### 4.3 Authentication and Authorization Patterns
- **GitHub Tokens:** Use GitHub tokens to authenticate with the GitHub API. Grant tokens the minimum necessary permissions.
- **Service Accounts:** Use service accounts to authenticate with external services. Store service account credentials as GitHub Secrets.
- **Role-Based Access Control (RBAC):** Implement RBAC to control access to your workflows and actions.
### 4.4 Data Protection Strategies
- **Encryption:** Encrypt sensitive data at rest and in transit.
- **Data Masking:** Mask sensitive data in logs and error messages.
- **Data Retention:** Establish a data retention policy to ensure that sensitive data is not stored indefinitely.
### 4.5 Secure API Communication
- **HTTPS:** Use HTTPS for all API communication.
- **TLS:** Use TLS encryption to protect data in transit.
- **API Keys:** Protect API keys and other credentials. Store them as GitHub Secrets and use them securely in your workflows.
- **Rate Limiting:** Implement rate limiting to prevent abuse of your APIs.
## 5. Testing Approaches
### 5.1 Unit Testing Strategies
- **Test Reusable Actions:** Unit test your custom reusable actions to ensure they function correctly.
- **Test Scripts:** Unit test your scripts to ensure they handle different inputs and edge cases correctly.
- **Mock Dependencies:** Use mocking to isolate units of code and test them in isolation.
### 5.2 Integration Testing
- **Test Workflow Integration:** Integrate test your workflows to ensure that all components work together correctly.
- **Test API Integrations:** Test your integrations with external APIs to ensure they function correctly.
- **Test Database Integrations:** Test your integrations with databases to ensure data is read and written correctly.
### 5.3 End-to-end Testing
- **Full Workflow Tests:** Run end-to-end tests to verify that your workflows function correctly from start to finish.
- **Simulate Real-World Scenarios:** Simulate real-world scenarios to ensure that your workflows can handle different situations.
### 5.4 Test Organization
- **Dedicated Test Directory:** Create a dedicated `tests/` directory for your tests.
- **Test Naming Conventions:** Follow consistent naming conventions for your test files and functions.
- **Test Suites:** Organize your tests into test suites based on functionality or component.
### 5.5 Mocking and Stubbing
- **Mock External Services:** Mock external services to isolate your tests from external dependencies.
- **Stub Functions:** Stub functions to control the behavior of dependencies during testing.
- **Mock GitHub API:** Mock the GitHub API to test your workflows without making real API calls.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes Developers Make
- **Incorrect Syntax:** YAML syntax can be tricky. Use a linter or validator to catch syntax errors.
- **Incorrect Indentation:** Indentation is crucial in YAML. Use consistent indentation throughout your workflow files.
- **Missing Permissions:** Grant workflows the necessary permissions to access resources (e.g., repository contents, secrets).
- **Typos in Secrets:** Double-check the names of your secrets to avoid typos.
- **Not Pinning Action Versions:** Always pin actions to specific versions or commits to prevent unexpected changes.
### 6.2 Edge Cases to Be Aware Of
- **Rate Limits:** Be aware of GitHub API rate limits. Implement retry logic to handle rate limit errors.
- **Concurrent Workflow Runs:** Handle concurrent workflow runs gracefully to avoid conflicts.
- **Network Issues:** Implement error handling to handle network issues and transient errors.
- **Large File Sizes:** Be aware of the maximum file sizes supported by GitHub Actions.
### 6.3 Version-Specific Issues
- **Action Compatibility:** Ensure that your actions are compatible with the version of GitHub Actions you are using.
- **Runner Images:** Be aware of the changes in runner images and update your workflows accordingly.
### 6.4 Compatibility Concerns
- **Cross-Platform Compatibility:** Ensure that your workflows are compatible with different operating systems (e.g., Linux, Windows, macOS).
- **Browser Compatibility:** If your workflows involve web applications, test them in different browsers.
### 6.5 Debugging Strategies
- **Workflow Logs:** Examine workflow logs to identify errors and warnings.
- **Debugging Actions:** Use debugging actions to inspect the state of your workflows.
- **Step-by-Step Debugging:** Insert `echo` statements or debugging actions to trace the execution of your workflows step by step.
- **Local Testing:** Use tools like `act` to test your workflows locally before pushing them to GitHub.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
- **VS Code with GitHub Actions Extension:** Use VS Code with the GitHub Actions extension for syntax highlighting, code completion, and validation.
- **GitHub CLI:** Use the GitHub CLI to interact with the GitHub API from your workflows.
- **`act`:** Use `act` to test your workflows locally.
- **YAML Linter:** Use a YAML linter to catch syntax errors in your workflow files.
### 7.2 Build Configuration
- **`.github/workflows/`:** Place all workflow files in this directory.
- **`action.yml`:** For reusable actions, define their metadata in this file.
### 7.3 Linting and Formatting
- **YAML Lint:** Use a YAML linting tool to enforce consistent formatting and catch syntax errors.
- **Shellcheck:** Use Shellcheck to lint your shell scripts.
- **Prettier:** Use Prettier to format your JavaScript and CSS files.
### 7.4 Deployment Best Practices
- **Environment Variables:** Use environment variables to configure your deployments.
- **Deployment Strategies:** Use appropriate deployment strategies (e.g., blue/green deployment, canary deployment) to minimize downtime.
- **Rollback Strategies:** Implement rollback strategies to revert to a previous version if a deployment fails.
### 7.5 CI/CD Integration
- **Continuous Integration (CI):** Run automated tests on every commit to ensure code quality.
- **Continuous Delivery (CD):** Automate the deployment process to deliver new features and bug fixes to users quickly.
- **Automated Releases:** Automate the release process to create and publish releases automatically.
## Conclusion
By following these best practices and coding standards, you can create efficient, reliable, secure, and maintainable GitHub Actions workflows. Remember to adapt these guidelines to your specific needs and context. Continuously review and improve your workflows to ensure they meet your evolving requirements.
@@ -0,0 +1,217 @@
---
description: This rule file provides comprehensive guidance on Docker best practices, covering Dockerfile construction, image optimization, and security considerations. It aims to improve the efficiency, maintainability, and security of Docker-based projects.
globs: **/{Dockerfile,docker-compose.yml,*.dockerfile}
---
# Docker Best Practices
This document provides comprehensive guidance on Docker best practices, covering Dockerfile construction, image optimization, security considerations, and more. It aims to improve the efficiency, maintainability, and security of Docker-based projects.
## 1. Code Organization and Structure
- **Directory Structure Best Practices:**
- Organize your project with a clear separation of concerns. For example:
project-root/
├── Dockerfile # Dockerfile for building the image
├── docker-compose.yml # Docker Compose file for multi-container setup
├── .dockerignore # Specifies intentionally untracked files that Docker should ignore
├── app/ # Application source code
│ ├── ...
├── config/ # Configuration files
│ ├── ...
├── data/ # Data files (if any, though consider volumes)
│ ├── ...
├── scripts/ # Scripts for building, deploying, or managing the container
│ ├── ...
- Keep the `Dockerfile` and `docker-compose.yml` at the root of your project for easy access.
- **File Naming Conventions:**
- Use descriptive names for your Dockerfiles (e.g., `Dockerfile.web`, `Dockerfile.api`).
- Follow a consistent naming convention for all files and directories.
- **Module Organization:**
- Structure your application into modular components to improve reusability and maintainability. This directly affects what goes into a docker image.
- Use appropriate build tools (e.g., Maven, Gradle, npm) to manage dependencies and package your application.
- **Component Architecture:**
- Design your application as a set of microservices or components, each running in its own container, when appropriate.
- Use Docker Compose to orchestrate multi-container applications.
- **Code Splitting Strategies:**
- Break down large applications into smaller, more manageable parts to reduce image size and improve build times.
- Consider multi-stage builds to include build-time dependencies in one stage and only the runtime dependencies in the final image.
## 2. Common Patterns and Anti-patterns
- **Design Patterns Specific to Docker:**
- **Sidecar Pattern:** Run a utility container alongside your main application container (e.g., for logging, monitoring).
- **Ambassador Pattern:** Proxy requests to a service running outside the container.
- **Adapter Pattern:** Adapt the interface of a service to match the expected interface of a client.
- **Init Container Pattern:** Run initialization tasks before the main application container starts. Often used to set up configuration, prepare databases, etc.
- **Recommended Approaches for Common Tasks:**
- **Configuration Management:** Use environment variables to configure your application.
- **Logging:** Centralize logging using a logging driver or a dedicated logging container (e.g., Fluentd, Logstash).
- **Health Checks:** Implement health checks to ensure that your services are running correctly.
- **Process Management:** Use a process manager (e.g., `tini`, `dumb-init`) to handle signal forwarding and zombie process reaping.
- **Anti-patterns and Code Smells to Avoid:**
- **Storing secrets in Dockerfile or images:** Never hardcode passwords or API keys in your Dockerfile.
- **Running services as root:** Avoid running your application as the root user.
- **Installing unnecessary packages:** Keep your images lean by only installing the required dependencies.
- **Ignoring `.dockerignore`:** Make sure to use `.dockerignore` to exclude unnecessary files from the build context, reducing image size and build time.
- **Using `ADD` instead of `COPY` unnecessarily:** `COPY` is usually more transparent and predictable.
- **State Management Best Practices:**
- **Stateless Applications:** Design your application to be stateless whenever possible.
- **Volumes:** Use volumes for persistent storage (e.g., databases, logs).
- **Bind Mounts:** Use bind mounts for development to allow code changes to be reflected immediately in the container.
- **Error Handling Patterns:**
- Implement robust error handling in your application.
- Use appropriate logging levels to capture errors and warnings.
- Implement retry mechanisms for transient errors.
- Monitor your application for errors and take corrective actions.
## 3. Performance Considerations
- **Optimization Techniques:**
- **Multi-stage builds:** Use multi-stage builds to create smaller, more efficient images.
- **Minimize layers:** Combine multiple commands into a single layer using `&&`.
- **Use a lightweight base image:** Choose a minimal base image like Alpine Linux.
- **Optimize caching:** Order your Dockerfile commands to maximize cache reuse.
- **Memory Management:**
- Set memory limits for your containers to prevent them from consuming excessive resources.
- Monitor memory usage and optimize your application accordingly.
- **Rendering Optimization (if applicable):**
- If your application involves rendering, optimize the rendering process (e.g., using caching, lazy loading).
- **Bundle Size Optimization:**
- Minimize the size of your application bundle by removing unnecessary dependencies and assets.
- Use tools like webpack or Parcel to optimize your bundle.
- **Lazy Loading Strategies:**
- Implement lazy loading for resources that are not immediately needed.
## 4. Security Best Practices
- **Common Vulnerabilities and How to Prevent Them:**
- **Image vulnerabilities:** Regularly scan your images for vulnerabilities using tools like Clair or Trivy.
- **Configuration vulnerabilities:** Secure your container configurations to prevent unauthorized access.
- **Network vulnerabilities:** Limit network exposure and use network policies to isolate containers.
- **Privilege escalation:** Avoid running containers with unnecessary privileges.
- **Input Validation:**
- Validate all input data to prevent injection attacks.
- **Authentication and Authorization Patterns:**
- Implement robust authentication and authorization mechanisms.
- Use secure protocols like HTTPS.
- Store secrets securely using tools like HashiCorp Vault or Kubernetes Secrets.
- **Data Protection Strategies:**
- Encrypt sensitive data at rest and in transit.
- Use appropriate access control mechanisms to protect data.
- **Secure API Communication:**
- Use secure protocols like HTTPS for API communication.
- Implement authentication and authorization for API endpoints.
- Rate limit API requests to prevent abuse.
## 5. Testing Approaches
- **Unit Testing Strategies:**
- Write unit tests to verify the functionality of individual components.
- Use mocking and stubbing to isolate components during testing.
- **Integration Testing:**
- Write integration tests to verify the interaction between different components.
- Test the integration with external services and databases.
- **End-to-end Testing:**
- Write end-to-end tests to verify the entire application flow.
- Use tools like Selenium or Cypress to automate end-to-end tests.
- **Test Organization:**
- Organize your tests into a clear and maintainable structure.
- Use descriptive names for your test cases.
- **Mocking and Stubbing:**
- Use mocking and stubbing to isolate components during testing.
- Mock external services and databases to simulate different scenarios.
## 6. Common Pitfalls and Gotchas
- **Frequent Mistakes Developers Make:**
- **Not using `.dockerignore`:** This can lead to large image sizes and slow build times.
- **Not pinning package versions:** This can lead to unexpected build failures due to dependency updates.
- **Exposing unnecessary ports:** This can increase the attack surface of your application.
- **Not cleaning up after installing packages:** This can lead to larger image sizes.
- **Using the shell form of `CMD` or `ENTRYPOINT`:** Use the exec form (`["executable", "param1", "param2"]`) to avoid shell injection vulnerabilities and signal handling issues.
- **Edge Cases to Be Aware Of:**
- **File permissions:** Ensure that your application has the correct file permissions.
- **Timezone configuration:** Configure the correct timezone for your container.
- **Resource limits:** Set appropriate resource limits for your containers.
- **Version-Specific Issues:**
- Be aware of version-specific issues and compatibility concerns.
- Test your application with different Docker versions to ensure compatibility.
- **Compatibility Concerns:**
- Ensure that your application is compatible with the base image you are using.
- Test your application on different platforms to ensure cross-platform compatibility.
- **Debugging Strategies:**
- Use `docker logs` to view container logs.
- Use `docker exec` to execute commands inside a running container.
- Use `docker inspect` to inspect container metadata.
- Use a debugger to debug your application code.
## 7. Tooling and Environment
- **Recommended Development Tools:**
- **Docker Desktop:** For local development and testing.
- **Docker Compose:** For orchestrating multi-container applications.
- **Visual Studio Code with Docker extension:** For enhanced Docker development experience.
- **Container image scanners (e.g., Trivy, Clair):** For identifying vulnerabilities in container images.
- **Build Configuration:**
- Use a consistent build configuration for all your images.
- Automate the build process using a build tool (e.g., Make, Gradle).
- **Linting and Formatting:**
- Use a linter to enforce code style and best practices.
- Use a formatter to automatically format your code.
- **Deployment Best Practices:**
- Use a container orchestration platform like Kubernetes or Docker Swarm.
- Implement rolling updates and rollbacks.
- Monitor your application for performance and availability.
- **CI/CD Integration:**
- Integrate Docker into your CI/CD pipeline.
- Automate the build, test, and deployment process.
- Use tools like Jenkins, GitLab CI, or CircleCI.
---
## Additional Notes:
- Always use a specific tag for the base image (e.g., `ubuntu:20.04`) instead of `latest` to ensure reproducibility.
- Use `.dockerignore` to exclude files and directories that are not needed in the image. This reduces the image size and improves build performance.
- When possible, use the official Docker images from Docker Hub. They are usually well-maintained and optimized.
- Consider using a tool like `docker-slim` to further reduce the size of your Docker images by removing unnecessary files and dependencies after the build process.
- Understand the Docker build context and ensure you're only including necessary files and directories. A large build context slows down builds and increases image sizes.
- Regularly update your base images to patch security vulnerabilities.
- Use environment variables to configure your application, making it more flexible and portable.
- Implement health checks in your Dockerfiles to ensure that your containers are running correctly. This can be done using the `HEALTHCHECK` instruction.
- Consider using a private Docker registry to store your images securely.
- Document your Dockerfiles and images to make them easier to understand and maintain.
- Review your Dockerfiles regularly to ensure they are up-to-date and following best practices.
- Consider using a Dockerfile linter like `hadolint` to identify potential issues and enforce best practices.
By following these guidelines, you can create efficient, maintainable, and secure Docker-based applications.
@@ -0,0 +1,353 @@
---
description: This rule provides comprehensive best practices for developing and maintaining Kubernetes applications and infrastructure, covering coding standards, security, performance, testing, and deployment.
globs: **/*.{go,yaml,yml,sh,tf,tfvars,json}
---
# Kubernetes Development and Operations Best Practices
This document outlines a collection of guidelines, style suggestions, and tips for writing code and managing infrastructure within the Kubernetes ecosystem. It emphasizes clarity, maintainability, security, and performance.
## 1. Code Organization and Structure
### 1.1 Directory Structure
- **Root Level:**
- `cmd/`: Main application entry points. Each subdirectory represents a separate command-line tool or service.
- `pkg/`: Reusable libraries and components that can be imported by other projects.
- `internal/`: Private code that should not be imported by external projects. Enforces encapsulation.
- `api/`: API definitions, including protobuf files and OpenAPI specifications.
- `config/`: Configuration files, such as YAML manifests, Kustomize configurations, and Helm charts.
- `scripts/`: Utility scripts for building, testing, and deploying the application.
- `docs/`: Documentation for the project.
- `examples/`: Example usage of the library or application.
- `vendor/`: (If using `go modules` without external dependency management) Contains vendored dependencies. Generally discouraged in modern Go with `go modules`.
- **Component-Specific Directories:** Inside `pkg/` or `internal/`, organize code by component or module. Each component should have its own directory with clear separation of concerns.
Example:
my-kubernetes-project/
├── cmd/
│ └── controller/
│ └── main.go
├── pkg/
│ └── api/
│ ├── types.go
│ └── controller/
│ ├── controller.go
│ ├── reconciler.go
│ └── util/
│ └── util.go
├── internal/
│ └── admission/
│ └── webhook.go
├── config/
│ ├── deploy/
│ │ └── deployment.yaml
│ └── kustomize/
│ ├── base/
│ │ ├── kustomization.yaml
│ │ └── ...
│ └── overlays/
│ ├── dev/
│ │ ├── kustomization.yaml
│ │ └── ...
│ └── prod/
│ ├── kustomization.yaml
│ └── ...
├── scripts/
│ └── build.sh
├── docs/
│ └── architecture.md
└── go.mod
### 1.2 File Naming Conventions
- **Go Files:** Use lowercase with underscores (e.g., `my_controller.go`).
- **YAML Files:** Use lowercase with dashes (e.g., `deployment.yaml`).
- **Configuration Files:** Be descriptive and consistent (e.g., `config.yaml`, `kustomization.yaml`).
- **Test Files:** Follow the standard Go convention: `*_test.go` (e.g., `my_controller_test.go`).
### 1.3 Module Organization (Go)
- **Packages:** Organize code into meaningful packages that represent logical units of functionality.
- **Internal Packages:** Use `internal/` directories to create packages that are only visible within the project.
- **Interfaces:** Define interfaces to abstract dependencies and promote testability.
### 1.4 Component Architecture
- **Microservices:** Design applications as a collection of loosely coupled microservices.
- **Separation of Concerns:** Each component should have a single responsibility and well-defined interfaces.
- **API Gateway:** Use an API gateway to handle routing, authentication, and rate limiting for external requests.
- **Service Mesh:** Consider using a service mesh (e.g., Istio, Linkerd) to manage inter-service communication, observability, and security.
### 1.5 Code Splitting Strategies
- **Feature-Based Splitting:** Group code by feature or functionality.
- **Layer-Based Splitting:** Separate code into layers, such as data access, business logic, and presentation.
- **Component-Based Splitting:** Divide code into reusable components that can be shared across multiple projects.
## 2. Common Patterns and Anti-Patterns
### 2.1 Design Patterns
- **Controller Pattern:** Implement controllers to reconcile the desired state of Kubernetes resources with the actual state.
- **Operator Pattern:** Extend the Kubernetes API with custom resources and controllers to automate complex application management tasks.
- **Sidecar Pattern:** Deploy a sidecar container alongside the main application container to provide supporting functionality, such as logging, monitoring, or security.
- **Ambassador Pattern:** Use an ambassador container to proxy network traffic to the main application container, providing features such as load balancing, routing, and authentication.
- **Adapter Pattern:** Translate requests from one interface to another, allowing different components to work together.
- **Singleton Pattern:** Implement a singleton pattern for managing global resources, such as database connections or configuration settings. Be extremely cautious, as this can hurt testability and introduce implicit dependencies.
### 2.2 Recommended Approaches for Common Tasks
- **Resource Management:** Use Kubernetes resource requests and limits to ensure that applications have sufficient resources and prevent resource contention.
- **Configuration Management:** Use ConfigMaps and Secrets to manage configuration data and sensitive information separately from the application code.
- **Service Discovery:** Use Kubernetes services to provide a stable endpoint for accessing applications, even when pods are scaled up or down.
- **Health Checks:** Implement liveness and readiness probes to monitor the health of applications and automatically restart unhealthy pods.
- **Logging and Monitoring:** Use a centralized logging and monitoring system to collect and analyze application logs and metrics.
- **Rolling Updates:** Use Kubernetes deployments to perform rolling updates of applications with zero downtime.
### 2.3 Anti-Patterns and Code Smells
- **Naked Pods:** Avoid creating pods directly without a deployment or replica set, as they will not be automatically rescheduled if a node fails.
- **Hardcoded Configuration:** Avoid hardcoding configuration data in the application code. Use ConfigMaps and Secrets instead.
- **Ignoring Resource Limits:** Failing to set resource requests and limits can lead to resource contention and performance issues.
- **Oversized Containers:** Keep container images small and focused to improve startup time and reduce security risks.
- **Privileged Containers:** Avoid running containers in privileged mode, as it can create security vulnerabilities.
- **Long-Lived Branches:** Avoid creating long-lived branches, and prefer small, frequent merges to the main branch.
- **God Classes:** Avoid creating classes that are too large and complex. Break them down into smaller, more manageable classes.
- **Shotgun Surgery:** Avoid making changes to multiple classes when a single feature is modified. This suggests poor class design and coupling.
- **Feature Envy:** Avoid methods that access the data of another object more than their own. This suggests that the method might be in the wrong class.
### 2.4 State Management Best Practices
- **Stateless Applications:** Prefer stateless applications whenever possible, as they are easier to scale and manage.
- **Persistent Volumes:** Use Persistent Volumes to store persistent data for stateful applications.
- **External Databases:** Consider using external databases for managing application state, such as databases hosted on cloud providers.
- **Kubernetes Operators:** Implement Kubernetes operators to automate the management of stateful applications.
- **Etcd:** Understand the importance of etcd as Kubernetes' data store and protect it accordingly.
### 2.5 Error Handling Patterns
- **Centralized Error Handling:** Implement a centralized error handling mechanism to handle exceptions and log errors consistently.
- **Retry Mechanism:** Implement a retry mechanism to automatically retry failed operations.
- **Circuit Breaker Pattern:** Use a circuit breaker pattern to prevent cascading failures in distributed systems.
- **Logging Error Details:** Log detailed error messages, including stack traces and relevant context, to help with debugging.
- **Graceful Degradation:** Design applications to gracefully degrade functionality when errors occur.
- **Alerting on Critical Errors:** Set up alerts to notify administrators when critical errors occur.
## 3. Performance Considerations
### 3.1 Optimization Techniques
- **Caching:** Implement caching to reduce latency and improve performance.
- **Load Balancing:** Use load balancing to distribute traffic across multiple instances of an application.
- **Connection Pooling:** Use connection pooling to reuse database connections and reduce overhead.
- **Compression:** Use compression to reduce the size of data transmitted over the network.
- **Gzip:** Enable Gzip compression in web servers to reduce the size of HTTP responses.
### 3.2 Memory Management
- **Memory Profiling:** Use memory profiling tools to identify memory leaks and optimize memory usage.
- **Garbage Collection:** Understand how garbage collection works in the programming language used for the application.
- **Resource Limits:** Set memory resource limits for containers to prevent them from consuming excessive memory.
- **Monitor Memory Usage:** Monitor memory usage regularly to identify potential issues.
### 3.3 Rendering Optimization
- **Minimize DOM Manipulation:** Reduce the number of DOM manipulations to improve rendering performance in web applications.
- **Virtual DOM:** Use a virtual DOM to optimize rendering updates in web applications.
- **Lazy Loading:** Use lazy loading to load images and other resources only when they are needed.
### 3.4 Bundle Size Optimization
- **Code Minification:** Use code minification to reduce the size of JavaScript and CSS files.
- **Tree Shaking:** Use tree shaking to remove unused code from JavaScript bundles.
- **Image Optimization:** Optimize images to reduce their file size without sacrificing quality.
- **Code Splitting:** Split the application code into smaller bundles that can be loaded on demand.
### 3.5 Lazy Loading Strategies
- **On-Demand Loading:** Load resources only when they are needed by the application.
- **Intersection Observer:** Use the Intersection Observer API to detect when elements are visible in the viewport and load them accordingly.
- **Placeholder Images:** Use placeholder images while loading the actual images to improve the user experience.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities and How to Prevent Them
- **Injection Attacks:** Prevent injection attacks by validating and sanitizing all user input.
- **Cross-Site Scripting (XSS):** Prevent XSS attacks by escaping all user-generated content before rendering it in the browser.
- **Cross-Site Request Forgery (CSRF):** Prevent CSRF attacks by using anti-CSRF tokens.
- **Authentication and Authorization Flaws:** Implement robust authentication and authorization mechanisms to protect sensitive data and resources.
- **Security Misconfiguration:** Avoid using default configurations and ensure that all components are properly configured with security in mind.
- **Using Components with Known Vulnerabilities:** Keep all dependencies up to date to patch known vulnerabilities.
- **Insufficient Logging and Monitoring:** Implement comprehensive logging and monitoring to detect and respond to security incidents.
- **Container Security:** Follow best practices for securing containers, such as using minimal images, running as non-root, and limiting capabilities.
- **Network Policies:** Use network policies to restrict network traffic between pods.
- **RBAC (Role-Based Access Control):** Implement RBAC to control access to Kubernetes resources.
- **Secrets Management:** Use Kubernetes Secrets to store sensitive information, and encrypt secrets at rest.
- **Pod Security Policies/Pod Security Standards:** Enforce Pod Security Standards to restrict the capabilities of pods.
### 4.2 Input Validation
- **Validate All Input:** Validate all input, including user input, API requests, and configuration data.
- **Use Strong Data Types:** Use strong data types to enforce data integrity.
- **Sanitize Input:** Sanitize input to remove potentially harmful characters and prevent injection attacks.
- **Whitelist Input:** Use a whitelist approach to only allow known good input.
- **Blacklist Input:** Avoid using a blacklist approach, as it can be easily bypassed.
### 4.3 Authentication and Authorization Patterns
- **Multi-Factor Authentication (MFA):** Use MFA to enhance authentication security.
- **OAuth 2.0:** Use OAuth 2.0 for authorization and delegation of access.
- **JSON Web Tokens (JWT):** Use JWTs for securely transmitting claims between parties.
- **Role-Based Access Control (RBAC):** Implement RBAC to control access to resources based on roles.
- **Least Privilege Principle:** Grant users and applications only the minimum necessary permissions.
### 4.4 Data Protection Strategies
- **Encryption at Rest:** Encrypt sensitive data at rest to protect it from unauthorized access.
- **Encryption in Transit:** Encrypt sensitive data in transit using HTTPS or other secure protocols.
- **Data Masking:** Mask sensitive data to prevent it from being exposed to unauthorized users.
- **Data Anonymization:** Anonymize data to remove personally identifiable information (PII).
- **Data Loss Prevention (DLP):** Implement DLP measures to prevent sensitive data from leaving the organization.
### 4.5 Secure API Communication
- **HTTPS:** Use HTTPS for all API communication to encrypt data in transit.
- **API Authentication:** Implement API authentication to verify the identity of clients.
- **API Authorization:** Implement API authorization to control access to API endpoints.
- **Rate Limiting:** Implement rate limiting to prevent abuse and denial-of-service attacks.
- **Input Validation:** Validate all API requests to prevent injection attacks and other vulnerabilities.
## 5. Testing Approaches
### 5.1 Unit Testing Strategies
- **Test-Driven Development (TDD):** Write unit tests before writing the application code.
- **Mock Dependencies:** Use mocks to isolate the unit being tested from its dependencies.
- **Test Boundary Conditions:** Test boundary conditions and edge cases to ensure that the code handles them correctly.
- **Test Error Conditions:** Test error conditions to ensure that the code handles errors gracefully.
- **Code Coverage:** Aim for high code coverage to ensure that all parts of the code are tested.
- **Table-Driven Tests:** Use table-driven tests to easily test multiple inputs and outputs.
### 5.2 Integration Testing
- **Test Interactions Between Components:** Test the interactions between different components of the application.
- **Test with Real Dependencies:** Use real dependencies or integration mocks for integration tests.
- **Test Data Flows:** Test the data flows through the application to ensure that data is processed correctly.
- **Contract Tests:** Use contract tests to ensure that services adhere to a defined contract.
### 5.3 End-to-End Testing
- **Test the Entire System:** Test the entire system from end to end to ensure that all components work together correctly.
- **Automate End-to-End Tests:** Automate end-to-end tests to ensure that they are run regularly.
- **Use Realistic Test Data:** Use realistic test data to simulate real-world scenarios.
- **CI/CD Integration:** Integrate end-to-end tests into the CI/CD pipeline.
### 5.4 Test Organization
- **Keep Tests Separate from Code:** Keep tests separate from the application code in a dedicated `test/` directory.
- **Organize Tests by Component:** Organize tests by component or module to make them easier to find and maintain.
- **Use Clear Naming Conventions:** Use clear naming conventions for test files and test functions.
### 5.5 Mocking and Stubbing
- **Use Mocking Frameworks:** Use mocking frameworks to simplify the creation of mocks and stubs.
- **Mock External Dependencies:** Mock external dependencies, such as databases and APIs, to isolate the unit being tested.
- **Stub Responses:** Use stubs to provide predefined responses for external dependencies.
- **Verify Interactions:** Verify that the code under test interacts with dependencies as expected.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes Developers Make
- **Ignoring Error Handling:** Failing to handle errors properly can lead to unexpected behavior and crashes.
- **Not Using Version Control:** Not using version control can lead to lost code and conflicts.
- **Hardcoding Configuration:** Hardcoding configuration data can make it difficult to deploy the application in different environments.
- **Not Securing Sensitive Data:** Not securing sensitive data can lead to security breaches.
- **Not Testing Thoroughly:** Not testing thoroughly can lead to bugs and performance issues.
- **Over-Engineering:** Adding unnecessary complexity to the code can make it difficult to understand and maintain.
- **Premature Optimization:** Optimizing code before it is necessary can waste time and make the code harder to read.
- **Not Documenting Code:** Not documenting code can make it difficult for others to understand and maintain it.
### 6.2 Edge Cases to Be Aware Of
- **Network Connectivity Issues:** Handle network connectivity issues gracefully.
- **Resource Exhaustion:** Handle resource exhaustion gracefully.
- **Concurrency Issues:** Avoid concurrency issues by using proper synchronization mechanisms.
- **Data Corruption:** Protect against data corruption by using checksums and other data integrity techniques.
- **Time Zone Issues:** Be aware of time zone issues when working with dates and times.
### 6.3 Version-Specific Issues
- **API Version Compatibility:** Be aware of API version compatibility issues when upgrading Kubernetes or other dependencies.
- **Feature Deprecation:** Be aware of feature deprecation when upgrading Kubernetes or other dependencies.
- **Configuration Changes:** Be aware of configuration changes when upgrading Kubernetes or other dependencies.
### 6.4 Compatibility Concerns
- **Operating System Compatibility:** Ensure that the application is compatible with the target operating systems.
- **Architecture Compatibility:** Ensure that the application is compatible with the target architectures (e.g., x86, ARM).
- **Browser Compatibility:** Ensure that web applications are compatible with the target browsers.
### 6.5 Debugging Strategies
- **Logging:** Use detailed logging to help identify the root cause of issues.
- **Debugging Tools:** Use debugging tools, such as debuggers and profilers, to analyze the code and identify performance bottlenecks.
- **Remote Debugging:** Use remote debugging to debug applications running in Kubernetes.
- **Log Aggregation:** Use log aggregation tools (e.g., Elasticsearch, Loki) to centralize and analyze logs.
- **Metrics Monitoring:** Use metrics monitoring tools (e.g., Prometheus, Grafana) to track application performance.
- **Tracing:** Implement distributed tracing (e.g., Jaeger, Zipkin) to track requests across multiple services.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
- **IDE:** Use a modern IDE with support for the programming language used for the application (e.g., VS Code, IntelliJ IDEA, GoLand).
- **Kubectl:** Use `kubectl` for interacting with Kubernetes clusters.
- **Minikube/Kind:** Use Minikube or Kind for local Kubernetes development.
- **Helm:** Use Helm for managing Kubernetes packages.
- **Kustomize:** Use Kustomize for customizing Kubernetes configurations.
- **Docker:** Use Docker for building and managing container images.
- **Tilt:** Use Tilt for fast, local Kubernetes development.
- **Skaffold:** Use Skaffold for automated build, push, and deploy workflows.
- **Telepresence:** Use Telepresence to debug applications running in Kubernetes from your local machine.
### 7.2 Build Configuration
- **Makefile:** Use a Makefile to automate common build tasks.
- **CI/CD Pipeline:** Integrate the build process into a CI/CD pipeline.
- **Dependency Management:** Use a dependency management tool, such as `go modules`, to manage dependencies.
- **Version Control:** Use version control to track changes to the build configuration.
### 7.3 Linting and Formatting
- **Linters:** Use linters to enforce code style and best practices (e.g., `golangci-lint`, `eslint`, `stylelint`).
- **Formatters:** Use formatters to automatically format code according to a predefined style (e.g., `go fmt`, `prettier`).
- **Pre-Commit Hooks:** Use pre-commit hooks to run linters and formatters before committing code.
### 7.4 Deployment Best Practices
- **Infrastructure as Code (IaC):** Use IaC tools, such as Terraform or CloudFormation, to manage infrastructure.
- **Immutable Infrastructure:** Deploy immutable infrastructure to ensure consistency and repeatability.
- **Blue-Green Deployments:** Use blue-green deployments to minimize downtime during deployments.
- **Canary Deployments:** Use canary deployments to test new versions of the application with a small subset of users.
- **Rolling Updates:** Use rolling updates to gradually update the application with zero downtime.
- **Automated Rollbacks:** Implement automated rollbacks to quickly revert to a previous version of the application if something goes wrong.
### 7.5 CI/CD Integration
- **Automated Testing:** Automate all tests in the CI/CD pipeline.
- **Automated Deployment:** Automate the deployment process in the CI/CD pipeline.
- **Continuous Integration:** Use continuous integration to automatically build and test the application whenever code is committed.
- **Continuous Delivery:** Use continuous delivery to automatically deploy the application to production whenever a new version is released.
- **Pipeline Security:** Secure the CI/CD pipeline to prevent unauthorized access and code injection.
## Bibliography
- Kubernetes documentation: [https://kubernetes.io/docs/](https://kubernetes.io/docs/)
- Kubernetes Best Practices: [https://kubernetes.io/docs/concepts/configuration/overview/](https://kubernetes.io/docs/concepts/configuration/overview/)
- Application Security Checklist: [https://kubernetes.io/docs/concepts/security/application-security-checklist/](https://kubernetes.io/docs/concepts/security/application-security-checklist/)
- Kubernetes coding conventions: [https://www.kubernetes.dev/docs/guide/coding-convention/](https://www.kubernetes.dev/docs/guide/coding-convention/)
@@ -0,0 +1,270 @@
---
description: Comprehensive guidelines for mkdocs development, covering code organization, best practices, performance, security, testing, common pitfalls, and tooling. This rule aims to ensure maintainable, performant, and secure documentation using mkdocs.
globs: **/*.md
---
# mkdocs Best Practices
This document provides comprehensive guidelines for developing documentation using mkdocs. It covers various aspects including code organization, common patterns, performance, security, testing, common pitfalls, and tooling.
## 1. Code Organization and Structure
### 1.1. Directory Structure Best Practices
- **docs/**: All documentation source files should reside within this directory. This is the default and recommended location for mkdocs.
- `index.md`: The project homepage.
- `about.md`: An example of another page.
- `user-guide/`: A subdirectory for a section of documentation.
- `getting-started.md`: A sub-page within the user guide.
- `configuration-options.md`: Another sub-page.
- `img/`: A directory to store images used in the documentation. Store your images as close as possible to the document that references it.
- `screenshot.png`
- **mkdocs.yml**: The main configuration file for mkdocs, located at the root of the project alongside the `docs/` directory.
Example:
mkdocs.yml
docs/
index.md
about.md
license.md
img/
screenshot.png
user-guide/
getting-started.md
configuration-options.md
### 1.2. File Naming Conventions
- Use `.md` as the extension for Markdown files.
- Name the homepage `index.md` or `README.md`.
- Use descriptive names for other pages (e.g., `getting-started.md`, `configuration-options.md`).
- Use lowercase and hyphens for file names to create clean URLs.
### 1.3. Module Organization
- mkdocs itself doesn't have modules in the traditional programming sense. Structure your documentation content logically into sections and sub-sections using directories and files.
- Use the `nav` configuration in `mkdocs.yml` to define the structure of the navigation menu.
Example:
nav:
- Home: index.md
- User Guide:
- Getting Started: user-guide/getting-started.md
- Configuration Options: user-guide/configuration-options.md
- About: about.md
- License: license.md
### 1.4. Component Architecture
- mkdocs is not a component-based system like React or Vue.js.
- Instead, think of each Markdown file as a page or section of your documentation.
- Use includes or macros (via plugins) to reuse content across multiple pages (see Snippets and Includes section).
### 1.5. Code Splitting Strategies
- Divide your documentation into logical sections and sub-sections.
- Create separate Markdown files for each section.
- Use the `nav` configuration to structure the navigation menu.
- Use `include-markdown` plugin to avoid repeating content in multiple pages.
## 2. Common Patterns and Anti-patterns
### 2.1. Design Patterns Specific to mkdocs
- **Navigation as Code**: Managing the navigation structure directly within `mkdocs.yml` is a fundamental pattern. It allows for centralized control over the site's hierarchy.
- **Content Reusability**: Utilizing plugins like `include-markdown` to reuse common elements like disclaimers, notices, or standard procedures.
- **Theming Customization**: Overriding the default theme templates to tailor the look and feel of the documentation to match branding or specific aesthetic requirements.
- **Plugin Extension**: Extending the functionality of mkdocs by using and customizing existing plugins or creating custom ones to fulfill specific documentation needs, such as generating API documentation or integrating with external tools.
### 2.2. Recommended Approaches for Common Tasks
- **Linking to Pages**: Use relative paths for internal links to avoid issues when deploying (e.g., `[link to about](about.md)`).
- **Linking to Sections**: Use anchor links to link to specific sections within a page (e.g., `[link to license](about.md#license)`).
- **Including Images**: Place images in the `docs/img/` directory and link to them using relative paths (e.g., `![Screenshot](img/screenshot.png)`).
- **Adding Meta-Data**: Add YAML or MultiMarkdown style meta-data to the beginning of Markdown files to control page templates or add information such as authors or descriptions.
### 2.3. Anti-patterns and Code Smells to Avoid
- **Absolute Paths in Links**: Avoid using absolute paths for internal links. Use relative paths instead.
- **Large Markdown Files**: Avoid creating very large Markdown files. Break them into smaller, more manageable files and use the `nav` configuration to link them.
- **Ignoring the `nav` Configuration**: Relying on the automatic navigation generation instead of explicitly defining it in `mkdocs.yml` can lead to a disorganized navigation menu.
- **Over-Customization**: Excessively customizing the theme or adding too many plugins can make the documentation difficult to maintain and update.
- **Lack of a Clear File Structure**: An unstructured or inconsistent file structure makes it difficult to navigate and understand the documentation.
### 2.4. State Management Best Practices
- mkdocs is a static site generator, so it doesn't have a traditional concept of state management.
- However, you can use plugins to add dynamic content or interact with external data sources.
### 2.5. Error Handling Patterns
- mkdocs doesn't have runtime error handling in the traditional sense.
- Errors typically occur during the build process (e.g., invalid configuration, broken links).
- Use a CI/CD pipeline to automatically build and test the documentation and catch errors early.
- Utilize linters and validators (plugins) to ensure the integrity of your Markdown and configuration files.
## 3. Performance Considerations
### 3.1. Optimization Techniques
- **Optimize Images**: Use optimized images to reduce file sizes and improve loading times.
- **Minify HTML, CSS, and JavaScript**: Use the `mkdocs-minify-plugin` to minify the generated HTML, CSS, and JavaScript files.
- **Lazy Loading Images**: Lazy load images below the fold to improve initial page load time.
- **Use a CDN**: Use a CDN (Content Delivery Network) to serve static assets (images, CSS, JavaScript) from multiple locations around the world.
### 3.2. Memory Management
- mkdocs itself doesn't have specific memory management considerations.
- However, if you're using plugins that generate dynamic content, be mindful of memory usage.
### 3.3. Rendering Optimization
- mkdocs generates static HTML files, so rendering performance is generally not a concern.
- However, complex Markdown structures can slow down the build process. Keep your Markdown files as simple as possible.
### 3.4. Bundle Size Optimization
- Optimize the size of your images and other static assets.
- Use the `mkdocs-minify-plugin` to minify the generated HTML, CSS, and JavaScript files.
- Avoid including unnecessary CSS or JavaScript in your theme.
### 3.5. Lazy Loading Strategies
- Implement lazy loading for images using JavaScript.
## 4. Security Best Practices
### 4.1. Common Vulnerabilities and How to Prevent Them
- **Cross-Site Scripting (XSS)**: Since mkdocs generates static sites, the risk of XSS is minimal, but if you incorporate user-generated content or external data, sanitize inputs properly.
- **Injection Attacks**: Avoid using untrusted data to generate content. If you must use untrusted data, sanitize it properly.
### 4.2. Input Validation
- If your mkdocs site incorporates forms or user input via plugins, validate all inputs to prevent injection attacks.
### 4.3. Authentication and Authorization Patterns
- mkdocs doesn't provide built-in authentication or authorization.
- If you need to protect certain pages, you can implement authentication at the web server level or use a plugin.
### 4.4. Data Protection Strategies
- Since mkdocs generates static sites, there is no sensitive data stored on the server.
- However, be careful not to include sensitive information in your documentation source files.
### 4.5. Secure API Communication
- If your mkdocs site communicates with external APIs, use HTTPS to encrypt the communication.
- Verify the API server's SSL certificate.
## 5. Testing Approaches
### 5.1. Unit Testing Strategies
- mkdocs itself doesn't have unit tests in the traditional programming sense.
- However, if you create custom plugins, you should write unit tests for them.
### 5.2. Integration Testing
- Create integration tests to verify that your mkdocs site is built correctly and that all links are working.
- Use a tool like `htmlproofer` to validate URLs in the rendered HTML files.
### 5.3. End-to-end Testing
- Use an end-to-end testing framework to verify that your mkdocs site is working as expected in a browser.
### 5.4. Test Organization
- Organize your tests into separate directories (e.g., `tests/`).
- Use descriptive names for your test files and test functions.
### 5.5. Mocking and Stubbing
- If you're testing custom plugins that interact with external APIs, use mocking and stubbing to isolate your tests.
## 6. Common Pitfalls and Gotchas
### 6.1. Frequent Mistakes Developers Make
- **Incorrect File Paths**: Using incorrect file paths in links or image references.
- **Ignoring the `nav` Configuration**: Relying on the automatic navigation generation instead of explicitly defining it in `mkdocs.yml`.
- **Over-Customization**: Customizing the theme too much can make the documentation difficult to maintain and update.
- **Not Keeping Documentation Up-to-Date**: Forgetting to update the documentation when the codebase changes.
### 6.2. Edge Cases to Be Aware Of
- **Long File Paths**: Long file paths can cause issues on some operating systems.
- **Special Characters in File Names**: Avoid using special characters in file names.
- **Conflicting Plugin Options**: Some plugins may have conflicting options.
### 6.3. Version-Specific Issues
- mkdocs is constantly evolving, so be aware of version-specific issues.
- Always test your documentation with the latest version of mkdocs before deploying.
### 6.4. Compatibility Concerns
- Ensure that your documentation is compatible with different browsers and devices.
- Test your documentation on different platforms to ensure that it looks good everywhere.
### 6.5. Debugging Strategies
- **Check the mkdocs Build Log**: The mkdocs build log contains valuable information about errors and warnings.
- **Use a Debugger**: Use a debugger to step through the mkdocs build process and identify issues.
- **Simplify Your Configuration**: Simplify your `mkdocs.yml` file to isolate the issue.
- **Disable Plugins**: Disable plugins one by one to identify the plugin causing the issue.
## 7. Tooling and Environment
### 7.1. Recommended Development Tools
- **Text Editor**: VS Code, Sublime Text, Atom
- **Markdown Editor**: Typora, Mark Text
- **Web Browser**: Chrome, Firefox, Safari
- **mkdocs CLI**: The mkdocs command-line interface.
### 7.2. Build Configuration
- Use a `mkdocs.yml` file to configure your mkdocs site.
- The `mkdocs.yml` file should be located at the root of your project.
- The `mkdocs.yml` file should contain the following information:
- `site_name`: The name of your site.
- `site_description`: A description of your site.
- `site_author`: The author of your site.
- `docs_dir`: The directory containing your documentation source files.
- `theme`: The theme to use for your site.
- `nav`: The navigation menu for your site.
- `markdown_extensions`: A list of Markdown extensions to enable.
- `plugins`: A list of plugins to enable.
### 7.3. Linting and Formatting
- Use a linter to enforce code style and identify potential issues.
- Use a formatter to automatically format your Markdown files.
### 7.4. Deployment Best Practices
- **Use a CI/CD Pipeline**: Use a CI/CD pipeline to automatically build and deploy your mkdocs site.
- **Deploy to a CDN**: Deploy your mkdocs site to a CDN to improve performance.
- **Use HTTPS**: Use HTTPS to encrypt communication with your site.
- **Configure a Custom Domain**: Configure a custom domain for your site.
### 7.5. CI/CD Integration
- Use a CI/CD tool like GitHub Actions, GitLab CI, or Travis CI to automatically build and deploy your mkdocs site.
- Configure your CI/CD pipeline to run tests and linters.
- Configure your CI/CD pipeline to deploy your site to a CDN.
## Additional Notes
- Always refer to the official mkdocs documentation for the most up-to-date information.
- Consider contributing to the mkdocs community by creating plugins or themes.
- Stay informed about the latest best practices and security vulnerabilities.
This comprehensive guide should help you create maintainable, performant, and secure documentation using mkdocs.
@@ -0,0 +1,166 @@
---
description: This rule provides guidelines for Terraform best practices, coding standards, and security considerations to ensure maintainable, efficient, and secure infrastructure-as-code.
globs: **/*.tf
---
- **Use Remote State**: Store Terraform state files remotely to enable collaboration and prevent conflicts. Consider using Terraform Cloud, HashiCorp Consul, AWS S3 with DynamoDB locking, or Azure Storage Account with Blob Storage Locking.
- Properly configure access controls for your remote state backend to prevent unauthorized access.
- Implement versioning for state files to track changes and facilitate rollbacks.
- **Consistent Naming Conventions**: Adopt a consistent naming convention for resources, modules, and variables to improve readability and maintainability.
- Use nouns for resource names (e.g., `aws_instance.web_server` instead of `web_server_instance`).
- Include environment or project context in names (e.g., `dev_web_server` or `prod_db`).
- Follow a consistent casing style (e.g., snake_case or camelCase).
- **Modularity and Code Structure**: Organize Terraform code into modules to promote reusability and maintainability.
- Create modules for common infrastructure components (e.g., VPC, EC2 instance, database).
- Follow a standard module structure (e.g., `variables.tf`, `outputs.tf`, `main.tf`, `versions.tf`).
- Limit the use of custom scripts within modules; prefer Terraform resources and data sources.
- **Validation and Formatting**: Always validate and format Terraform code using `terraform fmt` and `terraform validate` to ensure quality and consistency.
- Integrate `terraform fmt` and `terraform validate` into your CI/CD pipeline.
- Use a linter such as TFLint to enforce organization-specific coding best practices.
- **Use Existing Shared and Community Modules**: Leverage pre-built modules from the Terraform Registry or other trusted sources to avoid reinventing the wheel.
- Thoroughly review modules before use to understand their functionality and security implications.
- Pin module versions to prevent unexpected changes.
- **Import Existing Infrastructure**: Use the `terraform import` command to bring existing infrastructure under Terraform management.
- Understand the limitations of `terraform import` and manually verify the imported configuration.
- **Avoid Hard-coding Variables**: Use variables to parameterize Terraform configurations and avoid hard-coding values.
- Define variables in `variables.tf` with appropriate descriptions, types, and default values.
- Use environment variables or Terraform Cloud variables to pass sensitive values.
- **Tag Resources**: Tag all Terraform resources with relevant metadata (e.g., `Name`, `Environment`, `Project`, `Owner`).
- Use consistent tagging conventions across your infrastructure.
- Leverage tags for cost allocation and resource management.
- **Introduce Policy as Code**: Implement policy as code using tools like HashiCorp Sentinel or Open Policy Agent (OPA) to enforce compliance and security policies.
- Define policies for resource configurations, naming conventions, and security settings.
- Integrate policy checks into your CI/CD pipeline.
- **Code Organization and Structure:**
- **Directory Structure Best Practices:** Organize your Terraform project with a clear directory structure. A common pattern:
├── modules/
│ ├── vpc/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ └── outputs.tf
│ ├── ec2/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ └── outputs.tf
├── environments/
│ ├── dev/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ └── terraform.tfvars
│ ├── prod/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ └── terraform.tfvars
├── main.tf # Top-level resources (if any)
├── variables.tf # Global variables
└── outputs.tf # Global outputs
- **File Naming Conventions:** Adhere to consistent file naming. Use `main.tf` for the primary resource definitions, `variables.tf` for variables, `outputs.tf` for outputs, and `terraform.tfvars` for environment-specific variable values.
- **Module Organization:** Keep modules self-contained and reusable. Each module should have a specific purpose (e.g., creating a VPC, an EC2 instance, or a database).
- **Component Architecture:** Design your infrastructure as a collection of loosely coupled components (modules) that can be composed together.
- **Code Splitting Strategies:** Break down large configurations into smaller, more manageable modules and files.
- **Common Patterns and Anti-patterns:**
- **Design Patterns:**
- **Singleton Pattern:** Ensure only one instance of a critical resource exists (e.g., a VPC). Use `count = var.create_vpc ? 1 : 0` to conditionally create a single VPC.
- **Factory Pattern:** Use modules to create multiple instances of a resource with different configurations (e.g., multiple EC2 instances with different sizes and roles).
- **Facade Pattern:** Create a module that simplifies the creation of complex infrastructure by abstracting away the underlying details.
- **Recommended Approaches:**
- Use data sources to retrieve information about existing resources instead of hardcoding their IDs or names.
- Use dynamic blocks to create multiple resources or configure resource properties based on variable values.
- Use lifecycle rules to manage resource creation, modification, and deletion.
- **Anti-patterns:**
- **Hardcoding values:** Avoid hardcoding values in your Terraform configurations. Use variables instead.
- **Creating monolithic configurations:** Break down large configurations into smaller, more manageable modules.
- **Ignoring errors:** Always handle errors and provide meaningful error messages.
- **State Management Best Practices:**
- **Remote State:** Always use remote state to store Terraform state files.
- **State Locking:** Enable state locking to prevent concurrent modifications.
- **State Encryption:** Encrypt state files to protect sensitive data.
- **State Versioning:** Implement versioning for state files.
- **Error Handling Patterns:**
- Use the `try` and `can` functions to handle errors when retrieving data or evaluating expressions.
- Use `validation` blocks to validate variable values and prevent invalid configurations.
- Provide meaningful error messages to help users diagnose and fix issues.
- **Performance Considerations:**
- **Optimization Techniques:**
- Use the `count` and `for_each` meta-arguments to create multiple resources efficiently.
- Use data sources to retrieve information about existing resources instead of creating new ones.
- Use the `depends_on` meta-argument sparingly to avoid unnecessary dependencies.
- **Memory Management:**
- Be mindful of the memory usage of your Terraform configurations, especially when working with large datasets.
- Avoid creating large variables or outputs that can consume excessive memory.
- **Rendering Optimization:**
- Use efficient string interpolation techniques to avoid unnecessary string concatenation.
- Use the `templatefile` function to render complex templates efficiently.
- **Security Best Practices:**
- **Common Vulnerabilities:**
- **Hardcoded secrets:** Avoid hardcoding secrets in your Terraform configurations.
- **Publicly accessible resources:** Ensure that resources are not publicly accessible unless explicitly required.
- **Insufficient access controls:** Implement strict access controls to prevent unauthorized access to resources.
- **Input Validation:**
- Validate variable values to prevent invalid or malicious input.
- Use regular expressions to enforce specific input formats.
- **Authentication and Authorization Patterns:**
- Use IAM roles and policies to grant resources the necessary permissions.
- Use Terraform Cloud or other secrets management tools to manage sensitive credentials.
- **Data Protection Strategies:**
- Encrypt sensitive data at rest and in transit.
- Use encryption keys managed by a key management service (KMS).
- **Secure API Communication:**
- Use HTTPS for all API communication.
- Validate API responses to prevent data injection attacks.
- **Testing Approaches:**
- **Unit Testing Strategies:**
- Use `terraform show` and `terraform plan` to verify that your Terraform configurations create the expected resources.
- Use `terratest` or other testing frameworks to write automated unit tests.
- **Integration Testing:**
- Deploy your Terraform configurations to a test environment and verify that the resources are functioning correctly.
- Use automated testing tools to perform integration tests.
- **End-to-end Testing:**
- Simulate real-world scenarios and verify that your infrastructure can handle them.
- Use automated testing tools to perform end-to-end tests.
- **Test Organization:**
- Organize your tests into a clear directory structure.
- Use meaningful test names to describe the purpose of each test.
- **Mocking and Stubbing:**
- Use mocking and stubbing to isolate your tests and prevent dependencies on external resources.
- Use testing frameworks that support mocking and stubbing.
- **Common Pitfalls and Gotchas:**
- **Frequent Mistakes:**
- **Incorrect resource dependencies:** Ensure that resource dependencies are correctly defined.
- **Ignoring resource lifecycle:** Understand the lifecycle of Terraform resources and how they are created, modified, and deleted.
- **Using outdated Terraform versions:** Keep your Terraform version up to date to take advantage of new features and bug fixes.
- **Edge Cases:**
- **Handling resource conflicts:** Be prepared to handle resource conflicts that can occur when multiple Terraform configurations are applied simultaneously.
- **Managing resources with external dependencies:** Be aware of resources that have external dependencies (e.g., DNS records) and handle them appropriately.
- **Version-specific Issues:**
- Be aware of version-specific issues and compatibility concerns when upgrading Terraform or provider versions.
- Consult the Terraform and provider documentation for any breaking changes or migration guides.
- **Compatibility Concerns:**
- Ensure that your Terraform configurations are compatible with the target infrastructure environment.
- Use provider versions that are compatible with the Terraform version.
- **Debugging Strategies:**
- Use the `terraform plan` command to preview the changes that will be made to your infrastructure.
- Use the `terraform apply` command with the `-auto-approve` flag to apply changes automatically.
- Use the `terraform show` command to inspect the current state of your infrastructure.
- **Tooling and Environment:**
- **Recommended Development Tools:**
- **Terraform CLI:** The official Terraform command-line interface.
- **Terraform Cloud/Enterprise:** A collaboration and automation platform for Terraform.
- **IDE/Text Editor:** Visual Studio Code with the Terraform extension, Atom, or Sublime Text.
- **TFLint:** A linter for Terraform code.
- **Terratest:** A testing framework for Terraform code.
- **Build Configuration:**
- Use a consistent build configuration across all environments.
- Use environment variables or Terraform Cloud variables to configure the build environment.
- **Linting and Formatting:**
- Integrate linting and formatting into your CI/CD pipeline.
- Use `terraform fmt` and TFLint to ensure code quality and consistency.
- **Deployment Best Practices:**
- Use a CI/CD pipeline to automate Terraform deployments.
- Use version control to track changes to your Terraform configurations.
- Use infrastructure-as-code principles to manage your infrastructure.
- **CI/CD Integration:**
- Integrate Terraform into your CI/CD pipeline using tools like Jenkins, GitLab CI, or GitHub Actions.
- Automate the execution of `terraform plan` and `terraform apply` commands.
- Implement automated testing and validation as part of the CI/CD process.
@@ -0,0 +1,348 @@
---
description: This rule file provides guidelines for writing stable and maintainable end-to-end tests using Detox, covering code structure, testing strategies, and performance considerations. It includes best practices for test ID usage, dealing with flakiness, and integrating with CI/CD pipelines.
globs: **/*.{e2e.js,e2e.ts,spec.js,spec.ts}
---
# Detox E2E Testing Best Practices for React Native
This document outlines best practices for writing stable, maintainable, and performant end-to-end (E2E) tests for React Native applications using Detox.
## Ground Rules
- **Isolate Tests:** Each test should start fresh and not depend on the execution of previous tests. Restart the app before each test.
- **Consistent Input, Consistent Output:** Ensure identical app behavior across test iterations by managing varying server responses and app states. Mock server responses to prevent external variations.
- **End every test with an expectation:** Ensures a validation phase that confirms the intended outcome of the test.
## 1. Code Organization and Structure
### Directory Structure
<project_root>/
e2e/
config.js # Detox configuration file
utils.js # Helper functions for tests
firstTest.spec.js # Example test file
... # More test files
src/
... # Your application source code
- **`e2e` directory:** Dedicated directory for all Detox-related files.
- **`config.js`:** Contains Detox configuration, including device settings, build paths, and test runner configuration.
- **`utils.js` (or similar):** Houses reusable helper functions, such as custom matchers, navigation helpers, and data generation functions.
- **`*.spec.js` or `*.e2e.js`:** Test files containing the actual test cases. Choose a consistent naming convention.
### File Naming Conventions
- **Test files:** `[ComponentName].spec.js`, `[FeatureName].e2e.js`.
- **Helper functions:** `helpers.js`, `utils.js`, `testData.js`.
- **Configuration:** `detox.config.js` or `e2e.config.js`.
### Module Organization
- **Separate test logic from application code:** Tests reside in the `e2e` directory, separate from the `src` directory containing the app's source code.
- **Group related tests into modules:** For example, put all tests related to user authentication in an `e2e/auth/` directory.
- **Use helper modules:** Extract common test logic, like logging in a user or navigating to a specific screen, into reusable helper functions.
### Component Architecture (Page Object Model)
- **Implement the Page Object Model (POM):** Create classes or modules that represent UI screens or components. Each page object should encapsulate the selectors and actions for that screen.
javascript
// e2e/pageObjects/LoginPage.js
const { element, by, expect } = require('detox');
class LoginPage {
constructor() {
this.usernameField = element(by.id('username_input'));
this.passwordField = element(by.id('password_input'));
this.loginButton = element(by.id('login_button'));
}
async enterUsername(username) {
await this.usernameField.typeText(username);
}
async enterPassword(password) {
await this.passwordField.typeText(password);
}
async tapLoginButton() {
await this.loginButton.tap();
}
async isLoggedIn() {
await expect(element(by.id('home_screen'))).toBeVisible();
}
}
module.exports = new LoginPage();
- **Benefits of POM:**
- Improved test readability and maintainability.
- Reduced code duplication.
- Easier refactoring of UI elements.
### Code Splitting Strategies (Not directly applicable to Detox, but consider app bundle size)
- **Dynamic imports:** Utilize dynamic imports in the app code to load modules only when needed, improving initial load time. This is a React Native concern, not Detox itself, but Detox tests will execute faster on a faster-loading app.
- **Route-based splitting:** Split your app into separate bundles based on routes or features.
## 2. Common Patterns and Anti-patterns
### Design Patterns Specific to Detox
- **Wait for element to be visible:**
javascript
await waitFor(element(by.id('my_element'))).toBeVisible().withTimeout(5000);
- **Retry flaky tests:** Implement a retry mechanism for tests that occasionally fail due to timing issues or other unpredictable factors. Use Jest's retryTimes:
javascript
jest.retryTimes(3); // Retry the test up to 3 times
- **Use `beforeAll` and `beforeEach` wisely:** `beforeAll` is for setup that only needs to happen once for the entire test suite, while `beforeEach` is for setup that must be done before each test.
### Recommended Approaches for Common Tasks
- **Simulating user interactions:**
javascript
await element(by.id('my_button')).tap();
await element(by.id('my_input')).typeText('Hello, Detox!');
await element(by.id('my_scroll_view')).scroll(50, 'down');
- **Asserting element visibility and text content:**
javascript
await expect(element(by.id('my_element'))).toBeVisible();
await expect(element(by.text('Expected Text'))).toBeVisible();
await expect(element(by.id('my_element'))).toHaveText('Actual Text');
- **Handling alerts and dialogs:**
javascript
await expect(element(by.text('Alert Title'))).toBeVisible();
await element(by.text('OK')).tap(); // Dismiss the alert
### Anti-patterns and Code Smells to Avoid
- **Hardcoded timeouts:** Avoid using `setTimeout` directly. Rely on Detox's built-in synchronization and waiting mechanisms.
- **Incomplete Test Coverage:** Focus on critical paths and user flows, ensuring comprehensive coverage of the core functionalities.
- **Over-reliance on Thread.sleep() (or equivalent):** Try to use `waitFor` or Detox's synchronization primitives instead. Sleeping is almost always a sign that Detox's sync isn't working right.
- **Ignoring console.log statements:** Keep console log statements clean and helpful for debugging purposes.
### State Management Best Practices (App-level, impacts test environment)
- **Mock external dependencies:** Mock API calls, database interactions, and other external dependencies to ensure consistent test results and isolate the app's logic.
- **Control app state before each test:** Use `beforeEach` to reset the app's state to a known value before running each test. This can involve clearing data, logging out users, or navigating to a specific screen.
### Error Handling Patterns
- **Use `try...catch` blocks:** Wrap test actions in `try...catch` blocks to handle potential errors gracefully.
- **Log errors:** Log any errors that occur during test execution to help with debugging.
- **Fail tests on unexpected errors:** If a test encounters an unexpected error, mark the test as failed to prevent false positives.
## 3. Performance Considerations
### Optimization Techniques (Mainly React Native app optimization)
- **Minimize UI updates:** Reduce the number of UI updates during animations or interactions to improve rendering performance.
- **Use virtualization for long lists:** Virtualize long lists to render only the visible items, reducing memory consumption and improving scrolling performance. This improves the app's performance generally, leading to faster test execution.
- **Optimize image loading:** Optimize image sizes and use caching mechanisms to reduce image loading times.
### Memory Management (React Native app concern)
- **Release resources:** Properly release resources, such as event listeners and timers, when they are no longer needed to prevent memory leaks.
- **Use memoization:** Use memoization techniques to avoid recomputing expensive values when they haven't changed.
### Rendering Optimization (React Native app concern)
- **Use `shouldComponentUpdate` or `React.memo`:** Implement `shouldComponentUpdate` or `React.memo` to prevent unnecessary re-renders of components.
- **Avoid inline styles:** Avoid using inline styles, as they can cause performance issues.
### Bundle Size Optimization (React Native app concern)
- **Use code splitting:** Split your app into smaller chunks to reduce the initial bundle size.
- **Remove unused code:** Remove any unused code, such as dead code or unused libraries.
- **Optimize images:** Optimize image sizes and use appropriate image formats.
### Lazy Loading Strategies (React Native app concern)
- **Load components on demand:** Load components only when they are needed, such as when a user navigates to a specific screen.
- **Use lazy-loaded images:** Load images only when they are visible in the viewport.
## 4. Security Best Practices (App Security - Impacts Test Scope)
### Common Vulnerabilities and How to Prevent Them
- **Data injection:** Protect against data injection attacks by validating all user input and using parameterized queries.
- **Cross-site scripting (XSS):** Prevent XSS attacks by sanitizing all user-generated content before rendering it.
- **Man-in-the-middle (MITM) attacks:** Implement SSL/TLS to encrypt communication between the app and the server.
### Input Validation
- **Validate all user input:** Validate all user input on both the client and server sides to prevent invalid or malicious data from being processed.
- **Use appropriate validation libraries:** Use established validation libraries to simplify the validation process and ensure consistency.
### Authentication and Authorization Patterns
- **Use secure authentication protocols:** Use secure authentication protocols, such as OAuth 2.0 or OpenID Connect.
- **Implement proper authorization checks:** Implement proper authorization checks to ensure that users can only access the resources they are authorized to access.
### Data Protection Strategies
- **Encrypt sensitive data:** Encrypt sensitive data, such as passwords and credit card numbers, both in transit and at rest.
- **Store data securely:** Store data in secure locations, such as encrypted databases or keychains.
### Secure API Communication
- **Use HTTPS:** Always use HTTPS to encrypt communication between the app and the server.
- **Validate API responses:** Validate API responses to ensure that they are not tampered with.
## 5. Testing Approaches
### Unit Testing Strategies (Generally not used with Detox)
- **Test individual components or functions in isolation:** Use unit tests to verify the behavior of individual components or functions in isolation.
- **Use mocking to isolate dependencies:** Use mocking to isolate dependencies and ensure that the unit tests are not affected by external factors.
### Integration Testing
- **Test interactions between multiple components or modules:** Use integration tests to verify the interactions between multiple components or modules.
- **Use stubs to simulate external dependencies:** Use stubs to simulate external dependencies and ensure that the integration tests are not affected by real-world conditions.
### End-to-End Testing
- **Test the entire application from end to end:** Use end-to-end tests to verify the entire application flow from the user's perspective.
- **Simulate real user interactions:** Simulate real user interactions as closely as possible to ensure that the tests accurately reflect the user experience.
### Test Organization
- **Organize tests by feature or functionality:** Group tests by feature or functionality to improve test discoverability and maintainability.
- **Use descriptive test names:** Use descriptive test names to clearly indicate what each test is verifying.
- **Keep tests small and focused:** Keep tests small and focused on verifying a single aspect of the application.
### Mocking and Stubbing (Used sparingly with Detox. More common is configuring the backend)
- **Mock external dependencies:** Mock external dependencies, such as API calls or database interactions, to ensure consistent test results.
- **Use stubs to simulate specific scenarios:** Use stubs to simulate specific scenarios, such as error conditions or edge cases.
## 6. Common Pitfalls and Gotchas
### Frequent Mistakes Developers Make
- **Using brittle selectors:** Avoid using selectors that are based on text or position, as these can easily break when the UI changes. Use `testID` whenever possible.
- **Not handling asynchronous operations correctly:** Ensure that all asynchronous operations are properly handled to prevent race conditions and timing issues.
- **Ignoring error messages:** Pay attention to error messages and logs to identify and fix problems quickly.
### Edge Cases to Be Aware Of
- **Handling different screen sizes and orientations:** Test the app on different screen sizes and orientations to ensure that the UI adapts correctly.
- **Handling network connectivity issues:** Test the app's behavior when the network connection is slow or unavailable.
- **Handling different languages and locales:** Test the app with different languages and locales to ensure that it is properly localized.
### Version-Specific Issues
- **Keep Detox up to date:** Stay up to date with the latest version of Detox to take advantage of bug fixes and performance improvements.
- **Be aware of compatibility issues:** Be aware of compatibility issues between different versions of Detox, React Native, and other dependencies.
### Compatibility Concerns
- **Test on multiple devices and operating systems:** Test the app on a variety of devices and operating systems to ensure that it is compatible with the target audience.
- **Use a device farm:** Use a device farm, such as HeadSpin, to test the app on a wide range of real devices.
### Debugging Strategies
- **Use the Detox CLI:** Use the Detox CLI to run tests, inspect the app's state, and debug issues.
- **Use logging statements:** Use logging statements to track the execution flow and identify potential problems.
- **Use breakpoints:** Use breakpoints in your test code to pause execution and inspect variables.
## 7. Tooling and Environment
### Recommended Development Tools
- **Visual Studio Code:** A popular code editor with excellent support for JavaScript and React Native.
- **Detox CLI:** The Detox command-line interface for running tests and managing the Detox environment.
- **HeadSpin:** For running tests on real devices and analyzing performance metrics.
### Build Configuration
- **Configure Detox in `package.json`:** Configure Detox in the `package.json` file, including device settings, build paths, and test runner configuration.
- **Use different configurations for different environments:** Use different configurations for development, staging, and production environments.
### Linting and Formatting
- **Use ESLint:** Use ESLint to enforce code style and detect potential errors.
- **Use Prettier:** Use Prettier to automatically format code.
### Deployment Best Practices
- **Automate the deployment process:** Automate the deployment process using tools like Fastlane or Bitrise.
- **Use continuous integration and continuous delivery (CI/CD):** Use CI/CD to automatically build, test, and deploy the app whenever changes are made.
### CI/CD Integration
- **Integrate Detox tests into your CI/CD pipeline:** Integrate Detox tests into your CI/CD pipeline to automatically run tests whenever changes are made.
- **Use a CI/CD service like Jenkins, CircleCI, or Travis CI:** Use a CI/CD service like Jenkins, CircleCI, or Travis CI to automate the build, test, and deployment process.
## Working with Test IDs
### Benefits of Test IDs
* Stable matchers that don't depend on UI text.
* Locale-agnostic testing.
* Clear code navigability.
### Assigning Test IDs
* **React Native:** Use the `testID` prop on View components.
jsx
<View>
<TouchableOpacity testID="Onboarding.Next_button">
<Text>Next</Text>
</TouchableOpacity>
</View>
* **iOS Native:** Use the `accessibilityIdentifier` property.
* **Android Native:** Use the `viewTag` property.
### Best Practices for Naming Test IDs
* Use a consistent naming system (e.g., `ITEM_NAME_ALL_CAPS` or `ItemNameUpperCamelCase`).
* Use notations for special items (e.g., `_ROOT` for screen roots, `_BTN` for buttons).
* Apply consistent prefixes as categories (e.g., `EDIT_PROFILE_SCREEN.DONE_BTN`).
* Drill down to details of elements via chains of contexts (e.g., `SITE_LIST_ITEM1.OPTIONS`).
* In large projects, use module identifiers (e.g., `AUTH.LOGIN_SCREEN.EDIT_PASSWORD`).
#### Examples of good test ID usage:
EDIT_PROFILE_SCREEN.DONE_BTN
SITE_LIST_ROOT
SITE_LIST_ITEM1.OPTIONS
### Rules of Thumb for test IDs
* Use unique, simple, and concise names.
* Dissociate test ID names from element text/labels.
* Do not utilize the element's text / label in the naming of a test ID!
### Finding Test IDs
* **MacOS Accessibility Inspector:** Use the built-in accessibility inspector to verify test IDs on iOS.
* **Detox Layout Inspector:** Set up and use the Detox Layout Inspector for Android.
* Incorrect or absent testID is a common cause for test failure. If your test can't find your testID and you can't see it either using tools described above, that usually means you haven't passed it down to this component.
Make sure you keep forwarding it down until it reaches a native component.
By following these best practices, you can create a robust and maintainable suite of Detox E2E tests for your React Native application.
@@ -0,0 +1,139 @@
---
description: This rule provides guidelines for writing clean, maintainable, and effective tests using Jest. It covers code organization, performance, common pitfalls, and best practices for testing JavaScript and TypeScript projects.
globs: **/*.{js,jsx,ts,tsx,mjs,cjs,mts,cts}
---
- **Organize tests by feature or module:**
- Group tests into files or directories that correspond to the features or modules they are testing. This makes it easier to locate and maintain tests.
- Create a `__tests__` directory alongside your source code files. This is a common convention that Jest recognizes.
- **Use descriptive test names:**
- Write test names that clearly describe what the test is verifying. This makes it easier to understand the purpose of each test and to diagnose failures.
- Use the `describe` and `it` blocks to structure your tests and provide context.
- Example: `describe('User authentication', () => { it('should log in a user with valid credentials', () => { /* ... */ }); });`
- **Keep tests isolated and independent:**
- Each test should be independent of other tests. Avoid sharing state or dependencies between tests.
- Use `beforeEach` and `afterEach` hooks to set up and tear down the environment for each test.
- **Avoid testing implementation details:**
- Focus on testing the public API of your code, rather than the internal implementation details.
- This makes your tests more resilient to changes in the implementation.
- Test the "what", not the "how".
- **Use setup and teardown methods:**
- Use `beforeAll`, `afterAll`, `beforeEach`, and `afterEach` hooks to set up and tear down the environment for your tests.
- `beforeAll` and `afterAll` run once before and after all tests in a `describe` block.
- `beforeEach` and `afterEach` run before and after each test in a `describe` block.
- **Mock external dependencies:**
- Use mocking to isolate your code from external dependencies, such as network requests or database connections.
- Jest provides built-in mocking capabilities with `jest.mock` and `jest.spyOn`.
- Consider using a library like `axios-mock-adapter` for mocking HTTP requests.
- **Write tests that are easy to read and maintain:**
- Keep your tests concise and focused.
- Use clear and consistent formatting.
- Add comments to explain complex logic.
- Refactor your tests regularly to keep them up to date.
- **Aim for high test coverage, but prioritize meaningful tests over quantity:**
- Aim for high test coverage to ensure that your code is well-tested.
- However, prioritize writing meaningful tests that verify the core functionality of your code.
- Don't just aim for 100% coverage without considering the value of each test.
- **Use Jest's built-in matchers effectively:**
- Jest provides a rich set of matchers for asserting different conditions.
- Use matchers like `toBe`, `toEqual`, `toBeGreaterThan`, `toContain`, `toHaveBeenCalled`, etc.
- Explore the Jest documentation for the full list of matchers.
- **Handle asynchronous code correctly:**
- Use `async/await` or Promises to handle asynchronous code in your tests.
- Use the `resolves` and `rejects` matchers to assert that a Promise resolves or rejects.
- Example: `expect(myAsyncFunction()).resolves.toBe(expectedValue);`
- **Test error handling:**
- Write tests to verify that your code handles errors correctly.
- Use the `toThrow` matcher to assert that a function throws an error.
- Example: `expect(() => myDangerousFunction()).toThrow(Error);`
- **Use snapshots sparingly:**
- Snapshots can be useful for verifying the output of a component or function.
- However, they can also be brittle and difficult to maintain if used excessively.
- Use snapshots strategically and review them carefully when they change.
- **Configure Jest correctly:**
- Configure Jest using the `jest.config.js` or `jest.config.ts` file.
- Configure settings such as test environment, module file extensions, and coverage thresholds.
- Consider using presets like `ts-jest` or `babel-jest` for TypeScript or Babel support.
- **Leverage code coverage reports:**
- Use Jest's code coverage reports to identify areas of your code that are not well-tested.
- Aim to increase coverage in critical areas of your codebase.
- Use the `--coverage` flag to generate coverage reports.
- **Keep test data separate from test logic:**
- Externalize test data to improve readability and maintainability.
- Use fixtures or factories to generate test data.
- Avoid hardcoding data directly in your tests.
- **Consider using test-driven development (TDD):**
- Write tests before you write code to drive the development process.
- This can help you write more testable and well-designed code.
- **Run tests frequently:**
- Run your tests frequently to catch errors early.
- Use Jest's watch mode to automatically run tests when files change.
- Integrate tests into your CI/CD pipeline.
- **Document your tests:**
- Add comments to explain the purpose of each test and the expected behavior.
- This will make it easier for others to understand and maintain your tests.
- **Code Organization and Structure:**
- **Directory structure best practices:** Organize test files alongside the component/module they test (e.g., `src/components/MyComponent/MyComponent.test.js`)
- **File naming conventions:** Use `.test.js` or `.spec.js` suffixes for test files (e.g., `MyComponent.test.js`, `MyModule.spec.ts`).
- **Module organization:** Keep test files close to the modules they are testing. Use a consistent naming convention for test files.
- **Component architecture:** Test components in isolation, mocking dependencies where necessary.
- **Code splitting strategies:** Ensure tests cover all code paths in dynamically imported modules.
- **Common Patterns and Anti-patterns:**
- **Design patterns specific to Jest:** Use Page Object Model (POM) for UI tests, Factory pattern for test data generation.
- **Recommended approaches for common tasks:** Use `jest.mock` for mocking modules, `jest.spyOn` for spying on methods, and `fakeTimers` for controlling time-dependent behavior.
- **Anti-patterns and code smells to avoid:** Avoid testing implementation details, relying on global state, and creating brittle snapshots.
- **State management best practices:** Mock external state dependencies and verify state changes using `expect` assertions.
- **Error handling patterns:** Test for specific error messages and ensure error boundaries are properly tested.
- **Performance Considerations:**
- **Optimization techniques:** Use `jest.clearAllMocks` and `jest.resetAllMocks` in `beforeEach` blocks to prevent state leakage and improve test performance.
- **Memory management:** Avoid creating large data structures in tests that are not necessary. Manually trigger garbage collection in tests where large objects are created and released.
- **Rendering optimization:** Mock expensive rendering logic to speed up tests that involve React components.
- **Bundle size optimization:** Not applicable, as Jest primarily tests individual modules or components.
- **Lazy loading strategies:** Ensure tests cover all code paths in dynamically imported modules.
- **Security Best Practices:**
- **Common vulnerabilities and how to prevent them:** Avoid using sensitive data in test snapshots. Sanitize test data to prevent potential injection attacks.
- **Input validation:** Test input validation logic and ensure that invalid inputs are handled correctly.
- **Authentication and authorization patterns:** Mock authentication and authorization logic to test different user roles and permissions.
- **Data protection strategies:** Not directly applicable, as Jest primarily focuses on functional testing.
- **Secure API communication:** Mock API calls and verify that data is transmitted securely.
- **Testing Approaches:**
- **Unit testing strategies:** Test individual functions, classes, or components in isolation.
- **Integration testing:** Test interactions between different modules or components.
- **End-to-end testing:** Use tools like Cypress or Playwright for end-to-end tests.
- **Test organization:** Group tests into logical suites based on functionality or module.
- **Mocking and stubbing:** Use `jest.mock` and `jest.spyOn` to create mocks and stubs for dependencies.
- **Common Pitfalls and Gotchas:**
- **Frequent mistakes developers make:** Forgetting to mock dependencies, testing implementation details, and creating brittle snapshots.
- **Edge cases to be aware of:** Testing asynchronous code correctly, handling errors, and testing different input types.
- **Version-specific issues:** Be aware of breaking changes in Jest updates and update your tests accordingly.
- **Compatibility concerns:** Ensure tests are compatible with different browsers or environments.
- **Debugging strategies:** Use `console.log` statements, debuggers, or Jest's interactive mode to debug tests.
- **Tooling and Environment:**
- **Recommended development tools:** VS Code, WebStorm, Jest Runner extension.
- **Build configuration:** Configure Jest using `jest.config.js` or `package.json`.
- **Linting and formatting:** Use ESLint and Prettier to enforce code style and prevent errors.
- **Deployment best practices:** Integrate tests into your CI/CD pipeline to ensure code quality.
- **CI/CD integration:** Use tools like GitHub Actions, Jenkins, or CircleCI to automate testing and deployment.
@@ -0,0 +1,151 @@
---
description: This rule enforces best practices and coding standards for Playwright tests, including stable selectors, test isolation, user-centric testing, and performance considerations.
globs: **/*.spec.ts
---
- **General Principles**
- **Test User-Visible Behavior:** Focus tests on how users interact with your application, not on internal implementation details.
- **Isolate Tests:** Ensure tests are independent of each other to prevent cascading failures and ensure predictable results.
- **Avoid Testing Third-Party Dependencies:** Mock or stub external services and APIs to isolate your application's behavior.
- **Code Organization and Structure**
- **Directory Structure:**
- `tests/`: Contains all test files.
- `tests/e2e/`: End-to-end tests.
- `tests/unit/`: Unit tests (if applicable, though Playwright is primarily for E2E).
- `tests/utils/`: Helper functions and page object models.
- **File Naming Conventions:**
- Use `.spec.ts` or `.spec.js` for test files (e.g., `login.spec.ts`).
- Group related tests in the same file.
- **Module Organization:**
- Employ Page Object Model (POM) to encapsulate UI elements and interactions.
- **Component Architecture:**
- Structure tests around components or features of your application.
- **Code Splitting Strategies:**
- Not directly applicable to tests, but keep test files concise and focused.
- **Common Patterns and Anti-patterns**
- **Design Patterns:**
- **Page Object Model (POM):** A common pattern where each page is represented as a class, with methods for interacting with the page's elements. This improves reusability and maintainability. Example:
typescript
class LoginPage {
constructor(private readonly page: Page) {}
async goto() {
await this.page.goto('/login');
}
async login(username: string, password: string) {
await this.page.fill('#username', username);
await this.page.fill('#password', password);
await this.page.click('#login-button');
}
async getErrorMessage() {
return await this.page.textContent('#error-message');
}
}
- **Fixture pattern:** Use Playwright's built-in fixtures to manage test setup and teardown. This ensures each test starts in a clean state.
- **Recommended Approaches:**
- Use `baseURL` in `playwright.config.ts` to avoid hardcoding URLs in tests.
- Utilize `expect` matchers for assertions (e.g., `expect(page.locator('#success')).toBeVisible()`).
- Use auto-waiting features for improved stability.
- **Anti-patterns:**
- Hardcoding URLs.
- Using brittle selectors (e.g., XPath based on DOM structure).
- Writing tests that depend on each other.
- **State Management:**
- Keep tests stateless. Reset the application state before each test.
- Use database transactions or API calls to seed data for tests.
- **Error Handling:**
- Use `try...catch` blocks to handle expected errors.
- Log errors and failures with descriptive messages.
- Use `expect.soft()` for non-critical assertions that shouldn't fail the test immediately.
- **Performance Considerations**
- **Optimization Techniques:**
- Run tests in parallel to reduce overall test execution time.
- Use `reuseExistingServer: true` in `playwright.config.ts` during development to speed up debugging.
- Use `codegen` to generate selectors automatically.
- **Memory Management:**
- Close pages and browsers after each test or group of tests to release resources.
- **Rendering Optimization:**
- Not directly applicable but optimize your application's rendering for faster testing.
- **Bundle Size Optimization:**
- Not directly applicable, but optimize your application's bundle size for faster loading.
- **Lazy Loading Strategies:**
- Not directly applicable to tests.
- **Security Best Practices**
- **Common Vulnerabilities:**
- Avoid exposing sensitive data (e.g., passwords, API keys) in test code or logs.
- **Input Validation:**
- Test input validation to ensure your application handles invalid data correctly.
- **Authentication and Authorization:**
- Test different user roles and permissions.
- **Data Protection:**
- Ensure sensitive data is encrypted in the database.
- **Secure API Communication:**
- Test that API calls are made over HTTPS.
- **Testing Approaches**
- **Unit Testing:**
- While Playwright primarily focuses on E2E testing, unit tests can be written for utility functions or components.
- **Integration Testing:**
- Test the interaction between different parts of your application.
- **End-to-End Testing:**
- Simulate user flows to test the entire application.
- **Test Organization:**
- Group tests by feature or functionality.
- Use `describe` blocks to organize tests.
- **Mocking and Stubbing:**
- Use Playwright's `route` API to mock API responses.
- Use `locator.evaluate` to stub JavaScript functions.
- **Common Pitfalls and Gotchas**
- **Frequent Mistakes:**
- Using XPath instead of CSS selectors.
- Not using auto-waiting features.
- Writing flaky tests.
- **Edge Cases:**
- Handling different screen sizes and devices.
- Testing error conditions and edge cases.
- **Version-Specific Issues:**
- Stay up-to-date with Playwright's release notes and upgrade guides.
- **Compatibility Concerns:**
- Test on different browsers and operating systems.
- **Debugging Strategies:**
- Use Playwright Inspector to debug tests visually.
- Use `console.log` statements to log information during test execution.
- Use `pause()` to halt test execution and inspect the page.
- **Tooling and Environment**
- **Recommended Development Tools:**
- VS Code with the Playwright extension.
- **Build Configuration:**
- Use TypeScript for type safety and autocompletion.
- **Linting and Formatting:**
- Use ESLint and Prettier to enforce code style.
- **Deployment Best Practices:**
- Run tests in CI/CD pipeline before deploying to production.
- **CI/CD Integration:**
- Integrate Playwright with CI/CD tools like GitHub Actions, Jenkins, or GitLab CI.
- **Specific Best Practices & Details**
- **Stable Selectors:** Prefer CSS selectors based on attributes like `data-testid` or `data-test-id` over XPath or fragile CSS classnames.
- **Leverage Auto-waiting:** Playwright automatically waits for elements to be actionable before performing actions. Avoid explicit waits where possible. However, use explicit waits (e.g. `waitForSelector`) when necessary.
- **Web-First Assertions:** Use `expect` assertions, which retry and wait for conditions to be met. They help to avoid flakiness.
- **Configure Debugging Highlights:** Configure `playwright.config.ts` to highlight actions performed by playwright in the browser during debugging to see what's happening step by step. Example:
typescript
use: {
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
video: 'on',
screenshot: 'only-on-failure',
}
- **Additional Notes**
- Regularly review and update your test suite to reflect changes in your application.
- Document your tests to make them easier to understand and maintain.
- Use a consistent naming convention for your tests.
@@ -0,0 +1,363 @@
---
description: This rule file provides comprehensive best practices for using Vitest, covering code organization, testing strategies, performance, and security within Vitest projects. These guidelines ensure clean, maintainable, and reliable test suites.
globs: **/*.{js,jsx,ts,tsx,vue,svelte,spec,test}.*
---
# Vitest Best Practices and Coding Standards
This document outlines best practices for using Vitest to create reliable, maintainable, and performant test suites. It covers various aspects of testing, from code organization to performance considerations and security measures.
## 1. Code Organization and Structure
### 1.1 Directory Structure
* **Keep tests close to the source code:** Place test files in the same directory as the components or modules they test. This improves discoverability and maintainability.
src/
components/
MyComponent.vue
MyComponent.spec.ts
MyComponent.test.ts # Alternative naming
utils/
math.ts
math.test.ts
App.vue
App.spec.ts
* **Use a dedicated `tests` directory for end-to-end tests or shared utilities:** For larger projects, a `tests` directory at the root level can house end-to-end tests, integration tests that require a specific environment, or shared testing utilities.
tests/
e2e/
specs/
home.spec.ts
support/
commands.ts
unit/
utils.test.ts # Tests for general utilities
integration/
db.setup.ts # Setup for integration tests
src/
...
### 1.2 File Naming Conventions
* **Use consistent naming:** Adopt a consistent naming scheme for test files. Common conventions include:
* `[component/module].spec.ts`
* `[component/module].test.ts`
* `[component/module].e2e.ts` (for end-to-end tests)
* **Be descriptive:** Name test files to clearly indicate what they are testing. For example, `MyComponent.props.spec.ts` might test specific props of `MyComponent`.
### 1.3 Module Organization
* **Group related tests:** Organize tests into modules using `describe` blocks. This improves readability and helps structure test output.
typescript
import { describe, it, expect } from 'vitest';
import { add } from './math';
describe('Math functions', () => {
describe('add', () => {
it('should add two numbers correctly', () => {
expect(add(2, 3)).toBe(5);
});
it('should handle negative numbers', () => {
expect(add(-1, 1)).toBe(0);
});
});
});
### 1.4 Component Architecture
* **Test component logic separately:** Extract complex logic from components into separate, testable functions or modules. This promotes reusability and simplifies component testing.
* **Focus on component interactions:** When testing components, concentrate on verifying that the component renders correctly given certain props or state and that it emits the correct events in response to user interactions.
### 1.5 Code Splitting Strategies
* **Test code splitting:** If your application uses code splitting, ensure your tests cover different code chunks and lazy-loaded modules.
* **Mock dynamic imports:** Use Vitest's mocking capabilities to simulate dynamic imports during testing.
typescript
import { describe, it, expect, vi } from 'vitest';
describe('Dynamic import', () => {
it('should mock dynamic import', async () => {
const mockModule = { value: 'mocked' };
vi.mock('./dynamic-module', () => ({
default: mockModule,
}));
const dynamicModule = await import('./dynamic-module');
expect(dynamicModule.default).toBe(mockModule);
});
});
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns Specific to Vitest
* **AAA (Arrange, Act, Assert):** Structure each test case following the AAA pattern for clarity and maintainability.
typescript
it('should add two numbers correctly', () => {
// Arrange
const a = 2;
const b = 3;
// Act
const result = add(a, b);
// Assert
expect(result).toBe(5);
});
* **Page Object Model (POM):** For end-to-end tests, use the Page Object Model to abstract away the details of the user interface and make tests more resilient to UI changes. Define dedicated classes representing different pages or components.
### 2.2 Recommended Approaches for Common Tasks
* **Mocking external dependencies:** Use Vitest's mocking capabilities to isolate units of code during testing. Use `vi.mock()` to mock modules and `vi.spyOn()` to spy on specific methods or properties.
* **Testing asynchronous code:** Utilize `async/await` and Vitest's `expect.resolves` and `expect.rejects` matchers for testing asynchronous functions.
typescript
it('should resolve with the correct value', async () => {
await expect(Promise.resolve(42)).resolves.toBe(42);
});
it('should reject with an error', async () => {
await expect(Promise.reject(new Error('Something went wrong'))).rejects.toThrow('Something went wrong');
});
### 2.3 Anti-patterns and Code Smells to Avoid
* **Over-mocking:** Avoid mocking everything. Mock only external dependencies or components that are not under test. Testing against mocks rather than real implementations reduces test confidence.
* **Flaky tests:** Tests that pass or fail intermittently are a sign of underlying issues. Investigate flaky tests to identify and fix the root cause, such as race conditions or reliance on external resources.
* **Ignoring edge cases:** Ensure your tests cover all possible scenarios, including edge cases, error conditions, and boundary values. Don't only test the "happy path".
* **Long test functions:** Break down overly complex test functions into smaller, more focused tests. This improves readability and makes it easier to identify the cause of failures.
### 2.4 State Management Best Practices
* **Isolate state:** When testing code that relies on state management libraries (e.g., Vuex, Pinia, Redux), isolate the state and actions being tested.
* **Mock store actions/getters:** Mock actions and getters to control the state during testing and verify that they are called correctly.
typescript
import { describe, it, expect, vi } from 'vitest';
import { useStore } from './store';
describe('Store actions', () => {
it('should dispatch the correct action', () => {
const store = useStore();
const mockAction = vi.fn();
store.dispatch = mockAction;
store.commit('increment');
expect(mockAction).toHaveBeenCalledWith('increment');
});
});
### 2.5 Error Handling Patterns
* **Test error handling:** Ensure your tests cover error handling scenarios. Use `try...catch` blocks or `expect.rejects` to verify that errors are thrown and handled correctly.
* **Mock error responses:** Mock API responses to simulate error conditions and test how your code handles them.
## 3. Performance Considerations
### 3.1 Optimization Techniques
* **Run tests in parallel:** Vitest supports running tests in parallel. Enable this feature to speed up test execution.
json
// vitest.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
threads: true, // Enable parallel execution
},
})
* **Use `--changed` and `--related` flags:** When running tests, use the `--changed` flag to only run tests that have changed since the last commit or the `--related` flag to run tests related to specific files.
bash
vitest --changed
vitest --related src/components/MyComponent.vue
* **Optimize test setup:** Minimize the amount of setup required for each test. Use `beforeAll` and `afterAll` hooks to perform setup and teardown operations once for each test suite, rather than for each test case.
### 3.2 Memory Management
* **Clean up after tests:** Ensure that your tests do not leak memory. Use `afterEach` hooks to clean up any resources created during the test, such as mocks or temporary files.
* **Avoid creating large objects in tests:** Minimize the size of objects created in tests to reduce memory consumption.
### 3.3 Rendering Optimization
* **Use shallow rendering:** When testing components, use shallow rendering to avoid rendering the entire component tree. This can significantly improve test performance.
typescript
import { shallowMount } from '@vue/test-utils';
import MyComponent from './MyComponent.vue';
it('should render correctly', () => {
const wrapper = shallowMount(MyComponent);
expect(wrapper.exists()).toBe(true);
});
### 3.4 Bundle Size Optimization
* **Keep tests small:** Avoid including unnecessary dependencies in your test files. This can help reduce the bundle size of your tests and improve startup time.
### 3.5 Lazy Loading Strategies
* **Mock lazy-loaded modules:** When testing code that uses lazy loading, mock the lazy-loaded modules to avoid loading them during testing. This can improve test performance and reduce dependencies.
## 4. Security Best Practices
### 4.1 Common Vulnerabilities and How to Prevent Them
* **Cross-Site Scripting (XSS):** Prevent XSS vulnerabilities by sanitizing user input and encoding output. Ensure the testing framework is not vulnerable either. Check versions of plugins.
* **Injection Attacks:** Prevent injection attacks by validating user input and using parameterized queries.
* **Sensitive Data Exposure:** Avoid storing sensitive data in test files. Use environment variables or secure configuration files to manage sensitive data.
### 4.2 Input Validation
* **Test input validation:** Ensure your tests cover input validation scenarios. Verify that your code correctly validates user input and handles invalid input gracefully.
### 4.3 Authentication and Authorization Patterns
* **Mock authentication:** When testing code that requires authentication, mock the authentication service to avoid making actual API calls. Verify that your code correctly handles authenticated and unauthenticated states.
* **Test authorization:** Ensure your tests cover authorization scenarios. Verify that your code correctly enforces access control and prevents unauthorized access to resources.
### 4.4 Data Protection Strategies
* **Protect sensitive data in tests:** Avoid including sensitive data in your test files. Use mock data or anonymized data for testing.
### 4.5 Secure API Communication
* **Mock API responses:** Mock API responses to avoid making actual API calls during testing. Use HTTPS for secure communication.
## 5. Testing Approaches
### 5.1 Unit Testing Strategies
* **Focus on individual units:** Unit tests should focus on testing individual functions, classes, or modules in isolation. Avoid testing multiple units of code in a single test.
* **Test all code paths:** Ensure your unit tests cover all possible code paths, including normal execution paths, error conditions, and edge cases.
* **Use mocks and stubs:** Use mocks and stubs to isolate units of code and control their behavior during testing.
### 5.2 Integration Testing
* **Test interactions between units:** Integration tests should focus on testing the interactions between different units of code. Verify that units of code work together correctly.
* **Use real dependencies:** Use real dependencies in integration tests whenever possible. This can help ensure that your code works correctly in a real-world environment.
### 5.3 End-to-End Testing
* **Test the entire application:** End-to-end tests should focus on testing the entire application, from the user interface to the backend services. Verify that the application works correctly from the user's perspective.
* **Use a real browser:** Use a real browser for end-to-end testing. This can help ensure that your application works correctly in different browsers and environments.
### 5.4 Test Organization
* **Group related tests:** Organize tests into modules using `describe` blocks. This improves readability and helps structure test output. (See 1.3 Module Organization)
* **Use meaningful test names:** Use descriptive test names that clearly indicate what the test is verifying. This makes it easier to understand the purpose of the test and to identify the cause of failures.
* **Keep tests short and focused:** Keep tests short and focused on a single aspect of the code. This improves readability and makes it easier to maintain the tests.
### 5.5 Mocking and Stubbing
* **Use mocks to verify interactions:** Use mocks to verify that functions are called with the correct arguments and that they return the correct values.
* **Use stubs to control behavior:** Use stubs to control the behavior of functions during testing. This allows you to simulate different scenarios and test how your code handles them.
* **Avoid over-mocking:** Only mock dependencies that are not under test. Over-mocking can lead to tests that are brittle and do not accurately reflect the behavior of the code.
## 6. Common Pitfalls and Gotchas
### 6.1 Frequent Mistakes Developers Make
* **Not writing enough tests:** Ensure that you have sufficient test coverage to catch bugs and prevent regressions.
* **Writing brittle tests:** Avoid writing tests that are too tightly coupled to the implementation details of the code. This makes the tests brittle and difficult to maintain.
* **Ignoring test failures:** Address test failures promptly. Ignoring test failures can lead to regressions and make it more difficult to maintain the code.
### 6.2 Edge Cases to Be Aware Of
* **Null and undefined values:** Ensure your tests cover scenarios where values are null or undefined.
* **Empty strings and arrays:** Ensure your tests cover scenarios where strings or arrays are empty.
* **Boundary values:** Ensure your tests cover boundary values, such as the minimum and maximum values of numeric types.
### 6.3 Version-Specific Issues
* **Keep Vitest up to date:** Stay up-to-date with the latest version of Vitest to benefit from bug fixes, performance improvements, and new features.
### 6.4 Compatibility Concerns
* **Test on different browsers and environments:** Ensure your tests cover different browsers and environments to catch compatibility issues.
### 6.5 Debugging Strategies
* **Use debugging tools:** Utilize debugging tools to step through your tests and identify the cause of failures. Vitest integrates with popular debuggers.
* **Write clear and concise tests:** Write clear and concise tests to make it easier to understand the purpose of the test and to identify the cause of failures.
* **Use logging:** Add logging statements to your tests to help track the flow of execution and identify the source of problems.
## 7. Tooling and Environment
### 7.1 Recommended Development Tools
* **VS Code with the Vitest extension:** VS Code with the Vitest extension provides a rich development experience, including test discovery, execution, and debugging.
* **Other IDEs with Vitest support:** Many other IDEs, such as WebStorm and IntelliJ IDEA, also offer support for Vitest.
### 7.2 Build Configuration
* **Use a build tool:** Use a build tool, such as Vite or esbuild, to bundle your code and optimize it for testing.
* **Configure Vitest:** Configure Vitest to suit your project's needs. Use the `vitest.config.ts` file to customize Vitest's behavior.
### 7.3 Linting and Formatting
* **Use ESLint and Prettier:** Use ESLint and Prettier to enforce consistent coding styles and catch potential errors. Integrate these tools into your development workflow.
### 7.4 Deployment Best Practices
* **Run tests before deployment:** Always run your tests before deploying your code to ensure that it is working correctly. Automate this process as part of your CI/CD pipeline.
### 7.5 CI/CD Integration
* **Integrate Vitest with your CI/CD pipeline:** Integrate Vitest with your CI/CD pipeline to automatically run tests on every commit. This helps catch bugs early and prevent regressions.
* **Use a CI/CD service:** Use a CI/CD service, such as GitHub Actions or GitLab CI, to automate your build, test, and deployment processes.
## Conclusion
By following these best practices, you can create robust and maintainable test suites with Vitest that ensure the quality and reliability of your code.
@@ -0,0 +1,85 @@
---
description: This rule outlines best practices for effective use of Git, including code organization, commit strategies, branching models, and collaborative workflows.
globs: **/.git/*
---
- **Commit Strategies:**
- **Atomic Commits:** Keep commits small and focused. Each commit should address a single, logical change. This makes it easier to understand the history and revert changes if needed.
- **Descriptive Commit Messages:** Write clear, concise, and informative commit messages. Explain the *why* behind the change, not just *what* was changed. Use a consistent format (e.g., imperative mood: "Fix bug", "Add feature").
- **Commit Frequently:** Commit early and often. This helps avoid losing work and makes it easier to track progress.
- **Avoid Committing Broken Code:** Ensure your code compiles and passes basic tests before committing.
- **Sign Your Commits (Optional but Recommended):** Use GPG signing to verify the authenticity of your commits.
- **Branching Model:**
- **Use Feature Branches:** Create branches for each new feature or bug fix. This isolates changes and allows for easier code review.
- **Gitflow or Similar:** Consider adopting a branching model like Gitflow for managing releases, hotfixes, and feature development.
- **Short-Lived Branches:** Keep branches short-lived. The longer a branch exists, the harder it becomes to merge.
- **Regularly Rebase or Merge:** Keep your feature branches up-to-date with the main branch (e.g., `main`, `develop`) by rebasing or merging regularly.
- **Avoid Direct Commits to Main Branch:** Protect your main branch from direct commits. Use pull requests for all changes.
- **Code Organization:**
- **Consistent Formatting:** Use a consistent coding style guide (e.g., PEP 8 for Python, Google Style Guide for other languages) and enforce it with linters and formatters (e.g., `flake8`, `pylint`, `prettier`).
- **Modular Code:** Break down your codebase into smaller, manageable modules or components. This improves readability, maintainability, and testability.
- **Well-Defined Interfaces:** Define clear interfaces between modules and components to promote loose coupling.
- **Avoid Global State:** Minimize the use of global variables and state to reduce complexity and potential conflicts.
- **Documentation:** Document your code with comments and docstrings. Explain the purpose of functions, classes, and modules.
- **Collaboration and Code Review:**
- **Pull Requests:** Use pull requests for all code changes. This provides an opportunity for code review and discussion.
- **Code Review Checklist:** Create a code review checklist to ensure consistency and thoroughness.
- **Constructive Feedback:** Provide constructive feedback during code reviews. Focus on improving the code, not criticizing the author.
- **Address Feedback:** Respond to and address feedback from code reviews promptly.
- **Pair Programming:** Consider pair programming for complex or critical tasks.
- **Ignoring Files and Directories:**
- **.gitignore:** Use a `.gitignore` file to exclude files and directories that should not be tracked by Git (e.g., build artifacts, temporary files, secrets).
- **Global .gitignore:** Configure a global `.gitignore` file to exclude files that you never want to track in any Git repository.
- **Handling Secrets and Sensitive Information:**
- **Never Commit Secrets:** Never commit secrets, passwords, API keys, or other sensitive information to your Git repository.
- **Environment Variables:** Store secrets in environment variables and access them at runtime.
- **Secret Management Tools:** Use secret management tools like HashiCorp Vault or AWS Secrets Manager to store and manage secrets securely.
- **git-secret or similar:** If secrets must exist in the repo (strongly discouraged), encrypt them.
- **Submodules and Subtrees:**
- **Use Sparingly:** Use Git submodules and subtrees sparingly, as they can add complexity.
- **Understand the Implications:** Understand the implications of using submodules and subtrees before adopting them.
- **Consider Alternatives:** Consider alternatives to submodules and subtrees, such as package managers or build systems.
- **Large File Storage (LFS):**
- **Use for Large Files:** Use Git LFS for storing large files (e.g., images, videos, audio files). This prevents your repository from becoming bloated.
- **Configure LFS:** Configure Git LFS properly to track the large files in your repository.
- **Reverting and Resetting:**
- **Understand the Differences:** Understand the differences between `git revert`, `git reset`, and `git checkout` before using them.
- **Use with Caution:** Use `git reset` and `git checkout` with caution, as they can potentially lose data.
- **Revert Public Commits:** Use `git revert` to undo changes that have already been pushed to a public repository. This creates a new commit that reverses the changes.
- **Tagging Releases:**
- **Create Tags:** Create tags to mark significant releases or milestones.
- **Semantic Versioning:** Follow semantic versioning (SemVer) when tagging releases.
- **Annotated Tags:** Use annotated tags to provide additional information about the release.
- **Dealing with Merge Conflicts:**
- **Understand the Conflict:** Understand the source of the merge conflict before attempting to resolve it.
- **Communicate with Others:** Communicate with other developers who may be affected by the conflict.
- **Use a Merge Tool:** Use a merge tool to help resolve the conflict.
- **Test After Resolving:** Test your code thoroughly after resolving the conflict.
- **Repository Maintenance:**
- **Regularly Clean Up:** Regularly clean up your Git repository by removing unused branches and tags.
- **Optimize the Repository:** Optimize the repository with `git gc` to improve performance.
- **CI/CD Integration:**
- **Automate Testing:** Integrate Git with a CI/CD system to automate testing and deployment.
- **Run Tests on Every Commit:** Run tests on every commit to ensure code quality.
- **Common Pitfalls and Gotchas:**
- **Accidental Commits:** Accidentally committing sensitive information or large files.
- **Merge Conflicts:** Difficulty resolving merge conflicts.
- **Losing Work:** Losing work due to incorrect use of `git reset` or `git checkout`.
- **Ignoring .gitignore:** Forgetting to add files to `.gitignore`.
- **Tooling and Environment:**
- **Git Clients:** Use a Git client that suits your needs (e.g., command line, GUI).
- **IDE Integration:** Use Git integration in your IDE to streamline workflows.
- **Online Repositories:** Use a reliable online Git repository hosting service (e.g., GitHub, GitLab, Bitbucket).