0

I am writing a python tcp proxy: whenever a connection gets established from the client, the proxy establishes the connection to the server, and transparently forwards both streams. Additionally, when the packet being forwarded has some conditions, I want to have it parsed and have that sent to another server.

This is the contents of my unittest:

class TestParsing(TestCase):
    def setUp(self) -> None:
        self.patcher = patch('EnergyDataClient.EnergyDataClient', autospec=True)
        self.EC_mock = self.patcher.start()
        EnergyAgent.EC = self.EC_mock()
        EnergyAgent.GP = MyParser.MyParser()
        self.server = multiprocessing.Process(target=tcp_server, args=(1235,))
        self.gp = multiprocessing.Process(target=EnergyAgentRunner, args=(1234, 1235))
        self.server.start()
        self.gp.start()

    def tearDown(self) -> None:
        self.patcher.stop()
        self.server.terminate()
        self.gp.terminate()

        while self.server.is_alive() or self.gp.is_alive():
            sleep(0.1)

    def test_parsemessage(self):
        # start the client process, and wait until done
        result = tcp_client(1234, correct_packets['DATA04']['request'])
        self.assertEqual(correct_packets['DATA04']['request'], result)
        EnergyAgent.EC.post.assert_called_once()

I want to validate that the 'post' method on the object EC is called with the contents I expect to have intercepted... but, as that object is on another process, mocking seems not to be helping. What am I doing wrong?

chronos
  • 325
  • 6
  • 12

1 Answers1

0

I figured out what is happening here. When calling multiprocessing.Process, python is spawning a new process using fork(), that produces a copy of the memory pages on the child process. That is the reason because I can patch the EnergyAgent.GP and works (as that object is only read from that point on, and we do not require it back at the main process) and EnergyAgent.EC does not work: The mocked object gets successfully updated on the child process, but the parent never realizes that.

chronos
  • 325
  • 6
  • 12