我是 Python 单元测试的新手,我不确定如何创建此函数的单元测试以返回连接?
def connection(self):
connection = mysql.connector.connect(host='localhost',
database='test',
user='user',
password='password',
auth_plugin='mysql_native_password')
return connection
Run Code Online (Sandbox Code Playgroud) python python-unittest mysql-connector-python python-unittest.mock
当为 CodeBuild 编写 Python Boto3 单元测试时,是否可以先 start_build() 然后 wait() 等待构建完成,然后再评估我的测试是否通过?通常,我只使用服务员,但据我所知,CodeBuild 没有任何服务员(我执行了 client.waiter_names 并得到了一个空数组,并且 Boto3 文档没有列出 CodeBuild 客户端的任何服务员)。
我发现了这个(重复的)问题,但答案并没有解决如何实际解决等待问题 - 它只是说如何检查构建的状态。如果我能以某种方式 wait() 直到状态更改为某个值,那将很有用。
我正在帮助我的团队将他们的应用程序从 python 2 升级到 3,但在单元测试中遇到了错误。当我使用以下命令运行测试时:
python3 manage.py test groupapp --settings=settings.deploy_dev
Run Code Online (Sandbox Code Playgroud)
我收到以下错误。但如果我运行:
python3 manage.py test groupapp.tests --settings=settings.deploy_dev
Run Code Online (Sandbox Code Playgroud)
错误不会发生。值得注意的是,即使我从测试文件夹中删除了所有测试,这些错误也会发生,并且据我所知,它们没有连接到实际的测试用例。
我不明白 python 3 中这两个调用之间的区别。在 python 2 中,如果我运行这两个调用,我会得到相同的结果(没有测试失败)。
groupapp_v2.groupapp.admin (unittest.loader._FailedTest) ... ERROR
groupapp_v2.groupapp.models (unittest.loader._FailedTest) ... ERROR
======================================================================
ERROR: groupapp_v2.groupapp.admin (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: groupapp_v2.groupapp.admin
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 462, in _find_test_path
package = self._get_module_from_name(name)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 369, in _get_module_from_name
__import__(name)
File "/Users/matthew/bitbucket/consortium-website/groupapp_v2/groupapp/admin/__init__.py", line 73, in <module>
admin.site.register(Grid, GridAdmin)
File "/Users/matthew/virtualenv/groupapp-python3.6/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 110, in register
raise …Run Code Online (Sandbox Code Playgroud) 我在 python 文件中有以下代码。我必须对该文件进行单元测试。但为了做到这一点,我需要实例化该类的对象
class BigQuery(metaclass=singleton.Singleton):
"""
Big Query Class for operations on big query
Will standardize in future versions.
"""
def __init__(self):
"""
Used for initializing client
"""
try:
self.client = bigquery.Client.from_service_account_json(
SERVICE_ACCOUNT_JSON)
except:
logging.error("Cannot instantiate bigquery client", exc_info=True)
raise Exception("Cannot instantiate bigquery client.")
Run Code Online (Sandbox Code Playgroud)
上面的类还包含其他需要测试的方法。如何在不调用 bigquery API 的情况下模拟每个方法的对象?
mocking python-3.x google-bigquery python-unittest python-unittest.mock
这是获取版本并与 open 一起使用以从文件路径位置读取文件的函数。
def get_version(self):
try:
with open("file_path") as openfile:
for line in openfile:
sline = line.split()
for row, column in enumerate(sline):
if column == "version=":
version = sline[row+1].strip('"')
return version
Run Code Online (Sandbox Code Playgroud) 我正在使用 Python 中的单元测试框架对圆的半径进行单元测试。如果半径不是数值,那么我会使用自定义消息引发异常。
文件:圆.py
class Circle():
def __init__(self, radius):
if not isinstance (radius, (int,float)):
raise TypeError('radius must be a number')
else:
self.radius = radius
Run Code Online (Sandbox Code Playgroud)
文件:test_circle.py
import unittest
from circle import Circle
class CircleTest(unittest.TestCase):
def test_radius(self):
c1 = Circle(2.5)
self.assertEqual(c1.radius, 2.5)
def test_radius_type(self):
self.assertRaises(TypeError, Circle, 'hello')
if __name__ == "__main__":
unittest.main()
Run Code Online (Sandbox Code Playgroud)
现在,我可以检查引发的异常。但是,我还想知道异常中传递的消息是否是准确的消息。谁能指导我如何在Python的unittest中测试和检查异常中传递的消息?
如何修补或模拟“任何未直接调用/使用的函数”?
我有一个简单的单元测试片段
# utils/functions.py
def get_user_agents():
# sends requests to a private network and pulls data
return pulled_data
# my_module/tasks.py
def create_foo():
from utils.functions import get_user_agents
value = get_user_agents()
# do something with value
return some_value
# test.py
class TestFooKlass(unittest.TestCase):
def setUp(self):
create_foo()
def test_foo(self):
...Run Code Online (Sandbox Code Playgroud)
在方法中,我通过调用间接setUp()调用get_user_agents()函数。在此执行过程中,由于尝试访问专用网络,我遇到了异常。那么,在测试过程中如何操作返回数据或整个函数呢?create_foo()socket.timeoutget_user_agents()get_user_agents
另外,有什么方法可以在整个测试套件执行期间保留这个模拟/补丁吗?
我正在尝试使用 python 框架进行处理 csv 文件的单元测试unittest。我想测试列名称匹配、列中的值匹配等情况。我知道有更方便的库,例如datatest和pytest,但我只能unittest在我的项目中使用。
猜猜我使用了错误的unittest.TestCase方法,并以错误的格式发送数据。请建议如何做得更好。
db.csv 示例:
TIMESTAMP TYPE VALUE YEAR FILE SHEET
0 02-09-2018 Index 45 2018 tq.xls A01
1 13-05-2018 Index 21 2018 tq.xls A01
2 22-01-2019 Index 9 2019 aq.xls B02
Run Code Online (Sandbox Code Playgroud)
这是代码示例:
import pandas as pd
import unittest
class DFTests(unittest.TestCase):
def setUp(self):
test_file_name = 'db.csv'
try:
data = pd.read_csv(test_file_name,
sep = ',',
header = 0)
except IOError:
print('cannot open file')
self.fixture = data
#Check column names …Run Code Online (Sandbox Code Playgroud) 我正在尝试实现一些单元测试来验证包含for循环的方法。此方法接收一个项目列表,并为每个项目执行一个foo()以该项目作为参数的函数。
有谁知道如何模拟该foo()函数以根据作为输入提供的元素动态提供模拟的返回值?
方法:
def foo(i):
if i == 'this':
return 'a'
else:
return 'b'
def bar(items):
results = []
for item in items:
results.append(foo(item))
return results
Run Code Online (Sandbox Code Playgroud)
单元测试:
from unittest import TestCase
from mock import patch
class TestCaseBar(TestCase):
@patch('my_module.foo')
def test_bar(self, mock_foo):
mock_foo.return_value = 'dummy' # I would like to dinamically mock this.
items = ['this', 'that']
result = bar(items)
self.assertEqual(result, ['a', 'b'])
self.assertTrue(mock_foo.call_count, 2)
Run Code Online (Sandbox Code Playgroud)
预先感谢您的回答。
我正在编写一个将在我的班级代码上运行的单元测试。对于他们必须编写的函数之一,他们可以返回两种可能的返回值,其中任何一种都适合我的目的。
我一直在使用
actual = my_function_call(arg1, arg2)
self.assertEqual(actual, expected)
Run Code Online (Sandbox Code Playgroud)
但这不适用于接受两个有效返回值之一,因此我将其更改为:
actual = my_function_call(arg1, arg2)
self.assertEqual(actual == expected1 or actual == expected2, True)
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以做到这一点而不那么hacky?
python-unittest ×10
python ×7
mocking ×3
python-3.x ×3
unit-testing ×3
boto3 ×1
dataframe ×1
django ×1
pandas ×1
python-mock ×1