estou tentando melhorar meus testa, atualmente, tenho esse arquivo import unittest…
- User
estou tentando melhorar meus testa, atualmente, tenho esse arquivo import unittest import sys import os sys.path.append(os.path.abspath(os.path.join(os.path.dirname(file), '..')))
from app import app
class TestPing(unittest.TestCase): def setUp(self): app.testing = True
self.app = app.test_client()def test_ping(self): response = self.app.get('/ping') self.assertEqual(response.status_code, 200) self.assertEqual(response.json, {'status': 'up'})Teste de Verificação do Status com Ping:
- Objetivo: Este teste verifica se a rota /ping está respondendo corretamente e retornando o status “up”.
- Implementação:
- O teste configura a aplicação Flask em modo de teste e cria um cliente de teste para a mesma.
- Em seguida, ele faz uma solicitação GET para a rota /ping e verifica o código de status da resposta.
- O teste confirma se o status da resposta é 200, indicando que a rota está acessível e operante.
- Além disso, ele verifica se a resposta JSON contém o valor 'up' para o status, garantindo o funcionamento adequado da rota.
def test_error_handling_in_prediction_route(client): response = client.post('/predict') assert response.status_code == 400 # Verifique se o código de status reflete um erro de solicitação inválida def test_error_handling_in_result_route(client): response = client.get('/result') assert response.status_code == 400 # Verifique se o código de status reflete um erro de solicitação inválida def test_error_handling_in_graphs_route(client): response = client.get('/graphs') assert response.status_code == 500 # Verifique se o código de status reflete um erro interno do servidorif name == 'main': unittest.main()
mas ao executar, estou tendo os erros: th@1TL-23TI01:~/dev/unit$ /bin/python3 /home/th/dev/unit/tests/test_unit.py EEE.
ERROR: test_error_handling_in_graphs_route (main.TestPing)
Traceback (most recent call last): File "/home/th/dev/unit/tests/test_unit.py", line 34, in test_error_handling_in_graphs_route response = client.get('/graphs') AttributeError: 'TestPing' object has no attribute 'get'
====================================================================== ERROR: test_error_handling_in_prediction_route (main.TestPing)
Traceback (most recent call last): File "/home/th/dev/unit/tests/test_unit.py", line 26, in test_error_handling_in_prediction_route response = client.post('/predict') AttributeError: 'TestPing' object has no attribute 'post'
====================================================================== ERROR: test_error_handling_in_result_route (main.TestPing)
Traceback (most recent call last): File "/home/th/dev/unit/tests/test_unit.py", line 30, in test_error_handling_in_result_route response = client.get('/result') AttributeError: 'TestPing' object has no attribute 'get'
Ran 4 tests in 0.004s
FAILED (errors=3) th@1TL-23TI01:~/dev/unit$
minha routes.py from flask import Blueprint, render_template, request, jsonify, redirect, url_for from utils import home, predict, get_salary_data_from_api, display_graphs import logging from flask import current_app prediction_routes = Blueprint('prediction_routes', name) @prediction_routes.route('/predict', methods=['POST']) def prediction(): try: current_app.logger.info('Submission received successfully') return predict(request)
except Exception as e: current_app.logger.error('Error in prediction route: %s', str(e))@prediction_routes.route('/ping') def ping(): try: return jsonify({'status': 'up'}) except Exception as e: current_app.logger.error('Error ing ping route: %s', str(e) ) return jsonify({'error': 'An error occured'}), 500
@prediction_routes.route('/') def index(): return home()
@prediction_routes.route('/result', methods=['GET']) def result(): try: predicted_salary = float(request.args.get('predicted_salary')) job_title = request.args.get('job_title') employee_residence = request.args.get('employee_residence') if predicted_salary is None or job_title is None or employee_residence is None: raise ValueError('Missing input data')
api_data = get_salary_data_from_api(job_title, employee_residence) formatted_predicted_salary = f"${predicted_salary:,.0f}" return render_template('result.html', predicted_salary=formatted_predicted_salary, api_data=api_data) except ValueError as e: current_app.logger.error('Error in result route: %s', str(e) ) return jsonify({'error': 'Invalid predicted salary provided'}), 400@prediction_routes.route('/graphs', methods=['GET']) def graphs(): try: return display_graphs() except Exception as e: current_app.logger.error('Error in graphs route: %s', str(e)) return jsonify({'error': 'An error occurred'}), 500
@prediction_routes.route('/report', methods=['GET']) def report(): try: return render_template('report.html') except Exception as e: current_app.logger.error('Error in predictions route: %s', str(e)) return jsonify({'error': 'An error occurred'}), 500
- Assistant
Os erros que você está recebendo indicam que o objeto
clientnão está sendo definido corretamente no seu arquivo de testes. Isso ocorre porque você não está passando o cliente da sua aplicação Flask para os métodos de teste.Para corrigir isso, você pode modificar os métodos de teste para receber o cliente como parâmetro. Assim, você poderá passar o cliente de teste da sua aplicação Flask para os métodos de teste.
Aqui está como você pode modificar seus métodos de teste:
class TestPing(unittest.TestCase): def setUp(self): app.testing = True self.app = app.test_client() ... def test_error_handling_in_prediction_route(self): response = self.app.post('/predict') assert response.status_code == 400 # Verifique se o código de status reflete um erro de solicitação inválida def test_error_handling_in_result_route(self): response = self.app.get('/result') assert response.status_code == 400 # Verifique se o código de status reflete um erro de solicitação inválida def test_error_handling_in_graphs_route(self): response = self.app.get('/graphs') assert response.status_code == 500 # Verifique se o código de status reflete um erro interno do servidorCertifique-se de chamar os métodos de teste corretamente após essas modificações para verificar se os erros foram corrigidos. Isso deve resolver os erros que você está enfrentando ao executar seus testes.