gpt4 book ai didi

python - 尝试在方法上使用 mock.patch 时出现 ModuleNotFoundError

转载 作者:行者123 更新时间:2023-12-03 23:07:58 24 4
gpt4 key购买 nike

我的 pytest 单元测试不断返回错误 ModuleNotFoundError: No module name billing .

奇怪的是send_invoices当我删除补丁语句时,可以调用计费模块中的方法。如果是这种情况,为什么 mock.patch 无法找到计费模块并修补方法?
billing.py

import pdfkit
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
from projectxapp.models import User

Class Billing:

#creates a pdf of invoice. Takes an invoice dictionary
def create_invoice_pdf(self, invoice, user_id):
#get the html of the invoice
file_path ='/{}-{}.pdf'.format(user_id, invoice['billing_period'])
invoice_html = render_to_string('templates/invoice.html', invoice)
pdf = pdfkit.from_file(invoice_html, file_path)
return file_path, pdf

#sends invoice to customer
def send_invoices(self, invoices):
for user_id, invoice in invoices.items():
#get customers email
email = User.objects.get(id=user_id).email
billing_period = invoice['billing_period']
invoice_pdf = self.create_invoice_pdf(invoice, user_id)
email = EmailMessage(
'Statement of credit: {}-{}'.format(user_id, billing_period),
'Attached is your statement of credit.\
This may also be viewed on your dashboard when you login.',
'no-reply@trevoe.com',
[email],
).attach(invoice_pdf)

email.send(fail_silently=False)

return True
test.py
from mock import patch
from projectxapp import billing

@pytest.mark.django_db
def test_send_invoice():
invoices = {
1: {
'transaction_processing_fee': 2.00,
'service_fee': 10.00,
'billing_period': '2020-01-02'
},
2: {
'transaction_processing_fee': 4.00,
'service_fee': 20.00,
'billing_period': '2020-01-02'
}
}

with patch('services.billing.Billing().create_invoice_pdf') as p1:
p1.return_value = '/invoice.pdf'
test = billing.Billing().send_invoices(invoices)

assert test == True

最佳答案

当你使用 patch 时,你应该指定模块的完整路径,包括包名。 .另外,不要在路径中使用括号。修改return_value Mock 的属性对象自定义调用对象的返回值:

with patch('projectxapp.billing.Billing.create_invoice_pdf') as p1:
p1.return_value = '/invoice.pdf'
test = billing.Billing().send_invoices(invoices)

关于python - 尝试在方法上使用 mock.patch 时出现 ModuleNotFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61044136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com