3

I am new in mock and tests for python code(whatever code).

I'm trying to test my function main.py

def get_channel_list():
    sc = SlackClient(get_token())
    channels_list_json = sc.api_call("channels.list")
    if channels_list_json['ok'] == True:
        return channels_list_json

that is function that I'm trying to test

I need to mock patch sc.api_call("channels.list") to return JSON object but I can't find any examples like this that would help me to figure out how to do it.

Evrething I found was like this example Mocking a class method...

I think it would look like this:

@patch.object(SlackClient, 'api_call')
def test_get_channel_list():
    assert get_channel_list() != ""

I don't have to to test lib I need to test the rest of my code in the function that I mentioned before. Thanks for any help, I'm realy stack with this test.

ischenkodv
  • 4,205
  • 2
  • 26
  • 34
  • I think you need to write a mock function to return the json and mention that in the `patch` decorator. If you add you mock function we might be able ot piece together the parts for you. – doctorlove Jul 04 '18 at 10:30
  • I didn't fully understand what you mean – Alex Edakin Jul 04 '18 at 10:32
  • You need something that to "return json object" - which you haven't included in the question. I could make something up - but wondered if there was something more specific than that you hadn't mentioned. – doctorlove Jul 04 '18 at 10:33
  • it doesn't realy matter what to return it could be just python dict – Alex Edakin Jul 04 '18 at 10:36

1 Answers1

3

You need to write a separate mock function to return a JSON object.

You can try this:

@pytest.fixture
def mock_api_call(monkeypatch):
    monkeypatch.setattr(SlackClient, 'api_call', lambda self, arg: {"ok": True})

def test(mock_api_call):
    sc = SlackClient(get_token())
    channels_list_json = sc.api_call("channels.list")
    assert True == channels_list_json['ok']

def test_get_channel_list(mock_api_call):
    channels_list_json = get_channels_list()
    assert dict == type(channels_list_json)
Oleksandr Yarushevskyi
  • 2,789
  • 2
  • 17
  • 24