Ejemplo n.º 1
0
 def handle(self, request):
     if request.path == '/foo':
         return Response(
             response='not redirected',
             status=status_code,
             headers={'Location': httpserver.url_for('/bar')},
         )
     else:
         return Response('redirected')
Ejemplo n.º 2
0
 def handle(self, request):
     if getattr(self, 'set_cookie'):
         domain = request.url.split('/')[2]
         headers = {'Set-Cookie': f'cookie_domain={domain}'}
     else:
         headers = {}
     return Response(
         response='current cookies: ' +
         ', '.join(f'{k}={v}' for k, v in request.cookies.items()),
         headers=headers,
     )
Ejemplo n.º 3
0
 def handle(self, request):
     request_seen = {
         'method': request.method,
         'User-Agent': request.headers.get('User-Agent', ''),
         'multipart/form-data': dict(request.form),
     }
     # werkzeug.Request stores files in the `files` property
     for field, filestorage in request.files.items():
         request_seen['multipart/form-data'][field] = filestorage.read()
     self.requests_seen.append(request_seen)
     # Upload form redirects to torrent page
     return Response(
         status=307,
         headers={'Location': '/torrents.php?id=123'},
     )
Ejemplo n.º 4
0
        def handle(self, request):
            from werkzeug.datastructures import ImmutableMultiDict
            request_cookies = getattr(self, 'request_cookies',
                                      ImmutableMultiDict())
            assert request.cookies == request_cookies

            bar = int(request_cookies.get('bar', 0))
            self.request_cookies = ImmutableMultiDict({'bar': str(bar + 1)})

            if request_cookies:
                headers = {'Set-Cookie': f'bar={bar + 1}'}
            else:
                headers = {'Set-Cookie': 'bar=1'}

            return Response(response=f'bar is currently {bar}',
                            headers=headers)
Ejemplo n.º 5
0
        def handle(self, request):
            from werkzeug.datastructures import ImmutableMultiDict
            assert request.cookies == ImmutableMultiDict(self.expected_cookies)

            if getattr(self, 'set_cookie'):
                subdomain = request.url.split('/')[2].split('.')[0]
                headers = {
                    'Set-Cookie': f'your_cookie={subdomain}; max-age=500000'
                }
            else:
                headers = {}
            domain = request.url.split('/')[2]
            return Response(
                response=f'got cookies on {domain}: ' +
                ', '.join(f'{k}={v}' for k, v in request.cookies.items()),
                headers=headers,
            )
Ejemplo n.º 6
0
def auth(request: Request):
    request = json.loads(request.data)

    if "password" in request and "username" in request:
        response = {"access_token": "123"}

        return json.dumps(response)

    else:
        response = {
            "description": "Invalid credentials",
            "error": "Bad Request",
            "status_code": "401"
        }

        return Response(response=json.dumps(response),
                        status=401,
                        content_type="application/json")
Ejemplo n.º 7
0
async def forwarder(client, example_id, example_entry_ids):
    """A http server forwarding REST requests to `client`, bound to app under test."""
    httpserver = HTTPServer()
    httpserver \
        .expect_request(re.compile(r'/about/[0-9a-f]+')) \
        .respond_with_json((await client.get(f'/about/{example_id}')).json())
    httpserver \
        .expect_request(re.compile(r'/list/[0-9a-f]+')) \
        .respond_with_json((await client.get(f'/list/{example_id}')).json())
    json_responses = [Response((await client.get(f'/json/{example_id}/{id}')).content)
                      for id in example_entry_ids]
    json_responses_iter = iter(json_responses)
    httpserver \
        .expect_request(re.compile(rf'/json/{example_id}/[0-9a-f]+')) \
        .respond_with_handler(lambda _: next(json_responses_iter))
    try:
        httpserver.start()
        yield httpserver
    finally:
        httpserver.stop()
Ejemplo n.º 8
0
 def handle(self, request):
     assert request.content_type.startswith('multipart/form-data')
     data = request.data.decode('utf-8')
     assert re.search(
         (r'^'
          r'--[0-9a-f]{32}\r\n'
          r'Content-Disposition: form-data; name="foo"; filename="foo.jpg"\r\n'
          r'Content-Type: image/jpeg\r\n'
          r'\r\n'
          r'foo image\r\n'
          r'--[0-9a-f]{32}\r\n'
          r'Content-Disposition: form-data; name="bar"; filename="bar"\r\n'
          r'Content-Type: image/png\r\n'
          r'\r\n'
          r'bar image\r\n'
          r'--[0-9a-f]{32}--\r\n'
          r'$'),
         data,
     )
     return Response('have this')
Ejemplo n.º 9
0
    class Handler(RequestHandler):
        responses = [
            Response(
                status=transmission.TransmissionClientApi.CSRF_ERROR_CODE,
                headers={
                    transmission.TransmissionClientApi.CSRF_HEADER: csrf_token
                },
            ),
            json.dumps(response),
        ]

        def handle(self, request):
            self.requests_seen.append({
                'method':
                request.method,
                'csrf_token':
                request.headers.get(
                    transmission.TransmissionClientApi.CSRF_HEADER),
                'data':
                request.data,
            })
            return self.responses.pop(0)
Ejemplo n.º 10
0
        def handle(self, request):
            from werkzeug.datastructures import ImmutableMultiDict
            if getattr(self, 'cookies_already_set', False):
                headers = {}
                exp_request_cookies = ImmutableMultiDict({
                    **custom_cookies,
                    **server_cookies
                })
            else:
                headers = {
                    'Set-Cookie':
                    ', '.join(f'{k}={v}' for k, v in server_cookies.items())
                }
                self.cookies_already_set = True
                exp_request_cookies = ImmutableMultiDict(custom_cookies)

            assert request.cookies == exp_request_cookies

            return Response(
                response='got cookies: ' +
                ', '.join(f'{k}={v}' for k, v in request.cookies.items()),
                headers=headers,
            )
Ejemplo n.º 11
0
 def handle(self, request):
     for k, v in http._default_headers.items():
         assert request.headers[k] == v
     return Response('have this')
Ejemplo n.º 12
0
 def handle(self, request):
     self.requests_seen.append(request.full_path)
     return Response(request.full_path)
Ejemplo n.º 13
0
 def handle(self, request):
     headers = {'Set-Cookie': 'your_cookie=foo; max-age=500000'}
     return Response(
         response='setting cookie',
         headers=headers,
     )
Ejemplo n.º 14
0
 def handle(self, request):
     for k, v in combined_headers.items():
         assert request.headers[k] == v
     return Response('have this')
Ejemplo n.º 15
0
 def handle(self, request):
     assert request.headers['Authorization'] == f'Basic {auth_encoded}'
     return Response('have this')
Ejemplo n.º 16
0
 def handle(self, request):
     s = f'{request.full_path} data:{request.data.decode("utf-8")}'
     self.requests_seen.append(s)
     return Response(s)
Ejemplo n.º 17
0
 def handle(self, request):
     import time
     time.sleep(response_delay)
     return Response('have this')
Ejemplo n.º 18
0
 def handle(self, request):
     assert request.headers.get('User-Agent') == exp_user_agent
     return Response('have this')
Ejemplo n.º 19
0
 def handle(self, request):
     assert request.headers.get('Authorization') is None
     return Response('have this')