假设我有一个python函数
def func(self):
self.method_1()
self.method_2()
如何编写单元测试来断言在method_2之前调用了method_1?
@mock.patch(method_1)
@mock.patch(method_2)
def test_call_order(method_2_mock, method_1_mock):
# Test the order
我试图为我的python脚本编写单元测试,它使用sqlalchemy连接到MySQL。
我的功能如下:
def check_if_table_exists(db):
with db.connect() as cursor:
table_exists = cursor.execute(f"SHOW TABLES LIKE '{PRIMARY_TABLE_NAME}';")
if not table_exists.rowcount:
cursor.execute(f"CREATE TABLE..
我正在尝试理解Python,以便更好地对我的代码进行单元测试。我过去没有做过太多的单元测试,但我想强调一下它的前进方向。"with mock.patch(‘某事’)作为模拟:“语法对于模拟我的代码正在使用的对象来说似乎非常方便。这对于模拟数据库或API调用特别方便。
然而,我注意到,随着我编写的测试数量的增加,我测试中的重复也在增加。如果我的类中有多个需要被模拟的类(下面是MyClass),我需要对它们进行多个测试的模拟,即使它们不是直接用于特定的测试。例如:
with context("my test"):
with it('responds true
我执行以下输入验证检查:
self.path = kwargs.get('path', default_path)
if not os.path.isdir(self.path):
raise ValueError(msg1)
if not os.access(self.path, os.W_OK):
raise ValueError(msg2)
测试它的最佳方法是什么(在单元测试中)?
澄清:我想检查以下几点:
如果path不是directoryfunction,则函数应引发ValueError,如果path是不可写的目录,则应引发ValueErr
我试图用Python语言解决一个在线编码问题,提交所需的I/O是简单的input()和print()。由于我很懒,并且不想为了运行单元测试而将I/O替换为方法参数,那么我如何创建一个允许我替换预设字符串作为输入的单元测试呢?例如:
class Test(TestCase):
__init__(self):
self.input = *arbitrary input*
def test(self):
c = Class_Being_Tested()
c.main()
...make self.input the re
我如何mock.patch一个普通字典{}?
我想检查标题是否设置为{‘Content’:‘application/json’}。
def get(self):
result = Spider.get_news_urls()
for k, v in result.iteritems():
response = requests.get(v)
xml = response.text()
headers = {'Content-Type': 'application/json'}
dat
我正在使用Mock进行Python单元测试。我正在测试一个函数foo,它包含一个不返回任何内容的函数bar,但会填充一个变量x (type:io.StringIO)作为副作用。我曾使用MagicMock模拟过bar,但我不知道如何从测试脚本中将其分配给x。
我有以下情况:
def foo():
x = io.StringIO()
bar(x) # x is filled with some string by bar method
here some operation on x
要为foo编写单元测试用例,我用MagicMock (返回
我正尝试在单元测试中使用Python的mock库,但是我看到了不一致的结果,这取决于我如何导入我试图修补的目标。我期望这两个print语句都返回False,但似乎只有第二个语句返回False
from requests import get
import requests
with mock.patch('requests.get') as get_mock:
get_mock.return_value.ok = False
print get('http://asdf.com').ok
print requests.get('
因此,我知道在单元测试中我可以模拟上下文管理器open(),即: with open('file_path', 'r') as stats: 被嘲笑为 with mock.patch('builtins.open', mock.mock_open(read_data=mock_json)): 但是有没有办法让我只模拟特定的文件路径呢?或者使用其他方法来确保在单元测试中使用正确的路径调用上下文管理器?
我有一个模块,它使dynamoDB客户端的对象。模块是外部的,不属于我的代码。我正在尝试对enclosingClass进行单元测试
class enclosingClass:
def enclosing_function():
ddb_client = get_ddb_client(role)
ddb_client.query()
# Module in my code which returns dynamoDB client object
from x.y.common import get_aws_client
def get_ddb_client
TL;DR
如何修补或模拟“未被直接调用/使用的任何函数”?
西塞利奥
我有一个简单的单元测试片段
# 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()
# d
我正在尝试测试一个简单python函数的异常块,如下所示
function_list.py
def option_check():
"""
Function to pick and return an option
"""
try:
# DELETE_FILES_ON_SUCCESS is a config value from constants class. Valid values True/False (boolean)
flag = Constants.DELETE_FILES_ON_SUCCESS
if fla
我是Python新手,但我在C#和JavaScript中做了相当多的单元测试。我在用Python找出模拟框架时遇到了麻烦。以下是我所做的(删减):
invoice_business.py
import ims.repository.invoice_repository as invoiceRepository
import logging
logger = logging.getLogger(__name__)
def update_invoice_statuses(invoices):
for invoice in invoices:
dbInvoice = in