我正在尝试使用unittest.mock,但出现错误:
\n\n\nAttributeError:没有属性“get_pledge_Frequency”
\n
我有以下文件结构:
\n\npledges/views/\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 __init__.py\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 util.py\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 user_profile.py\npledges/tests/unit/profile\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 __init__.py\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 test_user.py\nRun Code Online (Sandbox Code Playgroud)\n\n里面pledges/views/__init___.py我有:
from .views import *\nfrom .account import account\nfrom .splash import splash\nfrom .preferences import preferences\nfrom .user_profile import user_profile\nRun Code Online (Sandbox Code Playgroud)\n\n在里面,user_profile.py我有一个名为的函数user_profile,它调用内部的函数util.py,如下get_pledge_frequency所示:
def user_profile(request, user_id):\n # some logic\n\n # !!!!!!!!!!!!!!!!\n a, b = get_pledge_frequency(parameter) # this is the function I want to mock\n\n # more logic\n\n return some_value\nRun Code Online (Sandbox Code Playgroud)\n\n我里面有一个测试test_user.py如下:
def …Run Code Online (Sandbox Code Playgroud) 我想测试一些错误处理逻辑,所以我想在单元测试中模拟特定的异常类型。我正在模拟对 boto3 的调用,但我想进行该模拟以引发异常ParameterNotFound。我正在测试的代码遵循以下模式:
boto3_client = boto3.client('ssm')
try:
temp_var = boto3_client.get_parameter(Name="Something not found")['Parameter']['Value']
except boto3_client.exceptions.ParameterNotFound:
... [logic I want to test]
Run Code Online (Sandbox Code Playgroud)
我创建了一个单元测试模拟,但我不知道如何使其引发异常作为此 ParameterNotFound 异常。我尝试了以下方法,但它不起作用,因为在评估 except 子句时它得到“异常必须从基类派生”:
@patch('patching_config.boto3.client')
def test_sample(self, mock_boto3_client):
mock_boto3_client.return_value = mock_boto3_client
def get_parameter_side_effect(**kwargs):
raise boto3.client.exceptions.ParameterNotFound()
mock_boto3_client.get_parameter.side_effect = get_parameter_side_effect
Run Code Online (Sandbox Code Playgroud)
如何在单元测试中模拟 ParameterNotFound boto3 异常?
我正在使用发现模式运行 Python 单元测试:
% python -m unittest discover
Run Code Online (Sandbox Code Playgroud)
系统为每个测试打印一个点,但我宁愿看到测试名称。
有没有一个选项可以实现这种情况?
请检查以下代码:
import unittest
CORRECT_MESSAGE = 'Correct message'
WRONG_MESSAGE = 'Wrong message'
def fn():
raise KeyError(CORRECT_MESSAGE)
class Test(unittest.TestCase):
def test(self):
# I am expecting this test to fail as the msg I am
# checking is WRONG_MESSAGE, and not CORRECT_MESSAGE.
with self.assertRaises(KeyError, msg=WRONG_MESSAGE):
fn()
unittest.main()
Run Code Online (Sandbox Code Playgroud)
正如评论中提到的,我预计此测试会失败,因为我正在检查的消息 ( WRONG_MESSAGE) 不正确,但测试通过了。
我缺少什么?我已经检查过:assertRaises(exception, *, msg=None)。
我有一个名为的文件redis_db.py,其中包含连接到 redis 的代码
import os
import redis
import sys
class Database:
def __init__(self, zset_name):
redis_host = os.environ.get('REDIS_HOST', '127.0.0.1')
redis_port = os.environ.get('REDIS_PORT', 6379)
self.db = redis.StrictRedis(host=redis_host, port=redis_port)
self.zset_name = zset_name
def add(self, key):
try:
self.db.zadd(self.zset_name, {key: 0})
except redis.exceptions.ConnectionError:
print("Unable to connect to redis host.")
sys.exit(0)
Run Code Online (Sandbox Code Playgroud)
我有另一个名为 app.py 的文件,如下所示
from flask import Flask
from redis_db import Database
app = Flask(__name__)
db = Database('zset')
@app.route('/add_word/word=<word>')
def add_word(word):
db.add(word)
return ("{} added".format(word))
if __name__ == '__main__':
app.run(host='0.0.0.0', port='8080')
Run Code Online (Sandbox Code Playgroud)
现在我正在为 add_word 函数编写单元测试,如下所示 …
我希望无论传入什么内容,以下调用which_user都会返回,但它的行为就好像它根本没有被嘲笑一样。self.user
def test_user_can_retrieve_favs_using_impersonation(self):
with mock.patch('impersonate.helpers.which_user', return_value=self.user):
user = which_user(self.user2)
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么?我which_user像这样导入:from impersonate.helpers import which_user如果有帮助的话。
python django django-testing python-unittest python-unittest.mock
我需要在整个测试套件运行后或在整个测试退出时执行命令。我在unittest中看到tearDownhook ,但在ruby中没有after-testsuite hook或类似的东西。at_exit
有什么方法我可以遵循吗unittest?pytest或对此进行任何调整
我有以下(简化的)FBV:
def check_existing_contacts(request):
if request.is_ajax and request.method == "GET":
print('Function called')
return mailgun_validate_email(request)
return JsonResponse({"error": "Incorrect AJAX / GET request."}, status=400)
Run Code Online (Sandbox Code Playgroud)
我想测试该mailgun_validate_email函数是否被调用:
class TestCheckExistingContacts(TestCase):
@patch('myapp.mailgun_validate_email')
def test_new_contact(self, mock):
client = Client()
client.get('/check/', HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertTrue(mock.called)
Run Code Online (Sandbox Code Playgroud)
我确信测试调用如控制台中显示的mailgun_validate_email那样。print('Function called')但是我收到一个断言错误,该错误mock.called是False.
我哪里出错了/我该如何调试?
************更新*******************
当在与视图相同的模块中修补函数时,出现以下错误:
class TestCheckExistingContacts(TestCase):
@patch('[path to views.py with check_existing_contacts].mailgun_validate_email')
def test_new_contact(self, mock):
client = Client()
client.get('/check/', HTTP_X_REQUESTED_WITH='XMLHttpRequest')
self.assertTrue(mock.called)
Run Code Online (Sandbox Code Playgroud)
结果是:
Failure
Traceback (most recent call last):
File "\tests\test_utils.py", line 123, in test_new_contact …Run Code Online (Sandbox Code Playgroud) 我有这个测试程序在 Python 3.8.3 中运行
import unittest
import logging
class logging_TestCase (unittest.TestCase):
def test_logging(self):
with self.assertLogs() as cm:
logging.Logger('test').error("A test error message")
Run Code Online (Sandbox Code Playgroud)
然后我运行这个:
% python -m unittest dummy.py
Run Code Online (Sandbox Code Playgroud)
并得到这个。请注意,我的测试消息正在写出,但格式错误。也许这就是上下文管理器丢失的原因?这是我的全部代码,所以我看不到在哪里更改格式。
A test error message
F
======================================================================
FAIL: test_logging (dummy.logging_TestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/raysalemi/PycharmProjects/pyuvm/tests/dummy.py", line 7, in test_logging
logging.Logger('test').error("A test error message")
AssertionError: no logs of level INFO or higher triggered on root
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
(base) raysalemi@WriteNow tests % cat dummy.py
import unittest …Run Code Online (Sandbox Code Playgroud) 我可以使用以下命令运行烧瓶测试python -m unittest discover -p testing.py,但是当我尝试运行时,python app.py runserver它会显示以下错误消息:
Traceback (most recent call last):
File "app.py", line 10, in <module>
from models import db
File "/home/paula/projects/envioclicktest/restaurant_flask/models.py", line 1, in <module>
from app import app as app
File "/home/paula/projects/envioclicktest/restaurant_flask/app.py", line 10, in <module>
from models import db
ImportError: cannot import name 'db' from partially initialized module 'models'
(most likely due to a circular import) (/home/paula/projects/envioclicktest/restaurant_flask/models.py)
Run Code Online (Sandbox Code Playgroud)
我的项目结构如下:
-restaurant_flask
|-app.py
|-models.py
|-testing.py
Run Code Online (Sandbox Code Playgroud)
这是我的文件的内容以及我认为在每个文件中造成麻烦的行
from flask import Flask
from flask_script …Run Code Online (Sandbox Code Playgroud) python ×10
python-unittest ×10
python-3.x ×3
django ×2
boto3 ×1
flask ×1
mocking ×1
pytest ×1
python-mock ×1
unit-testing ×1