def test_pure_post_command(mocker, tmpdir, config_file, good_token): get_config(updated_key='auth_token', updated_value=good_token) data = {'id': 'myid'} f = tmpdir.mkdir('yaml').join('test.yaml') f.write(yaml.dump(data=data)) cmd = PurePostCommand() cmd.url_suffix = '/myendpoint' cmd.name = 'my_command' parser = argparse.ArgumentParser() parser = cmd.init_parser(parser) args = parser.parse_args([ '--file', f.strpath ]) class MockResponse(object): def __init__(self): self.text = json.dumps({'id': 'myid'}) self.status_code = 201 url = ''.join([cmd.base_url, cmd.url_suffix]) request_data = json.dumps(data) headers = {'Authorization': good_token} mocker.patch('requests.post', side_effect=lambda url, data, headers: MockResponse()) result = cmd.main(args) requests.post.assert_called_once_with(url, data=request_data, headers=headers) assert result == 'my_command\t201'
def test_get_config(config_file): config = get_config() content = json.loads(config_file.read_text()) assert content == config config = get_config('username', 'test2') content = json.loads(config_file.read_text()) assert content == config
def test_pure_get_command(mocker, config_file, good_token): get_config(updated_key='auth_token', updated_value=good_token) cmd = PureGetCommand() cmd.name = 'my_command' cmd.url_suffix = '/myendpoint' parser = argparse.ArgumentParser() parser = cmd.init_parser(parser) args = parser.parse_args() class MockResponse(object): def __init__(self): self.text = json.dumps({'id': 'my_id'}) self.status_code = 200 url = ''.join([cmd.base_url, cmd.url_suffix]) headers = {'Authorization': good_token} mocker.patch('requests.get', side_effect=lambda url, headers: MockResponse()) result = cmd.main(args) requests.get.assert_called_once_with(url, headers=headers) assert result['id'] == 'my_id'
def _handle_config(self): config = get_config() self.base_url = config['base_url'] self.username = config['username'] self.auth_url = config.get('auth_url', self.base_url) authentication_needed = False auth_token = config['auth_token'] if auth_token == '': authentication_needed = True else: payload = jwt.decode(auth_token, verify=False) expiration = datetime.datetime.fromtimestamp(payload['exp']) if expiration < datetime.datetime.now(): authentication_needed = True if authentication_needed is True: auth_token = self._authenticate() get_config('auth_token', auth_token) self.headers = {'Authorization': auth_token}