I'm trying to write some component/functional test for my application writed in C . The application communicates with several http servers. For test I would like to mock these servers to easy handle bad path e.g timeouts. Could you recommend me some python package to do this?
OR
I have tried to use Flask to mock my Http server. My problem with flask is that I don't know how to run it in backgroun non blocking mode. I have trying: Using thread and lamba
class MyServerMock:
def __init__(self, port=5000):
super().__init__()
self.port = port
self.app = Flask(__name__)
self.url = "http://localhost:{}".format(self.port)
self.app.add_url_rule("/path/to/function", view_func=self.function, methods=['POST'])
def function(body):
pass
def shutdown_server(self):
self.app.do_teardown_appcontext()
def run(self):
self.thread = Thread(target=lambda: self.app.run(port=self.port, debug=False, use_reloader=False)).start()
this solution works, but after execution test cases test script is hanging in Flask and I don't know how to proper shutdown Flask.
Thank you from advance for you help.
EDIT 1: How I use this Flask code:
import MyServerMock
import pytest
def test_example():
mock = MyServerMock(port=6500)
mock.run()
# testing stuf
mock.shutdown()
assert 1 == 2
I thinking about doing fixture with this mocking server
CodePudding user response:
For a Unix solution, run your test server(s) in the background using nohup
nohup python server_1.py > server_1.log 2>&1 &
echo $! > pid_server_1.txt
Run some test modules, for example, with a Makefile
make test
When tests are done, kill
the server(s) using the saved pid
kill $(cat pid_server_1.txt)
CodePudding user response:
@OneCricketeer if I don't find a better solution I will have to solve this like you propose but I see lots of disadvantages of this solution.
Ideal solution for me will be something like this:
import Mock
import time
def timeout():
time.sleep(5)
def some_content():
return "foo bar"
def test_func1():
server1 = Mock(URL, port)
server1.set_url_behavior('endpoint1', timeout)
server2 = Mock(URL, port)
server2.set_url_behavior('endpoint2', some_content)
p = subprocess.Popen('./my_application.exe')
time.sleep(5) # or watch for specific log
assert 'some message' in server1.endpoint['endpoint1'][0].body
p.shutdown()
server1.shutdown()
server3.shutdown()
But I cant find library to do this in Python