3

I am writing a Python library that calls on the network. While writing documentation, I would like to provide an example in the form as a doctest:

class Endpoint:                                                       
    """RPC endpoint representation for a service.                     

        >>> from ankhor import Endpoint                               
        >>> e = Endpoint("_hello_service._tcp.example.com")                 
        >>> e.say_hello(name="John Doe")
        'hello, John Doe!'                             
        >>>                                                           
    """

This obviously fails when running doctests, as the example.com domain does not exist. I would like to make this test pass, by mocking out the resolver that the Endpoint class uses, and by starting an example service, both before the service starts.

I can obviously use something like this:

class Endpoint:                                                       
    """RPC endpoint representation for a service.                     

        >>> from ankhor import Endpoint                               
        >>> from wsgiref.simple_server import make_server             
        >>> import threading     
        >>>                                                                          
        >>> app = hello_world_service.create_app({})                  
        >>> s = make_server('', TEST_PORT, app)                       
        >>> threading.Thread(target=s.handle_request).start()    
        >>>
        >>> e = Endpoint("_hello_service._tcp.example.com", MockedResolver())
        >>> e.say_hello(name="John Doe")                              
        'hello, John Doe!'
        >>>                                                           
    """

But this clutters the example code enormously.

So, the ultimate question is: how can I make the cleanness of the first piece of example code, behave like the latter (which mocks out both the service and the discovery)?

Note that this question differs from Using Mocks inside Doctests?, where the goal is to use a mock; the goal in this question is to keep the example readable, while still runnable.

Bonus: in the second example, I had to put test classes inside the main Python module tree. It would be nice if they only get loaded when doctests are run.

rubdos
  • 240
  • 1
  • 10
  • Workaround for anyone who'd be stuck on this would be to add `# doctest: +SKIP` at the end of lines that fail on you... – rubdos Jul 17 '17 at 20:17

0 Answers0