CodeGym /Corsi /Docker SELF /Test e debug di un'applicazione

Test e debug di un'applicazione

Docker SELF
Livello 24 , Lezione 2
Disponibile

8.1 Testing del frontend

In questa fase vedremo come fare test e debug della nostra applicazione multi-container. I test aiuteranno a identificare e correggere errori, oltre a garantire il corretto funzionamento di tutti i componenti del sistema.

Per testare il frontend con ReactJS utilizzeremo la libreria Jest e React Testing Library.

Installazione di Jest e React Testing Library

Passo 1. Installazione delle dipendenze:

Terminale

cd frontend
npm install --save-dev jest @testing-library/react @testing-library/jest-dom

Passo 2. Configurazione di Jest:

Crea un file jest.config.js nella directory frontend:

Javascript

module.exports = {
  setupFilesAfterEnv: ['<rootDir>/src/setupTests.js'],
  testEnvironment: 'jsdom',
};

Passo 3. Creazione del file setupTests.js:

Crea un file setupTests.js nella directory frontend/src:

Javascript

import '@testing-library/jest-dom/extend-expect';

Passo 4. Scrittura dei test per i componenti

Crea un file di test per il componente TaskList nella directory frontend/src:

Javascript

import React from 'react';
import { render, screen } from '@testing-library/react';
import TaskList from './TaskList';

test('renders Task List heading', () => {
  render(<TaskList />);
  const headingElement = screen.getByText(/Task List/i);
  expect(headingElement).toBeInTheDocument();
});

Passo 5. Esecuzione dei test

Per avviare i test, usa il comando:

Terminale

npm test

8.2 Test del backend

Per testare il backend su Flask utilizzeremo la libreria unittest.

Installazione delle dipendenze:

Terminal

cd ../backend
pip install Flask-Testing

Scrittura dei test per gli endpoint

Crea una directory tests e un file test_routes.py nella directory backend:

Python

import unittest
from app import app, db
from app.models import User, Task

class BasicTests(unittest.TestCase):

    def setUp(self):
        app.config['TESTING'] = True
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
        self.app = app.test_client()
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()

    def test_user_registration(self):
        response = self.app.post('/register', json={
            'username': 'testuser',
            'password': 'testpassword'
        })
        self.assertEqual(response.status_code, 201)

    def test_task_creation(self):
        self.app.post('/register', json={
            'username': 'testuser',
            'password': 'testpassword'
        })
        access_token = self.app.post('/login', json={
            'username': 'testuser',
            'password': 'testpassword'
        }).json['access_token']

        response = self.app.post('/tasks', json={
            'title': 'Task di Test',
            'description': 'Descrizione di Test',
            'owner_id': 1,
            'status': 'non completato'
        }, headers={'Authorization': f'Bearer {access_token}'})
        self.assertEqual(response.status_code, 201)

if __name__ == "__main__":
    unittest.main()

Esecuzione dei test

Per eseguire i test utilizza il comando:

Terminal

python -m unittest discover

8.3 Test di integrazione

Il test di integrazione verifica l'interazione tra i componenti del sistema.

Configurazione dell'ambiente di test

Per i test di integrazione useremo Docker Compose, in modo da avviare tutti i servizi in un ambiente di test.

Passo 1. Creazione del file Docker Compose per i test:

Crea un file docker-compose.test.yml nella directory principale del progetto:

Yaml

version: '3'

services:
  frontend:
    build: ./frontend
    ports:
      - "3001:3000"
    networks:
      - task-network

  backend:
    build: ./backend
    ports:
      - "5001:5000"
    depends_on:
      - database
    networks:
      - task-network
    environment:
      - DATABASE_URL=postgresql://taskuser:taskpassword@database:5432/taskdb

  database:
    image: postgres:13
    environment:
      - POSTGRES_DB=taskdb
      - POSTGRES_USER=taskuser
      - POSTGRES_PASSWORD=taskpassword
    networks:
      - task-network
    volumes:
      - db-data:/var/lib/postgresql/data

networks:
  task-network:
    driver: bridge

volumes:
  db-data:

Passo 2. Avvio dell'ambiente di test:

Per avviare tutti i servizi nell'ambiente di test usa il comando:

Terminal

docker compose -f docker-compose.test.yml up --build

Scrittura dei test di integrazione

I test di integrazione possono essere scritti utilizzando diversi strumenti. Uno degli approcci è usare Selenium per il test automatizzato dell'interfaccia utente.

Passo 1. Installazione di Selenium:

Terminal

pip install selenium

Passo 2. Scrittura del test di integrazione:

Crea un file test_integration.py nella directory tests:

Python

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

def test_frontend():
    driver = webdriver.Chrome()
    driver.get("http://localhost:3001")
    assert "Task List" in driver.title
    driver.close()

if __name__ == "__main__":
    test_frontend()

Passo 3. Avvio del test di integrazione:

Per avviare il test di integrazione usa il comando:

Terminal

python tests/test_integration.py

8.4 Debug

Per fare debug puoi usare i log dei container e degli strumenti di monitoring.

Visualizzazione dei log dei container

Per vedere i log utilizza il comando:

Terminale

docker compose logs

Utilizzo degli strumenti di monitoring

Usa Prometheus e Grafana configurati in precedenza per monitorare le metriche e lo stato dei servizi.

  1. Accedi all'interfaccia web di Grafana: Apri il browser e vai all'indirizzo http://localhost:3033.
  2. Controlla le dashboard: Usa le dashboard create per monitorare le performance e lo stato dei servizi.
Commenti
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION