CodeGym /Các khóa học /Docker SELF /Kiểm thử và gỡ lỗi ứng dụng

Kiểm thử và gỡ lỗi ứng dụng

Docker SELF
Mức độ , Bài học
Có sẵn

8.1 Kiểm thử frontend

Ở giai đoạn này, chúng ta sẽ xem xét cách thực hiện kiểm thử và debug cho ứng dụng đa container của chúng ta. Việc kiểm thử giúp tìm ra và sửa lỗi, cũng như đảm bảo tất cả các thành phần của hệ thống hoạt động đúng.

Để kiểm thử frontend bằng ReactJS, chúng ta sẽ sử dụng thư viện Jest và React Testing Library.

Cài đặt Jest và React Testing Library

Bước 1. Cài đặt dependencies:

Terminal

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

Bước 2. Cấu hình Jest:

Tạo file jest.config.js trong thư mục frontend:

Javascript

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

Bước 3. Tạo file setupTests.js:

Tạo file setupTests.js trong thư mục frontend/src:

Javascript

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

Bước 4. Viết test cho các component

Tạo file test cho component TaskList trong thư mục 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();
});

Bước 5. Chạy các test

Để chạy các test, sử dụng lệnh sau:

Terminal

npm test

8.2 Kiểm thử backend

Để kiểm thử backend dùng Flask, tụi mình sẽ dùng thư viện unittest.

Cài đặt dependencies:

Terminal

cd ../backend
pip install Flask-Testing

Viết test cho các endpoint

Tạo thư mục tests và file test_routes.py trong thư mục 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': 'Công việc thử nghiệm',
            'description': 'Miêu tả thử nghiệm',
            'owner_id': 1,
            'status': 'chưa hoàn thành'
        }, headers={'Authorization': f'Bearer {access_token}'})
        self.assertEqual(response.status_code, 201)

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

Chạy test

Để chạy test, sử dụng lệnh:

Terminal

python -m unittest discover

8.3 Kiểm thử tích hợp

Kiểm thử tích hợp kiểm tra sự tương tác giữa các thành phần trong hệ thống.

Cài đặt môi trường kiểm thử

Để kiểm thử tích hợp, chúng ta sẽ sử dụng Docker Compose để chạy tất cả các dịch vụ trong môi trường kiểm thử.

Bước 1. Tạo tệp Docker Compose cho kiểm thử:

Tạo tệp docker-compose.test.yml trong thư mục gốc của dự án:

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:

Bước 2. Khởi động môi trường kiểm thử:

Để khởi động tất cả các dịch vụ trong môi trường kiểm thử, sử dụng lệnh sau:

Terminal

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

Viết kiểm thử tích hợp

Bạn có thể viết kiểm thử tích hợp bằng cách sử dụng các công cụ khác nhau. Một trong những cách là sử dụng Selenium để kiểm thử giao diện người dùng tự động.

Bước 1. Cài đặt Selenium:

Terminal

pip install selenium

Bước 2. Viết kiểm thử tích hợp:

Tạo tệp test_integration.py trong thư mục 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()

Bước 3. Khởi chạy kiểm thử tích hợp:

Để khởi chạy kiểm thử tích hợp, sử dụng lệnh sau:

Terminal

python tests/test_integration.py

8.4 Debug

Để debug, bạn có thể sử dụng log của container và các công cụ giám sát.

Xem log của container

Để xem log, dùng lệnh:

Terminal

docker compose logs

Sử dụng các công cụ giám sát

Sử dụng Prometheus và Grafana đã được cấu hình từ trước để giám sát các metric và trạng thái của dịch vụ.

  1. Truy cập giao diện web Grafana: Mở trình duyệt và truy cập vào địa chỉ http://localhost:3033.
  2. Xem các dashboard: Sử dụng các dashboard đã tạo để theo dõi hiệu suất và trạng thái của dịch vụ.
Bình luận
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION