Mock attributes in Python mock?

后端 未结 3 1814
-上瘾入骨i
-上瘾入骨i 2020-12-01 00:51

I\'m having a fairly difficult time using mock in Python:

def method_under_test():
    r = requests.post(\"http://localhost/post\")

    print r         


        
3条回答
  •  旧时难觅i
    2020-12-01 01:02

    With mock version '1.0.1' the simpler syntax mentioned in the question is supported and works as is!

    Example code updated (py.test is used instead of unittest):

    import mock
    import requests
    
    
    def method_under_test():
        r = requests.post("http://localhost/post")
    
        print r.ok
    
        if r.ok:
            return r.ok
        else:
            raise Exception()
    
    
    def test_method_under_test():
        with mock.patch('requests.post') as patched_post:
            patched_post.return_value.ok = True
    
            result = method_under_test()
            assert result is True, "mock ok failed"
    

    Run this code with: (make sure you install pytest)

    $ py.test -s -v mock_attributes.py 
    ======= test session starts =======================
    platform linux2 -- Python 2.7.10 -- py-1.4.30 -- pytest-2.7.2 -- /home/developer/miniconda/bin/python
    rootdir: /home/developer/projects/learn/scripts/misc, inifile: 
    plugins: httpbin, cov
    collected 1 items 
    
    mock_attributes.py::test_method_under_test True
    PASSED
    
    ======= 1 passed in 0.03 seconds =================
    

提交回复
热议问题