Support user.token as a fallback for api.token

This commit is contained in:
Marcin Kulik
2013-10-08 17:09:29 +02:00
parent fa838b57d7
commit 8e80920226
2 changed files with 35 additions and 11 deletions

View File

@@ -47,19 +47,31 @@ class Config:
@property @property
def api_token(self): def api_token(self):
try: try:
api_token = self.config.get('user', 'token') return self._get_api_token()
except NoOptionError: except NoOptionError:
api_token = str(uuid.uuid1()) try:
self.config.set('user', 'token', api_token) return self._get_user_token()
except NoOptionError:
self._ensure_base_dir() return self._create_api_token()
with open(self.path, 'w') as f:
self.config.write(f)
return api_token
def _ensure_base_dir(self): def _ensure_base_dir(self):
dir = os.path.dirname(self.path) dir = os.path.dirname(self.path)
if not os.path.isdir(dir): if not os.path.isdir(dir):
os.mkdir(dir) os.mkdir(dir)
def _get_api_token(self):
return self.config.get('api', 'token')
def _get_user_token(self):
return self.config.get('user', 'token')
def _create_api_token(self):
api_token = str(uuid.uuid1())
self.config.set('api', 'token', api_token)
self._ensure_base_dir()
with open(self.path, 'w') as f:
self.config.write(f)
return api_token

View File

@@ -51,11 +51,23 @@ class TestConfig(object):
assert re.match('^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}', config.api_token) assert re.match('^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}', config.api_token)
assert os.path.isfile(config.path) assert os.path.isfile(config.path)
def test_api_token_when_no_token_set(self): def test_api_token_when_no_api_token_set(self):
config = create_config('') config = create_config('')
assert re.match('^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}', config.api_token) assert re.match('^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}', config.api_token)
def test_api_token_when_token_set(self): def test_api_token_when_api_token_set(self):
token = 'foo-bar-baz'
config = create_config("[api]\ntoken = %s" % token)
assert re.match(token, config.api_token)
def test_api_token_when_api_token_set_as_user_token(self):
token = 'foo-bar-baz' token = 'foo-bar-baz'
config = create_config("[user]\ntoken = %s" % token) config = create_config("[user]\ntoken = %s" % token)
assert re.match(token, config.api_token) assert re.match(token, config.api_token)
def test_api_token_when_api_token_set_and_user_token_set(self):
user_token = 'foo'
api_token = 'bar'
config = create_config("[user]\ntoken = %s\n[api]\ntoken = %s" %
(user_token, api_token))
assert re.match(api_token, config.api_token)