[Python] Pytest method mocking

Discussão em 'Python' iniciado por Stack, Fevereiro 5, 2025.

  1. Stack

    Stack Membro Participativo

    def create_interface(iface, address, netmask):
    validate_interface(iface, address, netmask)
    if ping_test(address):
    raise Exception("Address %s is already in use. interface %s with ip %s." % (address, iface, address))
    proc = Popen(["sudo ifconfig %s %s netmask %s up" %
    (iface, address, netmask)], shell=True, stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()
    ret = proc.returncode
    if ret:
    raise Exception("Failed to create virtual interface '%s': %s" %
    (iface, out + err))
    else:
    logging.info("Created %s with ip %s and netmask %s successfully" %
    (iface, address, netmask))


    this is th emethod for which i need to write test case

    My test case

    def test_create_interface(self):
    iface = "eth0:1"
    address = "1.2.3.4"
    netmask = "255.255.255.0"
    import subprocess
    process = self.mox.CreateMock(subprocess.Popen)
    process.returncode = 1
    self.mox.StubOutWithMock(vi, "validate_interface")
    vi.validate_interface(iface, address, netmask).AndReturn(None)
    self.mox.StubOutWithMock(vi, "ping_test")
    vi.ping_test(address).AndReturn(False)
    self.mox.StubOutWithMock(subprocess, "Popen")
    subprocess.Popen( IgnoreArg(), stdout=subprocess.PIPE,
    stderr=subprocess.PIPE).AndReturn(process)
    self.mox.StubOutWithMock(process, "communicate")
    process.communicate().AndReturn(("", 0))
    self.mox.ReplayAll()
    vi.create_interface(iface, address, netmask)
    self.mox.VerifyAll()


    but it fails with Unexpected method call function.__call__('eth0:1', '1.2.3.4', '255.255.255.0') -> None. what is that iam missing

    Continue reading...

Compartilhe esta Página