-1

My code looks roughly like

40 def send_pubkey( s: socket ) -> None:                                           
41     '''Transmit own public key unencrypted.'''                                  
42     _, pub = crypto.read_keypair()                                              
43     s.sendall(pub.save_pkcs1()) 

This is extremely difficult to test as it involves network operations. However adding another level of abstraction between this layer and OS sockets goes against import this*. Any silver bullet out there?

* - Simple is better than complex.

Vorac
  • 7,129

2 Answers2

6

The way to make this code unit testable is not by mocking it. It's to give it a functional core.

def extract_pubkey( crypto ) -> bytes:
    _, pub = crypto.read_keypair() 
    return pub.save_pkcs1()

That is unit testable. It simplifies send_pubkey down to a one liner, if not out of existence. Yes it leaves the sending code not under unit test but that's as should be. Unit tests are about internal behavior. Not integration with the outside world.

candied_orange
  • 108,538
3

I would say no.

In these cases it's better to create a test environment (docker?) and actually send packets, integration rather than unit testing.

A unit test with a mocked network layer is going to be testing the mock to a large extent, and just wont pick up on lots of common networking errors.

Ewan
  • 75,506
  • +1 but sorry for changing the accepted answer. I got down to it just now and realized implementing a whole new layer(containers) is so much over my head. Thanks again, I'll keep Your wisdom in mind! – Vorac Aug 25 '23 at 05:52