def test_with_query_param(self): paginator = Paginator(range(20), per_page=1) req = HttpRequest() req.GET = QueryDict("?q=contract") ctx = {"page_obj": paginator.page(10), "request": req} result = self.template.render(ctx) assert f"q=contract&page=9" in html.unescape(result)
def test_periodic_table_module_retrieve_data_returns_empty_if_no_data_given( self, render_template): # Arrange request = HttpRequest() request.method = 'GET' request.GET = {} my_module = PeriodicTableModule() # Act result = my_module._retrieve_data(request) self.assertEqual(True, result == '')
def test_get_item_invalid_key(self): request = HttpRequest() request.GET = QueryDict("a=1&b=2&c=3") context = { "request": request, } rendered = self.render_template( "{% load get_item %}" "{% get_item request.GET 'z' '0' %}", context) self.assertEqual(rendered, '0')
def test_query_replace_no_value(self): request = HttpRequest() request.GET = QueryDict("a=1&b=2&c=3") context = { "request": request, } rendered = self.render_template( "{% load query_replace %}" "{% query_replace a=new_a %}", context) self.assertDictEqual(parse_qs(rendered), parse_qs("b=2&c=3"))
def test_text_area_module_retrieve_data_returns_empty_if_no_data_given( self): # Arrange request = HttpRequest() request.method = "GET" request.GET = {} my_module = TextAreaModule() # Act result = my_module._retrieve_data(request) self.assertEqual(True, result == "")
def test_query_replace_duplicate_keys(self): request = HttpRequest() request.GET = QueryDict("a=1&a=2&c=3") context = { "new_a": 4, "request": request, } rendered = self.render_template( "{% load query_replace %}" "{% query_replace a=new_a %}", context) self.assertDictEqual(parse_qs(rendered), parse_qs("a=4&c=3"))
def test_query_replace_invalid_type(self): request = HttpRequest() request.GET = QueryDict("a=1&b=2&c=3") context = { "new_a": 4, "request": request, } self.assertRaises( TemplateSyntaxError, self.render_template, "{% load query_replace %}" "{% query_replace new_a %}", context)
def test_query_replace_multiple_values(self): request = HttpRequest() request.GET = QueryDict("a=1&b=2&c=3") context = { "new_a": 4, "new_b": 5, "request": request, } rendered = self.render_template( "{% load query_replace %}" "{% query_replace a=new_a b=new_b %}", context) self.assertDictEqual(parse_qs(rendered), parse_qs("a=4&b=5&c=3"))
def handle(self, *args, **options): """Automatically called when the makeresources command is given.""" BASE_PATH = "staticfiles/resources/" if not os.path.exists(BASE_PATH): os.makedirs(BASE_PATH) if options["resource_name"]: resources = [Resource.objects.get(name=options["resource_name"])] else: resources = Resource.objects.order_by("name") for resource in resources: resource_start_time = time() print("Creating {}...".format(resource.name)) # Get path to resource module resource_view = resource.generation_view if resource_view.endswith(".py"): resource_view = resource_view[:-3] module_path = "resources.views.{}".format(resource_view) # Save resource module resource_module = importlib.import_module(module_path) parameter_options = resource_module.valid_options() parameter_option_keys = sorted(parameter_options) combinations = [ dict(zip(parameter_option_keys, product)) for product in itertools.product( *(parameter_options[parameter_option_key] for parameter_option_key in parameter_option_keys)) ] # noqa: E501 # Create PDF for all possible combinations for number, combination in enumerate(combinations): start_time = time() request = HttpRequest() if resource.copies: combination["copies"] = 30 request.GET = combination (pdf_file, filename) = generate_resource_pdf(request, resource, module_path) filename = "{}.pdf".format(filename) pdf_file_output = open(os.path.join(BASE_PATH, filename), "wb") pdf_file_output.write(pdf_file) pdf_file_output.close() print("Created {}".format(filename)) print("{}{:.1f} secs".format(" " * 4, time() - start_time)) print("{}{:.0f}% of {} generated".format( " " * 4, (number + 1) / len(combinations) * 100, resource.name)) print( "\n{} took {:.1f} secs to generate all combinations\n".format( resource.name, time() - resource_start_time))
def test_response_whitout_message_and_querystring(self): from django.contrib.messages.storage import default_storage request = HttpRequest() request.GET = QueryDict('test=asd') request.session = SessionStore('asd') request._messages = default_storage(request) response = easy.action_response(request, keep_querystring=False) self.assertEqual(len(request._messages._queued_messages), 0) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], '.')
def test_query_replace_object_value(self): request = HttpRequest() request.GET = QueryDict("a=1&b=2&c=3") context = { "data": { "a": 4 }, "request": request, } rendered = self.render_template( "{% load query_replace %}" "{% query_replace a=data.a %}", context) self.assertDictEqual(parse_qs(rendered), parse_qs("a=4&b=2&c=3"))
def test_text_area_module_retrieve_data_returns_element_if_data_given( self): # Arrange request = HttpRequest() data = "dummy text" request.method = "GET" request.GET = { "data": data, } my_module = TextAreaModule() # Act result = my_module._retrieve_data(request) self.assertEqual(True, result == data)
def test_response_normal(self): from django.contrib.messages.storage import default_storage request = HttpRequest() request.GET = QueryDict('test=asd') request.session = SessionStore('asd') request._messages = default_storage(request) response = easy.action_response(request, 'Some message') self.assertEqual(len(request._messages._queued_messages), 1) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], './?test=asd')
def test_periodic_table_module_retrieve_data_returns_element_if_data_given( self, render_template): # Arrange request = HttpRequest() element = 'AC' request.method = 'GET' request.GET = { 'data': element, } my_module = PeriodicTableModule() # Act result = my_module._retrieve_data(request) self.assertEqual(True, result == element)
def test_get_http_response_raises_error_when_module_returns_None( self, data_structure_element_get_by_id): request = HttpRequest() request.GET = { "module_id": str(ObjectId()), "url": "/url", } module_object = ModuleImplementationNone() data_structure_element_get_by_id.return_value = ( _create_mock_data_structure_element()) with self.assertRaises(ModuleError): module_object._get(request)
def test_get_returns_http_response(self, data_structure_element_get_by_id, render_template): request = HttpRequest() request.GET = { 'module_id': str(ObjectId()), 'url': '/url', } module_object = ModuleImplementation() data_structure_element_get_by_id.return_value = _create_mock_data_structure_element( ) render_template.return_value = "" response = module_object.get(request) self.assertTrue(isinstance(response, HttpResponse))
def test_get_data_structure_element_contains_module_values( self, data_structure_element_get_by_id, render_template): request = HttpRequest() request.GET = { 'module_id': str(ObjectId()), 'url': '/url', } module_object = ModuleImplementation() data_structure_element = _create_mock_data_structure_element() data_structure_element_get_by_id.return_value = data_structure_element render_template.return_value = "" module_object.get(request) self.assertTrue( data_structure_element.options['data'] == "module result")
def make_request(scope, url, method, params, body, headers, **kwargs): path, query = urlparse(url).path, urlparse(url).query request = HttpRequest() request.path = path request.session = scope.get('session', None) content = json.dumps(body) request.META['HTTP_CONTENT_TYPE'] = 'application/json' request.META['HTTP_ACCEPT'] = 'application/json' request.META['HTTP_CONTENT_LENGTH'] = len(content) request.META['QUERY_STRING'] = query or '' request._read_started = False request._stream = BytesIO(content.encode('utf-8')) for (header_name, value) in scope.get('headers', []): request.META[header_name.decode('utf-8')] = value.decode('utf-8') query_s, data = QueryDict(query, mutable=True), QueryDict(mutable=True) print(params, query_s) query_s.update(params) data.update(body) request.method = method request.POST = data request.GET = query_s if scope.get('cookies'): request.COOKIES = scope.get('cookies') for k, v in headers.items(): header = f'HTTP_{k.upper()}' request.META[header] = v.encode() if "server" in scope: request.META["SERVER_NAME"] = scope["server"][0] request.META["SERVER_PORT"] = scope["server"][1] else: request.META["SERVER_NAME"] = "localhost" request.META["SERVER_PORT"] = 80 for k, v in kwargs.items(): setattr(request, k, v) return request
def is_module_managing_occurencies(module): request = HttpRequest() request.method = 'GET' request.GET = { 'url': module.url, 'module_id': module.id, 'managing_occurences': True } module_view = get_module_view(module.url) response = module_view(request).content.decode("utf-8") if response == 'false': return False elif response == 'true': return True else: raise ValueError("Unexpected value (expected 'true'|'false', got {})".format(response))
def test_get_returns_http_response( self, mock_data_structure_element_upsert, mock_data_structure_element_get_by_id, mock_render_template, ): request = HttpRequest() request.GET = { "module_id": str(ObjectId()), "url": "/url", } request.user = create_mock_user("1") module_object = ModuleImplementation() mock_data_structure_element = _create_mock_data_structure_element() mock_data_structure_element_get_by_id.return_value = mock_data_structure_element mock_data_structure_element_upsert.return_value = mock_data_structure_element mock_render_template.return_value = "" response = module_object.get(request) self.assertTrue(isinstance(response, HttpResponse))
def convert_request(request): """ Converts an aiohttp Request to a Django HttpRequest This does not convert the async body to a sync body for POST requests """ djr = HttpRequest() djr.method = request.method upper_keys = {k.upper() for k in request.headers.keys()} # These two headers are specially set by Django without the HTTP prefix h = {"CONTENT_LENGTH", "CONTENT_TYPE"} djr.META = { f"HTTP_{k}" if k not in h else k: request.headers[k] for k in upper_keys } djr.COOKIES = request.cookies djr.path = request.path djr.path_info = request.match_info.get("path", "") djr.encoding = request.charset djr.GET = request.query djr._get_scheme = lambda: request.scheme return djr
def test_get_data_structure_element_contains_module_values( self, mock_data_structure_element_upsert, mock_data_structure_element_get_by_id, mock_render_template, ): request = HttpRequest() request.GET = { "module_id": str(ObjectId()), "url": "/url", } request.user = create_mock_user("1") module_object = ModuleImplementation() data_structure_element = _create_mock_data_structure_element() mock_data_structure_element_get_by_id.return_value = data_structure_element mock_data_structure_element_upsert.return_value = data_structure_element mock_render_template.return_value = "" module_object.get(request) self.assertTrue( data_structure_element.options["data"] == "module result")
def test_hop_is_cut_off(request: HttpRequest): request.GET = _test_source() request_get_flows_to_sink(request)
def test_trace_has_no_tito(request: HttpRequest): request.GET = _test_source() _test_sink(request.GET)
def test_untainted_assign(request: HttpRequest): request.GET = {} _test_sink(request.GET)