我正在尝试在 Flask 应用程序上运行单元测试,该应用程序利用公钥和私钥生成 JWT 令牌。但是,在运行单元测试时,我收到 FileNotFoundError ,指示找不到私钥文件。
这是我的项目的结构:
project/
│
├── app/
│ ├── __init__.py
│ ├── user.py
│ ├── news.py
│ ├── public_key.pem
│ └── private_key.pem
│
└── tests/
├── __init__.py
└── test_app.py
private_key.pem 文件用于在 Flask 应用程序中对 JWT 令牌进行签名。但是,在运行单元测试时,我收到以下错误:
FileNotFoundError: [Errno 2] No such file or directory: 'private_key.pem'
这是加载私钥的代码片段:
# Load the private key
with open('private_key.pem', 'r') as f:
private_key = f.read()
我的终端:
PS C:\Users\ferre\Projects\Portal-de-Noticias> & c:/Users/ferre/Projects/Portal-de-Noticias/.venv/Scripts/python.exe c:/Users/ferre/Projects/Portal-de-Noticias/backend/user_registration/test_app.py
Arquivo public_key.pem não encontrado.
Traceback (most recent call last):
File "c:\Users\ferre\Projects\Portal-de-Noticias\backend\user_registration\test_app.py", line 4, in <module>
from user import user_bp
File "c:\Users\ferre\Projects\Portal-de-Noticias\backend\user_registration\user.py", line 54, in <module>
with open('private_key.pem', 'r') as f:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'private_key.pem'
PS C:\Users\ferre\Projects\Portal-de-Noticias>
我的测试代码:
import unittest
from flask import Flask
from flask_cors import CORS
from user import user_bp
from noticias import noticias_bp
class TestApp(unittest.TestCase):
def setUp(self):
# Configurar a aplicação Flask para testes
self.app = Flask(__name__)
CORS(self.app)
self.app.secret_key = '2002'
self.app.register_blueprint(user_bp)
self.app.register_blueprint(noticias_bp)
# Configurar o cliente de teste
self.client = self.app.test_client()
def test_user_blueprint_registration(self):
# Verificar se o blueprint do usuário está registrado na aplicação Flask
self.assertIn('user', self.app.blueprints)
def test_noticias_blueprint_registration(self):
# Verificar se o blueprint de notícias está registrado na aplicação Flask
self.assertIn('noticias', self.app.blueprints)
def test_user_blueprint_routes(self):
# Testar se as rotas do blueprint do usuário estão acessíveis
response = self.client.get('/user/')
self.assertEqual(response.status_code, 200)
response = self.client.get('/user/profile')
self.assertEqual(response.status_code, 200)
def test_noticias_blueprint_routes(self):
# Testar se as rotas do blueprint de notícias estão acessíveis
response = self.client.get('/noticias/')
self.assertEqual(response.status_code, 200)
response = self.client.get('/noticias/latest')
self.assertEqual(response.status_code, 200)
if __name__ == '__main__':
unittest.main()
如何解决这个问题并使我的单元测试正常工作?我应该将私钥直接包含在测试代码中,还是有更好的方法来处理这个问题?
预先感谢您的帮助!
当您从 shell 运行代码时,您仍在工作目录
C:\Users\ferre\Projects\Portal-de-Noticias
中,但密钥位于 app
文件夹中。
尝试使用
app/private_key.pem
或在测试运行之前导航到应用程序