Come progettare prompt dinamici con chain-of-thought per test unitari in CI/CD?

Introduzione

Hai mai pensato di chiedere a un modello di linguaggio di scrivere i tuoi unit test in modo automatico?Chain-of-Thought (CoT)

1. Cos’è la Chain-of-Thought e perché funziona con la programmazione?

1.1 Vantaggi di CoT per l’unit testing

  • Maggiore accuratezza: il modello esegue verifiche intermedie.
  • TracciabilitÃ: è facile capire perché è stato scelto un certo asserzione.
  • Riduzione degli errori di sintassi: la verifica passo-passo aiuta a evitare errori di formattazione.

2. Come strutturare un prompt dinamico

Un prompt dinamico deve adattarsi a:

  • linguaggio di programmazione (Python, JavaScript, Java, etc.)
  • framework di testing (pytest, JUnit, Jest, etc.)
  • stile di coding (docstring, comments, naming convention)

2.1 Template base del prompt CoT

You are an expert software engineer specializing in {framework} tests for code written in {language}.\nYour task is to generate a unit test for the following function/method:\n{function_signature}\n\nFollow these steps:\n1. Analyze the function signature and identify edge cases.\n2. Outline the test plan with input scenarios and expected outputs.\n3. Write the test code, including setup, assertions, and cleanup.\n4. Provide a brief rationale for each test case.\n
Generate only the test code and the rationale, nothing else.

2.2 Esempio pratico: Python + pytest

def add(a: int, b: int) -> int:
    """Return the sum of a and b."""
    return a + b
You are an expert software engineer specializing in pytest tests for code written in Python.\nYour task is to generate a unit test for the following function: def add(a: int, b: int) -> int: return a + b\n\nFollow these steps: ...
import pytest

# Step 1: Edge cases identified
# Step 2: Test plan
#  - Normal addition
#  - Adding zero
#  - Negative numbers

# Step 3: Test code

def test_add_normal():
    assert add(2, 3) == 5

def test_add_zero():
    assert add(0, 10) == 10

def test_add_negative():
    assert add(-2, -3) == -5

# Step 4: Rationale
# The tests cover typical and boundary conditions, ensuring stability across integer ranges.

3. Integrazione nei pipeline CI/CD

Una volta generati i test, è cruciale verificarne l’efficacia all’interno della pipeline di integrazione continua.

3.1 GitHub Actions

name: CI
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Setup Python
        uses: actions/setup-python@v2
        with:
          python-version: '3.10'
      - name: Install dependencies
        run: pip install -r requirements.txt
      - name: Generate tests via OpenAI API
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: |
          python generate_tests.py
      - name: Run tests
        run: pytest --cov=.

3.2 GitLab CI

stages:
  - test

generate_tests:
  stage: test
  image: python:3.10
  script:
    - pip install -r requirements.txt
    - python generate_tests.py
  artifacts:
    paths:
      - tests/

run_tests:
  stage: test
  image: python:3.10
  script:
    - pip install -r requirements.txt
    - pytest --cov=.

3.3 Jenkins (Pipeline Script)

pipeline {
  agent any
  stages {
    stage('Checkout') {
      steps { checkout scm }
    }
    stage('Generate Tests') {
      steps {
        sh 'pip install -r requirements.txt'
        sh 'python generate_tests.py'
      }
    }
    stage('Run Tests') {
      steps {
        sh 'pytest --cov=.'
      }
    }
  }
}

4. Valutare la qualità e la copertura dei test generati

4.1 Metriche chiave

  • Coverage percentage: % di linee di codice coperti dai test.
  • Test pass rate: % di test che passano rispetto al totale.
  • Mean time to detect (MTTD): tempo medio per rilevare un bug.
  • False positives rate: percentuale di test che falliscono per motivi non correlati al codice.
  • Code review feedback score: punteggio medio delle revisioni (es. numero di commenti per file).

4.2 Strumenti di misurazione

  • coverage.pyper Python.
  • Jacocoper Java.
  • nycper JavaScript.
  • Dashboard diSonarQubeper analisi statica e copertura.

4.3 Checklist di revisione manuale

  • Il test copre tutti i casi d’uso dichiarati.
  • Non è dipendente dallo stato globale.
  • Le asserzioni sono esplicite e non ambigue.
  • Il nome del test è descrittivo.
  • Il codice è conforme ai linee guida di stile.

5. Takeaway pratici

  • Costruisci prompt modulare: separa linguaggio, framework e logica CoT.
  • Automatizza la generazione con script che richiamano l’API OpenAI.
  • Includi una fase di verifica della copertura con tool dedicati.
  • Integra i test generati nella pipeline CI/CD con step dedicati.
  • Raccogli metriche e usa i risultati per iterare sul modello e sul prompt.

Conclusione

Domande Frequenti

Che cos’è la Chain-of-Thought in prompt engineering?

Come posso verificare la qualità dei test generati dall’LLM?

Usa strumenti di copertura come coverage.py, Jacoco o nyc, e controlla metriche come percentuale di copertura, pass rate e feedback delle code review.

💼 Vuoi ottimizzare i tuoi processi con l'AI?

Scopri come possiamo aiutarti a creare prompt personalizzati e strategie AI su misura per il tuo business.

Richiedi Consulenza Gratuita