Giter Club home page Giter Club logo

pytest-mock-server's People

Contributors

andreyermilov avatar intsynko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

pytest-mock-server's Issues

Headers class don't have function update.

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.

Configure the port on which the mock server listens

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!

time.sleep to wait server ready

   @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.

404 on URL with parameters

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

Exception

requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionRefusedError(61, 'Connection refused'))
Raise exception at running example.But it will not raise if sleep some time.

return 403 when Flask==2.2.2 and Werkzeug==2.2.2

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}]

Failed to establish a new connection

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?

Waring `KeyError: 'WERKZEUG_SERVER_FD'`

=========================================================================================== 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
CleanShot 2023-08-01 at 12 43 30@2x

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.