Python 嘲笑医生

Python 嘲笑医生,python,mocking,doctest,Python,Mocking,Doctest,我正在编写一个在网络上调用的Python库。在编写文档时,我想以doctest的形式提供一个示例: class Endpoint: """RPC endpoint representation for a service. >>> from ankhor import Endpoint

我正在编写一个在网络上调用的Python库。在编写文档时,我想以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!'                             
        >>>                                                           
    """
当运行doctests时,这显然会失败,因为
example.com
域不存在。我希望通过模拟
端点
类使用的解析器,并在服务启动之前启动一个示例服务,从而通过此测试

很明显,我可以这样使用:

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!'
        >>>                                                           
    """
但这会使示例代码非常混乱

因此,最终的问题是:如何使第一段示例代码保持干净,表现得像后一段代码(它模拟了服务和发现)

请注意,此问题与目标是使用模拟的问题不同;这个问题的目标是保持示例可读性,同时仍然可以运行


好处:在第二个示例中,我必须将测试类放在主Python模块树中。如果只有在运行doctest时才会加载它们,那就太好了。

对于那些被困于此的人来说,解决办法是在你失败的行末尾添加
\doctest:+SKIP
。对于那些被困于此的人来说,解决办法是在你失败的行末尾添加
\doctest:+SKIP
。。。