Пример #1
0
 def test_with_params(self):
     req = snug.GET('my/url/', params={'foo': 'bar'})
     assert req.with_params({'other': 3}) == snug.GET('my/url/',
                                                      params={
                                                          'foo': 'bar',
                                                          'other': 3
                                                      })
Пример #2
0
 def test_with_headers(self):
     req = snug.GET('my/url', headers={'foo': 'bla'})
     assert req.with_headers({'other-header':
                              3}) == snug.GET('my/url',
                                              headers={
                                                  'foo': 'bla',
                                                  'other-header': 3
                                              })
Пример #3
0
def test_header_adder():
    req = snug.GET('my/url', headers={'Accept': 'application/json'})
    adder = snug.header_adder({'Authorization': 'my-auth'})
    assert adder(req) == snug.GET('my/url',
                                  headers={
                                      'Accept': 'application/json',
                                      'Authorization': 'my-auth'
                                  })
Пример #4
0
 def test_with_headers_other_mappingtype(self):
     req = snug.GET('my/url', headers=FrozenDict({'foo': 'bar'}))
     added = req.with_headers({'bla': 'qux'})
     assert added == snug.GET('my/url',
                              headers={
                                  'foo': 'bar',
                                  'bla': 'qux'
                              })
     assert isinstance(added.headers, FrozenDict)
Пример #5
0
    def test_defaults(self, mocker):
        send = mocker.patch('snug.query.send', autospec=True)

        assert snug.execute(myquery()) == send.return_value
        client, req = send.call_args[0]
        assert isinstance(client, urllib.OpenerDirector)
        assert req == snug.GET('my/url')
Пример #6
0
    def test_auth(self):
        client = MockClient(snug.Response(204))

        result = snug.execute(myquery(), auth=('user', 'pw'), client=client)
        assert result == snug.Response(204)
        assert client.request == snug.GET(
            'my/url', headers={'Authorization': 'Basic dXNlcjpwdw=='})
Пример #7
0
 def comments(self, since: datetime) -> snug.Query[list]:
     """retrieve comments for this issue"""
     request = snug.GET(
         BASE +
         f'repos/{self.issue.repo.owner}/{self.issue.repo.name}/'
         f'issues/{self.issue.number}/comments',
         params={'since': since.strftime('%Y-%m-%dT%H:%M:%SZ')})
     return json.loads((yield request).content)
Пример #8
0
    def test_none_auth(self, loop):
        from .py3_only import MockAsyncClient
        client = MockAsyncClient(snug.Response(204))

        future = snug.execute_async(myquery(), auth=None, client=client)
        result = loop.run_until_complete(future)
        assert result == snug.Response(204)
        assert client.request == snug.GET('my/url')
Пример #9
0
    def test_auth_callable(self):
        client = MockClient(snug.Response(204))
        auther = methodcaller('with_headers', {'X-My-Auth': 'letmein'})

        result = snug.execute(myquery(), auth=auther, client=client)
        assert result == snug.Response(204)
        assert client.request == snug.GET('my/url',
                                          headers={'X-My-Auth': 'letmein'})
Пример #10
0
    def test_auth_callable(self, loop):
        from .py3_only import MockAsyncClient
        client = MockAsyncClient(snug.Response(204))
        auther = methodcaller('with_headers', {'X-My-Auth': 'letmein'})

        future = snug.execute_async(myquery(), auth=auther, client=client)
        result = loop.run_until_complete(future)
        assert result == snug.Response(204)
        assert client.request == snug.GET('my/url',
                                          headers={'X-My-Auth': 'letmein'})
Пример #11
0
    def test_custom_execute(self):
        client = MockClient(snug.Response(204))

        class MyQuery(object):
            def __execute__(self, client, auth):
                return client.send(snug.GET('my/url'))

        result = snug.execute(MyQuery(), client=client)
        assert result == snug.Response(204)
        assert client.request == snug.GET('my/url')
Пример #12
0
    def test_auth(self, loop):
        from .py3_only import MockAsyncClient
        client = MockAsyncClient(snug.Response(204))

        future = snug.execute_async(myquery(),
                                    auth=('user', 'pw'),
                                    client=client)
        result = loop.run_until_complete(future)
        assert result == snug.Response(204)
        assert client.request == snug.GET(
            'my/url', headers={'Authorization': 'Basic dXNlcjpwdw=='})
Пример #13
0
    def test_custom_execute(self, loop):
        from .py3_only import MockAsyncClient
        client = MockAsyncClient(snug.Response(204))

        class MyQuery:
            def __execute_async__(self, client, auth):
                return client.send(snug.GET('my/url'))

        future = snug.execute_async(MyQuery(), client=client)
        result = loop.run_until_complete(future)
        assert result == snug.Response(204)
        assert client.request == snug.GET('my/url')
Пример #14
0
    def test_defaults(self, loop, mocker):
        import asyncio
        from .py3_only import awaitable

        send = mocker.patch('snug._async.send_async',
                            return_value=awaitable(snug.Response(204)))

        future = snug.execute_async(myquery())
        result = loop.run_until_complete(future)
        assert result == snug.Response(204)
        client, req = send.call_args[0]
        assert isinstance(client, asyncio.AbstractEventLoop)
        assert req == snug.GET('my/url')
Пример #15
0
def journey_options(
        origin: str,
        destination: str,
        via: t.Optional[str] = None,
        before: t.Optional[int] = None,
        after: t.Optional[int] = None,
        time: t.Optional[datetime] = None,
        hsl: t.Optional[bool] = None,
        year_card: t.Optional[bool] = None) -> (snug.Query[t.List[Journey]]):
    """journey recommendations from an origin to a destination station"""
    return snug.GET('treinplanner',
                    params={
                        'fromStation': origin,
                        'toStation': destination,
                        'viaStation': via,
                        'previousAdvices': before,
                        'nextAdvices': after,
                        'dateTime': time,
                        'hslAllowed': hsl,
                        'yearCard': year_card,
                    })
Пример #16
0
 def __iter__(self):
     request = snug.GET(
         BASE +
         f'repos/{self.repo.owner}/'
         f'{self.repo.name}/issues/{self.number}')
     return json.loads((yield request).content)
Пример #17
0
 def __iter__(self):
     request = snug.GET(BASE + f'/repos/{self.owner}/{self.name}')
     return json.loads((yield request).content)
Пример #18
0
    def test_none_auth(self):
        client = MockClient(snug.Response(204))

        result = snug.execute(myquery(), auth=None, client=client)
        assert result == snug.Response(204)
        assert client.request == snug.GET('my/url')
Пример #19
0
 def test_with_prefix(self):
     req = snug.GET('my/url/')
     assert req.with_prefix('mysite.com/') == snug.GET('mysite.com/my/url/')
Пример #20
0
 def __execute__(self, client, auth):
     return client.send(snug.GET('my/url'))
Пример #21
0
 def test_repr(self):
     req = snug.GET('my/url')
     assert 'GET my/url' in repr(req)
Пример #22
0
    def test_custom_client(self):
        client = MockClient(snug.Response(204))

        result = snug.execute(myquery(), client=client)
        assert result == snug.Response(204)
        assert client.request == snug.GET('my/url')
Пример #23
0
def stations() -> snug.Query[t.List[Station]]:
    """a list of all stations"""
    return snug.GET('stations-v2')
Пример #24
0
def myquery():
    return_((yield snug.GET('my/url')))
Пример #25
0
def departures(station: str) -> snug.Query[t.List[Departure]]:
    """departures for a station"""
    return snug.GET('avt', params={'station': station})
Пример #26
0
 def test_full(self):
     metadata = quiz.QueryMetadata(
         request=snug.GET("https://my.url/foo"), response=snug.Response(200)
     )
     selection = _.dog[
         _.name.color("knows_sit")
         .knows_command(command=Command.SIT)("knows_roll")
         .knows_command(command=Command.ROLL_OVER)
         .is_housetrained.owner[
             _.name.hobbies[_.name("coolness").cool_factor]
         ]
         .best_friend[_.name]
         .age(on_date=MyDateTime(datetime.now()))
         .birthday
     ]
     loaded = quiz.load(
         DogQuery,
         selection,
         quiz.RawResult(
             {
                 "dog": {
                     "name": "Rufus",
                     "color": "GOLDEN",
                     "knows_sit": True,
                     "knows_roll": False,
                     "is_housetrained": True,
                     "owner": {
                         "name": "Fred",
                         "hobbies": [
                             {"name": "stamp collecting", "coolness": 2},
                             {"name": "snowboarding", "coolness": 8},
                         ],
                     },
                     "best_friend": {"name": "Sally"},
                     "age": 3,
                     "birthday": 1540731645,
                 }
             },
             meta=metadata,
         ),
     )
     # TODO: include union types
     assert isinstance(loaded, DogQuery)
     assert loaded.__metadata__ == metadata
     assert loaded == DogQuery(
         dog=Dog(
             name="Rufus",
             color=Color.GOLDEN,
             knows_sit=True,
             knows_roll=False,
             is_housetrained=True,
             owner=Human(
                 name="Fred",
                 hobbies=[
                     Hobby(name="stamp collecting", coolness=2),
                     Hobby(name="snowboarding", coolness=8),
                 ],
             ),
             best_friend=Sentient(name="Sally"),
             age=3,
             birthday=MyDateTime(datetime.fromtimestamp(1540731645)),
         )
     )
Пример #27
0
def test_prefix_adder():
    req = snug.GET('my/url')
    adder = snug.prefix_adder('mysite.com/')
    assert adder(req) == snug.GET('mysite.com/my/url')
Пример #28
0
def repo(name: str, owner: str) -> snug.Query[dict]:
    """a repo lookup by owner and name"""
    request = snug.GET(f'https://api.github.com/repos/{owner}/{name}')
    response = yield request
    return json.loads(response.content)
Пример #29
0
 def __init__(self, name: str, owner: str):
     self.request = snug.GET(f'/repos/{owner}/{name}')
Пример #30
0
def _params_as_get(methodname: str, params: dict) -> snug.Request:
    return snug.GET(methodname, params=_dump_params(params))