コード例 #1
0
 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)
コード例 #2
0
 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 == '')
コード例 #3
0
 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')
コード例 #4
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"))
コード例 #5
0
 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 == "")
コード例 #6
0
 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"))
コード例 #7
0
 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)
コード例 #8
0
 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"))
コード例 #9
0
    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))
コード例 #10
0
ファイル: tests.py プロジェクト: xtaraim/django-admin-easy
    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'], '.')
コード例 #11
0
ファイル: tests.py プロジェクト: ebertti/django-admin-easy
    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'], '.')
コード例 #12
0
 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"))
コード例 #13
0
 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)
コード例 #14
0
ファイル: tests.py プロジェクト: ebertti/django-admin-easy
    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')
コード例 #15
0
ファイル: tests.py プロジェクト: xtaraim/django-admin-easy
    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')
コード例 #16
0
 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)
コード例 #17
0
    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)
コード例 #18
0
    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))
コード例 #19
0
    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")
コード例 #20
0
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
コード例 #21
0
ファイル: discover.py プロジェクト: Huchikoma/internship_MMQ
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))
コード例 #22
0
    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))
コード例 #23
0
ファイル: authentication.py プロジェクト: pavelpicka/pulpcore
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
コード例 #24
0
    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")
コード例 #25
0
ファイル: http_request.py プロジェクト: duruyi/pyre-check
def test_hop_is_cut_off(request: HttpRequest):
    request.GET = _test_source()
    request_get_flows_to_sink(request)
コード例 #26
0
ファイル: http_request.py プロジェクト: duruyi/pyre-check
def test_trace_has_no_tito(request: HttpRequest):
    request.GET = _test_source()
    _test_sink(request.GET)
コード例 #27
0
ファイル: http_request.py プロジェクト: duruyi/pyre-check
def test_untainted_assign(request: HttpRequest):
    request.GET = {}
    _test_sink(request.GET)