0

I can do this if I wrap them into python class:

class Foo:

    def generate_list(self):
        my_list = [3, 4, 5, 6]
        return my_list

    def get_first_list(self):
        lists = self.generate_list()
        first = lists[0]
        return first

class TestFoo:

    def fake_generate_list(self):
        return [10, 11]

    def test_get_first_list(self):
        foo = Foo()
        foo.generate_list = self.fake_generate_list # <----
        first = foo.get_first_list()
        assert first == 10 # PASSED (first is 10)

But it's failed, if I unwrap them without class:

def generate_list():
    print(generate_list)
    my_list = [3, 4, 5, 6]
    return my_list

def get_first_list():
    lists = generate_list()
    first = lists[0]
    return first

# Test

def fake_generate_list():
    return [10, 11]

def test_get_first_list():
    generate_list = fake_generate_list # <------
    first = get_first_list()
    assert first == 10 # FAILED (first still 3)

I know one alternative is using monkeypatch.setattr("myfilename.generate_list", fake_generate_list). But is there any simple alternative just like old_function = fake_function. ?

Thanks

azzamsa
  • 1,805
  • 2
  • 20
  • 28

1 Answers1

0

test_get_first_list's generate_list is a new local variable, not an assignment to the function generate_list, thus it's not visible inside get_first_list. You can write global generate_list at the top of test_get_first_list, then you're assigning to the function as you intended.

def test_get_first_list():
    global generate_list
    generate_list = fake_generate_list
    first = get_first_list()
    assert first == 10

This will rapidly lead you to writing bad / unmaintainable code though. See eg. [here].

moonGoose
  • 1,510
  • 6
  • 14
  • Yes, I ask this only for learning purposes, in production, I use classes or mock. +1 for the reason why it's failing. – azzamsa Mar 28 '19 at 05:41