py.测试模拟常量并在测试函数中引发异常

2024-10-01 15:39:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用py.测试还有嘲笑。我无法嘲笑一个常数。我的测试修改分配给常量的dict值。这应该会在我的测试中引发一个异常,但到目前为止还没有。我不确定问题出在哪里,希望您能帮我找出问题所在。谢谢您。在

在_模块.py

MY_DICT = {'one': 1, 'two': 2, 'three': 3}                                        

class OneMissingException(Exception):                                             
    pass                                                                          

class Test1(object):                                                              
    def __init__(self):                                                           
        self.mydict = MY_DICT                                                     

    @property                                                                     
    def mydict(self):                                                             
        return self._mydict                                                       

    @mydict.setter                                                                
    def mydict(self, mydict):                                                     
        if 'one' not in mydict:                                                   
            raise OneMissingException                                             
        self._mydict = mydict 

测试_模块.py

^{pr2}$

Tags: 模块pyselfmydef常数onedict
1条回答
网友
1楼 · 发布于 2024-10-01 15:39:38

在您的例子中,您不需要mock(并且您试图以错误的方式使用它,因为没有人调用MY tu DICT,而您尝试返回_value)

只需使用pytest的monkeypatch fixture:

import pytest                                                                                                                                                  
from unittest import mock                                                      
from the_module import Test1, OneMissingException                              

@pytest.fixture                                              
def patched_my_dict(monkeypatch):                                                                 
    patched = {'one': 1, 'two': 2, 'three': 3}
    monkeypatch.setattr("the_module.MY_DICT", patched)
    return patched                                    

def test_verify_test1_exception(patched_my_dict):                                      
    patched_my_dict.pop('one') # comment this out and test will not pass                                                       
    with pytest.raises(OneMissingException):                               
        Test1()  

相关问题 更多 >

    热门问题