def test_mapped_values_request() -> None: """Test that values are correctly mapped from pyramid's Request.""" pyramid_request = DummyRequest(path="/foo") pyramid_request.matched_route = DummyRoute(name="foo", pattern="/foo") pyramid_request.matchdict["foo"] = "bar" pyramid_request.headers["X-Foo"] = "Bar" pyramid_request.cookies["tasty-foo"] = "tasty-bar" pyramid_request.content_type = "text/html" assert pyramid_request.host_url == "http://example.com" assert pyramid_request.path == "/foo" assert pyramid_request.method == "GET" openapi_request = PyramidOpenAPIRequest(pyramid_request) assert openapi_request.request == pyramid_request assert openapi_request.host_url == "http://example.com" assert openapi_request.path == "/foo" assert openapi_request.method == "get" assert openapi_request.path_pattern == "/foo" assert openapi_request.body == "" assert openapi_request.mimetype == "text/html" assert openapi_request.parameters == { "cookie": { "tasty-foo": "tasty-bar" }, "header": { "X-Foo": "Bar" }, "path": { "foo": "bar" }, "query": {}, }
def test_time_slot_receiver_JSON_runs(self): """ This method tests the time slot receiver JSON view when there are runs in the server-side database. The expected result of this pattern is for the correct JSON response to be retrieved. """ request = DummyRequest(route='/scheduler.json') if project_config["start_date"]: input_date = datetime.datetime.combine(project_config["start_date"], datetime.time()) else: input_date = datetime.datetime.today() + datetime.timedelta(hours=1) user_input = int(time.mktime(input_date.timetuple()) * 1000) request.content_type = "application/json" request.POST["date"] = str(user_input) # Insert runs that will the next hour with even minutes that are a multiple of 10 with transaction.manager: runs = [] for minutes in range(0, 60, 10): runs.append(Run(create_input_pattern(), datetime.datetime(input_date.year, input_date.month, input_date.day, input_date.hour, minutes), "")) DBSession.add_all(runs) DBSession.commit() response = time_slot_reciever_JSON(request) # Assert that a response has been received. assert response response_dict = eval(str(response)) for min in range(0, 60, 10): # Assert that the given slot is not in the response (means there is a run at this point) assert min not in response_dict[input_date.hour]
def test_mapped_values_request() -> None: """Test that values are correctly mapped from pyramid's Request.""" pyramid_request = DummyRequest(path="/foo") pyramid_request.matched_route = DummyRoute(name="foo", pattern="/foo") pyramid_request.matchdict["foo"] = "bar" pyramid_request.headers["X-Foo"] = "Bar" pyramid_request.cookies["tasty-foo"] = "tasty-bar" pyramid_request.content_type = "text/html" assert pyramid_request.application_url == "http://example.com" assert pyramid_request.path_info == "/foo" assert pyramid_request.method == "GET" openapi_request = PyramidOpenAPIRequestFactory.create(pyramid_request) assert openapi_request.full_url_pattern == "http://example.com/foo" assert openapi_request.method == "get" assert openapi_request.body == "" assert openapi_request.mimetype == "text/html" assert openapi_request.parameters == RequestParameters( path={"foo": "bar"}, query={}, header={"X-Foo": "Bar"}, cookie={"tasty-foo": "tasty-bar"}, )
def test_mapped_values_request() -> None: """Test that values are correctly mapped from pyramid's Request.""" pyramid_request = DummyRequest(path="/foo") pyramid_request.matched_route = DummyRoute(name="foo", pattern="/foo") pyramid_request.matchdict["foo"] = "bar" pyramid_request.headers["X-Foo"] = "Bar" pyramid_request.cookies["tasty-foo"] = "tasty-bar" pyramid_request.content_type = "text/html" assert pyramid_request.host_url == "http://example.com" assert pyramid_request.path == "/foo" assert pyramid_request.method == "GET" openapi_request = PyramidOpenAPIRequest(pyramid_request) assert openapi_request.request == pyramid_request assert openapi_request.host_url == "http://example.com" assert openapi_request.path == "/foo" assert openapi_request.method == "get" assert openapi_request.path_pattern == "/foo" assert openapi_request.body == "" assert openapi_request.mimetype == "text/html" assert openapi_request.parameters == { "cookies": {"tasty-foo": "tasty-bar"}, "headers": {"X-Foo": "Bar"}, "path": {"foo": "bar"}, "query": {}, }
def test_time_slot_reciever_JSON(self): """ This method will test the time slot receiver JSON view of the scheduling page. The expected result of this test is for the correct JSON response to be retrieved. """ request = DummyRequest(route='/scheduler.json') if project_config["start_date"]: input_date = datetime.datetime.combine(project_config["start_date"], datetime.time()) else: input_date = datetime.datetime.today() + datetime.timedelta(days=1) user_input = int(time.mktime(input_date.timetuple()) * 1000) request.content_type = "application/json" request.POST["date"] = str(user_input) response = time_slot_reciever_JSON(request) # Assert that a response has been retrieved. assert response response_dict = eval(str(response)) no_of_hours = math.ceil(((project_config["closing_time"].hour*60 + project_config["closing_time"].minute) - (project_config["starting_time"].hour*60 + project_config["starting_time"].minute)) / 60) # Assert the response holds the correct data. assert len(response_dict["hours"]) == no_of_hours
def test_no_matched_route() -> None: """Test path_pattern when no route is matched.""" pyramid_request = DummyRequest(path="/foo") pyramid_request.matched_route = None pyramid_request.content_type = "text/html" openapi_request = PyramidOpenAPIRequestFactory.create(pyramid_request) assert openapi_request.full_url_pattern == "http://example.com/foo"
def test_it_reads_from_json_content(self): data = {"key": "value"} request = DummyRequest( body=json.dumps(data), headers={"Content-Type": "application/json; charset=UTF-8"}, ) request.content_type = "application/json" assert self.ExampleSchema(request).parse() == data
def test_form_data_request() -> None: """Test that request.POST is used as the body in case of form-data.""" multi_dict = MultiDict() multi_dict.add("key1", "value1") multi_dict.add("key2", "value2.1") multi_dict.add("key2", "value2.2") pyramid_request = DummyRequest(path="/foo", post=multi_dict) pyramid_request.matched_route = DummyRoute(name="foo", pattern="/foo") pyramid_request.content_type = "multipart/form-data" openapi_request = PyramidOpenAPIRequestFactory.create(pyramid_request) assert openapi_request.body == { "key1": "value1", "key2": ["value2.1", "value2.2"] }
def test_pattern_clearer_JSON(self): """ This method tests the JSON clearer view linked to the pattern input page. The expected result of this test is for the correct JSON response to be retrieved. """ # Setup request = DummyRequest(route='/pattern_clearer.json') input = create_input_pattern() request.body = json.dumps(input) request.content_type = "application/json" request.json_body = input request.session["pattern"] = input response = pattern_input_clearer_JSON(request) # Assert that the pattern has been removed from the session assert "pattern" not in response.keys()
def mock_request( request_path_query="", # type: str method="GET", # type: str params=None, # type: Optional[Dict[str, str]] body="", # type: Union[str, JSON] content_type=None, # type: Optional[str] headers=None, # type: Optional[AnyHeadersType] cookies=None, # type: Optional[AnyCookiesType] settings=None, # type: SettingsType ): # type: (...) -> Request """ Generates a fake request with provided arguments. Can be employed by functions that expect a request object as input to retrieve details such as body content, the request path, or internal settings, but that no actual request needs to be accomplished. """ parts = request_path_query.split("?") path = parts[0] query = dict() if len(parts) > 1 and parts[1]: for part in parts[1].split("&"): kv = part.split( "=") # handle trailing keyword query arguments without values if kv[0]: # handle invalid keyword missing query[kv[0]] = kv[1] if len(kv) > 1 else None elif params: query = params request = DummyRequest(path=path, params=query) request.path_qs = request_path_query request.method = method request.content_type = content_type request.headers = headers or {} request.cookies = cookies or {} request.matched_route = None # cornice method if content_type: request.headers["Content-Type"] = content_type request.body = body try: if body: # set missing DummyRequest.json attribute request.json = json_pkg.loads(body) # type: ignore except (TypeError, ValueError): pass request.registry.settings = settings or {} return request # noqa # fake type of what is normally expected just to avoid many 'noqa'
def test_pattern_input_receiver_JSON(self): """ This method tests the JSON receiver view linked to the pattern input page. The expected result of this test is for the correct JSON response to be retrieved. """ # Setup request = DummyRequest(route='/pattern_receiver.json') input = create_input_pattern() request.body = json.dumps(input) request.content_type = "application/json" request.json_body = input response = pattern_input_receiver_JSON(request) # Assert that there is a pattern in the session. assert request.session["pattern"] == input responseDict = response # Assert that the correct number of turns has been calculated and stored. assert responseDict["turns"] == 53 # Assert that the correct run time has been calculated and stored. assert responseDict["runtime"] == SLEEP_TIME * 53
def test_it_fails_without_json_content_type_header(self, content_type): request = DummyRequest(body=json.dumps({})) request.content_type = content_type with pytest.raises(HTTPUnsupportedMediaType): self.ExampleSchema(request).parse()