[Python] Mocking a local variable of a function in python

Discussão em 'Python' iniciado por Stack, Março 22, 2025.

  1. Stack

    Stack Membro Participativo

    I am new to mock and unit testing in python. How can I mock the local variable of a function? For example, how do I change age to 10 instead of 27 while testing?

    # data_source.py
    def get_name():
    age = 27 #real value
    return "Alice"

    # person.py
    from data_source import get_name

    class Person(object):
    def name(self):
    return get_name()

    # The unit test
    from mock import patch
    from person import Person

    @patch('person.age')
    def test_name(mock_age):
    mock_age = 10 # mock value
    person = Person()
    name = person.name()
    assert age == 10

    Continue reading...

Compartilhe esta Página