andreyermilov / pytest-mock-server Goto Github PK
View Code? Open in Web Editor NEWMock server plugin for pytest
License: MIT License
Mock server plugin for pytest
License: MIT License
Line 39
if headers is not None:
json_response.headers.update(headers)
return json_response, status_code
json_response.headers is <class 'werkzeug.datastructures.Headers'> don't have update function.
pytest-mock-server/pytest_mock_server.py
Line 44 in 68bab88
thread = threading.Thread(target=app.run, daemon=True, kwargs=kwargs)
starts a thread.
thread.start()
starts a thread too, which errors on a port binding.
This a really neat mock server for pytest.
Kudos for it's simplicity.
I found though that it is a little bit of a hazard to base tests on it because of the port.
It opens a default flask on 5000 and this is not configurable in any way.
This is a liability as other services might be running on that very common port.
I, for instance, start a docker-compose suite, with my dev flask app on 5000, and exec in the python machine that runs the flask app in order run also run the tests. All the tests fail with 404 because the requests go to the main flask app that does not know about the routes.
I could move the main flask app - but it is weird to switch ports because of the test suite.
This might not be an option on other environments and it will yield unpredictable behaviour if forgotten.
It would be really nice if the port mock server starts on could be configured from the environment or otherwise.
Thanks!
@pytest.mark.server(url=f'/termprojsbypage/{moke_terms_db_id}', response=fake_terms_db_1, method='GET')
@pytest.mark.server_settings(port=free_port)
def test_word_level_mask(self):
import time
time.sleep(2)
config = {
"term_mask_url": f"http://127.0.0.1:{self.free_port}",
"translate_src_lang": "en",
}
protector = CodeSwitchProtector(config)
for case in self._word_level_test_cases:
sent, terms = protector.mask(case.text, self.moke_terms_db_id)
assert sent == case.masked
assert terms == case.terms
This is my code, I found that I must take a break to wait for the server ready.
In case I am mocking/testing URL with some parameter, server always response with 404:
@pytest.mark.server(url='/api/v2/products/?limit=2, response={}, method=‘GET’)
def test_url(monkeypatch) -> None:
….
I am using monkeypatch to mock environmental variables. Hope it doesn’t interfere with pytest-mock-server.
Is there a way howto passURL parameter to the Flask route?
Thanks for your help.
Lumir
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionRefusedError(61, 'Connection refused'))
Raise exception at running example.But it will not raise if sleep some time.
run this code under Flask==2.2.2 and Werkzeug==2.2.2
will return 403
import pytest
import requests
@pytest.mark.server(url='/v1/books/', response=[{'id': 1}], method='GET')
def test_handler_responses():
response = requests.get('http://localhost:5000/v1/books/')
assert response.status_code == 200
assert response.json() == [{'id': 1}]
Hi.
Am following the examples, but every time I got that error.
{ConnectionError}HTTPConnectionPool(host='localhost', port=5050): Max retries exceeded with url: /v1/books/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x06469290>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))
It doesn't matter which port is selected. OS is Windows. Any idea what went wrong?
=========================================================================================== warnings summary ===========================================================================================
test/video_download/test_download_video.py::TestVideoDownload::test_fetch_bilibili_video_info
/Users/ctrdh/.pyenv/versions/3.8.16/lib/python3.8/site-packages/_pytest/threadexception.py:73: PytestUnhandledThreadExceptionWarning: Exception in thread Thread-1
Traceback (most recent call last):
File "/Users/ctrdh/.pyenv/versions/3.8.16/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/Users/ctrdh/.pyenv/versions/3.8.16/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/Users/ctrdh/.pyenv/versions/3.8.16/lib/python3.8/site-packages/flask/app.py", line 889, in run
run_simple(t.cast(str, host), port, self, **options)
File "/Users/ctrdh/.pyenv/versions/3.8.16/lib/python3.8/site-packages/werkzeug/serving.py", line 1073, in run_simple
fd = int(os.environ["WERKZEUG_SERVER_FD"])
File "/Users/ctrdh/.pyenv/versions/3.8.16/lib/python3.8/os.py", line 675, in __getitem__
raise KeyError(key) from None
KeyError: 'WERKZEUG_SERVER_FD'
warnings.warn(pytest.PytestUnhandledThreadExceptionWarning(msg))
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
my test code
import pytest
import os
from script.main import FetchVideoInfo, DownloadVideo, Rename
# fix http server mock Warning
os.environ["WERKZEUG_RUN_MAIN"] = "true" <- I hope it can fix the warning, but it didn't working.
class TestVideoDownload:
@pytest.mark.server(url='/api/update', response=[{'data': 'update video status'}], method='POST')
def test_fetch_bilibili_video_info(self):
# to mock a http service
fixture_storage = ""
# single video
video_info_array = FetchVideoInfo("https://www.bilibili.com/video/BV1ZW411u7V3")
assert len(video_info_array) == 1
# # playlist
# video_info_array = FetchVideoInfo("https://www.bilibili.com/video/BV1SW4y1v7WN")
# assert len(video_info_array) == 3
# # playlist with 3 episode
# video_info_array = FetchVideoInfo("https://www.bilibili.com/video/BV15V411t7uW")
# assert len(video_info_array) == 4
# def test_fetch_youtube_video_info(self):
# assert 1
# def test_download_video(self):
# print("test_download_video")
# assert 1
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.