amarao (amarao_san) wrote,
amarao
amarao_san

working notes: pytest/python function mock with side_effects

(writing for myself)

To mock function calls in tests with pytest:

CodeTest
app/files.pytest_app.py
import os
def allfiles():
   return set(os.listdir('/foo')) + set(os.listdir('/bar'))
import pytest
import mock
from app import files

def test_allfiles():
    def side_effect(path):
        if path == '/foo':
            return ['a', 'b', 'c']
        if path = '/bar':
            return ['d', 'e', f']
        raise Exception('path: %s' % path)
    with mock.patch.object(os, 'listdir') as mock_listdir:
        mock_listdir.side_effect = side_effect
        assert file.allfiles() == set(['a', 'b', 'c', 'd', 'e', 'f'])

Tags: pytest, python
Subscribe

  • Post a new comment

    Error

    default userpic

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 0 comments