python project import uwsgi how to do unit test?

Tangwz

My Flask app is using uwsgi spooler so I import uwsgi in the project.But when I run my unit test cases, Then

Traceback (most recent call last):
  File "runapp.py", line 55, in <module>
    import topicservice 
  File "/home/workspace/topic.py", line 36, in <module>
    import uwsgi
ImportError: No module named uwsgi

I know uwsgi is not a python module, it is a binary server.The app run by uwsgi can access the "uwsgi" module. But is there any way do my unit test?

NullThePointer

I came to the same problem while encountering the RPC function used throughout a project. There is no official way around it, but I can share my solution.

You should extract the desired functionality to a separate class/function that lazy loads the uwsgi module. Example for uwsgi.rpc:

class RPCSender:

def __init__(self, host_address):
    self._host_address = host_address

def send(self, destination, data):
    import uwsgi

    uwsgi.rpc(self._host_address, destination, data)

...

local_rpc_sender = RPCSender('192.168.173.100:3031')
local_rpc_sender.send('myfunc', 'myarg')

Now, when you write tests for modules that use RPCSender, you should mock out the send method. Preferably by using mock.patch.object. It's not against any rules of unit testing since there is no point in testing uwsgi.rpc - it's a third party library which testing is not our responsibility - we assume that it works as intended.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related