How to mock a list in Python?

Viewed 11648

For example, I have some code which tries to access a list:

def some_code():
    script_dir = os.path.dirname(sys.argv[0])

I need to mock sys.argv[0]. So I add @patch.object to my test:

import os
import sys

THIS_DIR = os.path.dirname(os.path.abspath(__file__))
@mock.patch.object(sys, 'argv', mock.Mock(return_value=[THIS_DIR]))
def test_mytest():
    some_code()

But this doesn't work. Pytest raises error:

>     script_dir = os.path.dirname(sys.argv[0])
E     TypeError: 'Mock' object does not support indexing

What am I doing wrong?

1 Answers
Related