在尝试在python中获得TDD的预感时,我遇到了这个FunctionTestCase类.我明白,它定义了TestCase类的等效函数.
assertEqual = failUnlessEqual(self, first, second, msg=None)
assertNotEqual = failIfEqual(self, first, second, msg=None)
# and so on...
Run Code Online (Sandbox Code Playgroud)
使用中是否存在显着差异,FunctionTestCase或者是味道问题?
我必须模拟如下所示的方法:
import json
def some_method(self):
output_one = json.loads(varone)
output_two = json.loads(vartwo)
Run Code Online (Sandbox Code Playgroud)
import json
self.stubs = stubout.StubOutForTesting()
self.stubs.Set(json, "loads", lambda *a: output_one)
self.stubs.Set(json, "loads", lambda *a: output_two)
Run Code Online (Sandbox Code Playgroud)
结果是看到只有output_two因为output_one被覆盖了。我应该如何模拟一个方法两次并期望每次都有不同的输出。
我写了一个python模块,它依赖于我的CI测试机上没有的第三方软件包,因此我无法远程测试我的模块,因为我无法通过该import dependency语句.
如果我们假设我无法在CI主机上手动安装依赖项(看起来很痛苦),那么伪造/模拟/删除任何缺少的第三方软件包的最简单方法是什么,以便我可以测试我的代码?
我只使用依赖项提供的单个类,所以我很乐意只是模拟该对象,如果有办法那样做,而不是整个模块.
我正在尝试为调用subprocess.Popen. 我只想测试arg发送到的参数Popen是否符合预期。我其实不想Popen跑。在不嘲笑arg列表的情况下这可能吗?
例如
def call_something(argument_list):
binary = '/opt/mybin/'
Popen([binary] + argument_list)
Run Code Online (Sandbox Code Playgroud)
然后,进行测试。
@mock.patch('subprocess.Popen')
def test_call_something(self, mock_popen):
binary = '/opt/mybin/'
args = ['foo', 'bar']
mock_popen.return_value.returncode = 0
mock_popen.return_value.communicate.return_value = ('Running', '')
call_something(args)
self.assertEqual(
[binary] + args,
mock_popen.call_args_list
)
Run Code Online (Sandbox Code Playgroud)
我在这里遇到的问题是,首先调用二进制文件(我不想要),其次call_args_list是空的。
我想测试的这个演示功能非常简单。
def is_email_deliverable(email):
try:
return external.verify(email)
except Exception:
logger.error("External failed failed")
return False
Run Code Online (Sandbox Code Playgroud)
此功能使用external我想模拟的服务。
但我无法弄清楚如何exception从external.verify(email) 即如何强制except执行该子句。
我的尝试:
@patch.object(other_module, 'external')
def test_is_email_deliverable(patched_external):
def my_side_effect(email):
raise Exception("Test")
patched_external.verify.side_effects = my_side_effect
# Or,
# patched_external.verify.side_effects = Exception("Test")
# Or,
# patched_external.verify.side_effects = Mock(side_effect=Exception("Test"))
assert is_email_deliverable("some_mail@domain.com") == False
Run Code Online (Sandbox Code Playgroud)
这个问题声称有答案,但对我不起作用。
我正在创建测试以检查自定义校准模型保存功能是否更新资产记录(外键),如果它是资产的最新校准记录。save 函数在实时开发和生产服务器中甚至在 django shell 中都完全按预期执行,但在测试期间似乎失败了...
模型.py
class Asset(models.Model):
...
requires_calibration = models.BooleanField()
passed_calibration = models.BooleanField(default=False)
calibration_date_prev = models.DateField(null=True, blank=True)
calibration_date_next = models.DateField(null=True, blank=True)
class CalibrationRecord(models.Model):
calibration_record_id = models.AutoField(primary_key=True)
asset = models.ForeignKey(
"myapp.Asset",
on_delete=models.CASCADE,
limit_choices_to={"requires_calibration": True}
)
calibration_date = models.DateField(default=timezone.now)
calibration_date_next = models.DateField(null=True, blank=True)
calibration_outcome = models.CharField(max_length=10, default="Pass")
def save(self, *args, **kwargs):
super(CalibrationRecord, self).save(*args, **kwargs)
# Check if this is the latest calibration record for any asset, if so update asset.calibration_dates and status
latest_asset_calibration = CalibrationRecord.objects.filter(asset=self.asset.pk).order_by(
"-calibration_date", "-calibration_record_id")[0]
if self.pk == …Run Code Online (Sandbox Code Playgroud) django django-models django-testing django-unittest python-unittest
我在其中创建了自定义异常 errors.py
mapper = {
'E101':
'There is no data at all for these constraints',
'E102':
'There is no data for these constraints in this market, try changing market',
'E103':
'There is no data for these constraints during these dates, try changing dates',
}
class DataException(Exception):
def __init__(self, code):
super().__init__()
self.msg = mapper[code]
def __str__(self):
return self.msg
Run Code Online (Sandbox Code Playgroud)
DataException如果数据pandas帧中没有足够的数据,代码中其他地方的另一个函数会引发不同的实例.我想用unittest它来确保它返回相应的异常及其相应的消息.
使用一个简单的例子,为什么这不起作用:
from .. import DataException
def foobar():
raise DataException('E101')
import unittest
with unittest.TestCase.assertRaises(DataException):
foobar()
Run Code Online (Sandbox Code Playgroud)
正如这里建议的那样:Python assertRaises用户定义的异常 …
我希望有人可以帮助我。
我必须在烧瓶 api 中使用 Python 的单元测试编写单元测试。我有一个登录路由,当通过带有 React 前端的应用程序访问它时,它工作得非常好,但是每当我尝试从测试中发布时,request.authorization 是 None ......它让我发疯
我查看了整个互联网并尝试了很多不同的方法,但是无论我做什么,进行测试时 request.authorization 始终为 None
测试:
import unittest
import base64
from backend.peace_api import app
class TestLogin(unittest.TestCase):
# Assert login() with correct authentication
def test_login(self):
with app.app_context():
tester = app.test_client(self)
auth = 'seo@hotmail.com:password'
authheader = base64.b64encode(bytes(auth, 'UTF-8'))
headers = {"HTTP_AUTHORIZATION": "Bearer " + str(authheader), "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"}
response = tester.post('/api/login/', headers=dict(headers))
print(response.json)
self.assertEqual(response.status_code, 200)
if __name__ == '__main__':
unittest.main()
Run Code Online (Sandbox Code Playgroud)
路线 :
import jwt
import datetime
from flask import Blueprint, request, jsonify
from …Run Code Online (Sandbox Code Playgroud) 这是示例测试:
import a
import b
import c
import mock
from django.test import TestCase
@mock.patch.object(a, "method_a")
@mock.patch.object(b, "method_b")
@mock.patch.object(c, "method_c")
class SomeTestCase(TestCase):
def setUp(self):
# I want to set mock_method_a.return_value = 1 once here (or not here, but once)
pass
def test_one(self, mock_method_a, mock_method_b, mock_method_c):
mock_method_a.return_value = 1
mock_method_b.return_value = 2
pass # some test stuff
def test_two(self, mock_method_a, mock_method_b, mock_method_c):
mock_method_a.return_value = 1
mock_method_b.return_value = 2
pass # some test stuff
def test_three(self, mock_method_a, mock_method_b, mock_method_c):
mock_method_a.return_value = 1
mock_method_b.return_value …Run Code Online (Sandbox Code Playgroud) 我知道Python unittest。我有一些使用它测试Python子程序的经验。
现在,我需要添加测试用Python编写的命令行应用程序(而不仅仅是Python函数)。我想用stdin中的某些参数和某些输入以及stdout中的测试输出来调用它。
如何将测试命令行工具与其他unittest测试用例集成在一起?
还是用什么代替unittest?
python unit-testing command-line-interface python-unittest python-3.6
python-unittest ×10
python ×9
unit-testing ×3
django ×2
mocking ×2
python-mock ×2
assertraises ×1
flask ×1
python-3.5 ×1
python-3.6 ×1
python-3.x ×1
subprocess ×1
testcase ×1