ユニットテスト(view URL遷移、ちゃんとできてっか?)
→ 最初に学ぶべき。
APIテスト(API、ちゃんと応答してっか?)
→ 二番目 restfulAPI時、必須
統合テスト(データベースやセッションできてっか?)
→ 三番目
エンドツーエンドテスト(アプリ全体正しい動き?)
→ 一番最後でok
viewテスト
from flask import Flask
import pytest
app = Flask(__name__)
@app.route('/hello')
def hello():
return 'Hello, World!'
def test_hello():
with app.test_client() as client:
response = client.get('/hello')
assert response.data == b'Hello, World!'
APIテスト
from flask import Flask, jsonify
import pytest
app = Flask(__name__)
@app.route('/api/user/<int:user_id>')
def get_user(user_id):
return jsonify({'id': user_id, 'name': 'User'})
def test_get_user():
with app.test_client() as client:
response = client.get('/api/user/1')
assert response.status_code == 200
assert response.json['id'] == 1
セッションテスト
from flask import Flask, session
import pytest
app = Flask(__name__)
app.secret_key = 'secret'
@app.route('/set_session/<name>')
def set_session(name):
session['name'] = name
return 'Session Set'
def test_set_session():
with app.test_client() as client:
client.get('/set_session/test')
with client.session_transaction() as sess:
assert sess['name'] == 'test'
エンドツーエンドTest
describe('Login test', () => {
it('should log in successfully', () => {
cy.visit('/login') // ログインページにアクセス
cy.get('input[name="username"]').type('testuser') // ユーザー名入力
cy.get('input[name="password"]').type('password123') // パスワード入力
cy.get('button[type="submit"]').click() // ログインボタンをクリック
cy.url().should('include', '/dashboard') // ダッシュボードページにリダイレクトされることを確認
cy.contains('Welcome, testuser') // ダッシュボードにユーザー名が表示されることを確認
})
})
☑️ etcテスト(未まとめ)
APIが、ユーザーIDを渡すとそのユーザー情報を返すかどうかをテスト
import requests
def test_get_user():
response = requests.get("http://api.example.com/users/1")
assert response.status_code == 200
assert response.json()["id"] == 1
存在しないユーザーIDを渡したときに404エラーが返るかテスト
def test_get_user_not_found():
response = requests.get("http://api.example.com/users/9999")
assert response.status_code == 404
APIの応答速度が3秒以内
def test_api_performance():
response = requests.get("http://api.example.com/large-dataset")
assert response.elapsed.total_seconds() < 3
✍️Cypress
describe('Login Test', () => {
it('should login successfully', () => {
// ログインページにアクセス
cy.visit('http://yourflaskapp.com/login')
// フォームに情報を入力
cy.get('input[name="username"]').type('testuser')
cy.get('input[name="password"]').type('password123')
// ログインボタンをクリック
cy.get('button[type="submit"]').click()
// ダッシュボードにリダイレクトされることを確認
cy.url().should('include', '/dashboard')
cy.contains('Welcome, testuser').should('be.visible')
})
})