Lesson 08 – Codex Code Quality Scans and Test Generation¶
Writing maintainable code goes beyond getting features to work. Codex can help identify complex logic, violations of SOLID principles, and repeated code that should be consolidated. This lesson outlines how to leverage Codex for automated code reviews and unit test generation.
1. Overview¶
Codex can examine source files and highlight areas that may cause maintenance headaches. By combining its reasoning with static analysis tools, you can quickly surface issues such as high cyclomatic complexity, classes that break the Single Responsibility Principle, or duplicated functions. Once those issues are found, Codex can also draft unit tests to close coverage gaps.
flowchart TD
A[Source Code] --> B[Codex Analysis]
B --> C[Cyclomatic Complexity]
B --> D[SOLID Check]
B --> E[Reuse Violations]
C --> F[Refactor Suggestions]
D --> F
E --> F
F --> G[Generate Tests]
2. Checking Cyclomatic Complexity¶
Use the radon package to compute cyclomatic complexity for Python code. Codex can parse the output and point to functions that exceed your threshold.
pip install radon
radon cc my_module.py
Here is an example function for illustration:
def process_request(data: dict, retries: int) -> str:
"""Return a status message based on validation and retries.
This method validates the request data, retries the operation if needed,
and returns a final status string. It does not perform network calls.
Args:
data (dict): The incoming request payload.
retries (int): How many attempts have been made so far.
Returns:
str: A human-readable status message.
Raises:
KeyError: If required fields are missing from ``data``.
Examples:
>>> process_request({"id": 1}, 0)
'complete'
"""
if "id" not in data:
raise KeyError("missing id")
if data.get("retry") and retries < 3:
return "retrying"
if data.get("cancel"):
return "canceled"
return "complete"
A complexity score over 5 might warrant refactoring. Ask Codex to summarize the radon output and suggest ways to simplify branching.
3. Detecting SOLID Violations¶
Codex can inspect class hierarchies and spot when responsibilities blur together. Supply a class definition and prompt for potential issues related to Single Responsibility, Open/Closed, or Liskov Substitution. Example prompt:
Explain any SOLID violations in this class and how to correct them:
```python
class OrderManager:
def __init__(self, db):
self.db = db
self.logger = Logger()
def place_order(self, order):
self.db.save(order)
self.logger.info("saved")
def generate_report(self):
return self.db.summary()
Codex might recommend splitting logging concerns from persistence to satisfy Single Responsibility, then injecting abstractions for easier testing.
---
## 4. Finding Reuse Violations
Duplicate logic often creeps in as projects grow. Provide multiple functions or files to Codex and ask it to identify similar blocks of code. Tools like `jscpd` (for JavaScript) or `flake8` plugins can help surface these patterns. Once duplicates are found, consolidate them into shared utilities.
---
## 5. Generating Unit Tests for Coverage
After refactoring, measure test coverage with `coverage.py`.
```bash
pip install coverage
coverage run -m pytest
coverage report -m
If coverage is low, prompt Codex to generate additional test cases focusing on previously untested branches. Review the generated tests, adapt them to your project conventions, and rerun the coverage commands until critical paths are exercised.
By iterating with Codex to analyze complexity, design, and duplication, you can steadily improve code quality while ensuring thorough unit tests protect your changes.
Using Codex for code-quality scans and test generation fortifies your projects against regressions. Lesson 07 – Iterating on Web Page Code with ChatGPT showcased how iterative refinement drives better interfaces; next, Lesson 09 – Case Study: Iterative Design of a Custom Assessment Form demonstrates those principles in a full Gemini Canvas project.