示例#1
0
def test_rename_account(capsys, app, test_accounts):
    getme = Account.one(Q.name == 'getme').api_key

    # Generate a new API key for an account
    RenameAccount().run('getme', 'new_getme')

    # Check the account has been renamed
    new_getme = Account.one(Q.name == 'new_getme').api_key
    assert new_getme == getme

    # Check the output is as expected
    assert 'Account renamed: new_getme' == capsys.readouterr()[0].strip()
示例#2
0
def test_generate_new_api_key(capsys, app, test_accounts):
    # Find an existing account change the API key for
    old_api_key = Account.one(Q.name == 'getme').api_key

    # Generate a new API key for an account
    GenerateNewAPIKey().run('getme')

    # Check a new API key has been generated
    new_api_key = Account.one(Q.name == 'getme').api_key
    assert new_api_key
    assert new_api_key != old_api_key

    # Check the output is as expected
    assert 'New key generated: {0}'.format(new_api_key) \
            == capsys.readouterr()[0].strip()
示例#3
0
    def run(self, name):

        # Validate the parameters
        form = ViewAccountForm(name=name)
        if not form.validate():
            self.err(**form.errors)
            return

        # Find the account to view
        account = Account.one(Q.name == form.data['name'])

        # Output details of the account
        output = [("About '{0}':".format(account.name), 'underline_bold_blue')]

        pairs = [('created', account.created), ('modified', account.modified),
                 ('assets', Asset.count(Q.account == account)),
                 ('api_key', account.api_key),
                 ('backend', account.backend.get('backend', 'unknown'))]

        for key in sorted(account.backend.keys()):
            if key == 'backend':
                continue
            pairs.append(('> ' + key, account.backend[key]))

        # Find the longest key so we pad/align values
        width = sorted([len(p[0]) for p in pairs])[-1] + 2

        for pair in pairs:
            pair_str = '- {key:-<{width}} {value}'.format(key=pair[0].ljust(
                width, '-'),
                                                          value=pair[1],
                                                          width=width)
            output.append((pair_str, 'blue'))

        self.out(*output)
示例#4
0
def test_delete_account(capsys, app, test_accounts):
    # Delete an account
    DeleteAccount().run('getme')

    # Check the output is as expected
    assert 'Account deleted' == capsys.readouterr()[0].strip()

    # Check there is no longer an account for 'getme'
    getme = Account.one(Q.name == 'getme')
    assert getme is None
示例#5
0
    def add_variation(self, f, im, name, ops):
        """Add a variation to the asset"""
        from models.accounts import Account

        # Make sure we have access to the associated account frame
        if not isinstance(self.account, Account):
            self.account = Account.one(Q._id == self.account)

        # Transform the original image to generate the variation
        vim = None
        if im.format.lower() == 'gif' and im.is_animated:
            # By-pass transforms for animated gifs
            fmt = {'ext': 'gif', 'fmt': 'gif'}

        else:
            # Transform the image based on the variation
            vim = im.copy()
            vim, fmt = Variation.transform_image(vim, ops)

            # Prepare the variation file for storage
            f = io.BytesIO()
            vim.save(f, **fmt)
            f.seek(0)

        # Add the variation to the asset
        variation = Variation(name=name,
                              ext=fmt['ext'],
                              meta={
                                  'length': get_file_length(f),
                                  'image': {
                                      'mode': (vim or im).mode,
                                      'size': (vim or im).size
                                  }
                              })

        # Set a version
        variation.version = generate_uid(3)
        while self.get_variation(name, variation.version):
            variation.version = generate_uid(3)

        # Store the variation
        variation.store_key = Variation.get_store_key(self, variation)
        backend = self.account.get_backend_instance()
        backend.store(f, variation.store_key)

        # We use the $push operator to store the variation to prevent race
        # conditions if multiple processes attempt to update the assets
        # variations at the same time.
        self.get_collection().update(
            {'_id': self._id}, {'$push': {
                'variations': variation._document
            }})

        return variation
示例#6
0
    def wrapper(*args, **kwargs):

        api_key = request.values.get('api_key')
        if not api_key:
            return fail('`api_key` not specified.')

        # Find the account
        account = Account.one(Q.api_key == api_key.strip())
        if not account:
            return fail('Not a valid `api_key`.')

        # Set the account against the global context
        g.account = account

        return func(*args, **kwargs)
示例#7
0
def test_add_account(capsys, app):
    # Add a new account
    responses = ['tests/data/assets']
    with mock.patch.object(builtins, 'input', mock_input(responses)):
        AddAccount().run('test', 'local')

    # Check the output is as expected
    account = Account.one()
    assert 'Account added: {0}'.format(account.api_key) == \
        capsys.readouterr()[0].strip().split('\n')[-1]

    # Check the account was created correctly
    assert account.name == 'test'
    assert account.backend == json.load(open('tests/data/local.cfg'))
    assert account.api_key
示例#8
0
    def run(self, name):

        # Validate the parameters
        form = ConfigAccountBackendForm(name=name)
        if not form.validate():
            self.err(**form.errors)
            return

        # Find the account to be configured
        account = Account.one(Q.name == form.data['name'])

        # Let the user know to use dash to clear existing values
        self.out(('* Enter dash (-) to clear the existing value',
                  'underline_bold_blue'))

        # Ask the user for the backend configuration options
        backend = Backend.get_backend(account.backend['backend'])
        config = {'backend': account.backend['backend']}
        for field in backend.config_form():

            # Request the value
            self.out((field.label.text, 'blue'))
            value = input('({0}) > '.format(account.backend.get(
                field.name, '')))
            value = value.strip()

            # Check if the value should be set to the original, cleared or used
            # as provided.
            if value:
                if value == '-':
                    continue
                else:
                    config[field.name] = value
            else:
                if account.backend.get(field.name):
                    config[field.name] = account.backend.get(field.name)

        # Validate the users configuration
        result = backend.validate_config(**config)
        if not result[0]:
            self.err('Invalid backend config:', **result[1])
            return

        # Update the accounts backend
        account.backend = config
        account.update('modified', 'backend')

        self.out(('Account configured', 'bold_green'))
示例#9
0
    def run(self, name, new_name):

        # Validate the parameters
        form = RenameAccountForm(name=name, new_name=new_name)

        if not form.validate():
            self.err(**form.errors)
            return

        # Find the account to rename
        account = Account.one(Q.name == form.data['name'])

        # Set the accounts new name
        account.name = form.data['new_name']
        account.update('modified', 'name')

        self.out(('Account renamed: ' + account.name, 'bold_green'))
示例#10
0
def test_view_account(capsys, app, test_accounts):
    # View the details for an account
    ViewAccount().run('getme')

    # Find the account in question as some details are generate when the account
    # is created.
    getme = Account.one(Q.name == 'getme')

    # Check output is as expected
    expected_out = [
        "About 'getme':", '- created------- ' + str(getme.created),
        '- modified------ ' + str(getme.modified), '- assets-------- 0',
        '- api_key------- ' + getme.api_key, '- backend------- local',
        '- > asset_root-- tests/data/assets'
    ]
    expected_out = '\n'.join(expected_out)
    out = capsys.readouterr()[0].strip()
    assert out == expected_out
示例#11
0
def test_config_account(capsys, app, test_accounts):
    # Configure an account
    responses = [
        'AKIAIW5ILOAT5ZJ5XWJQ', 'y80Io/ukJhZxaiHd4ngEVxIC7v96D+z+tJOFOoY2',
        'hangar51test'
    ]
    with mock.patch.object(builtins, 'input', mock_input(responses)):
        ConfigAccount().run('hangar51')

    # Check the output is as expected
    assert 'Account configured' == \
        capsys.readouterr()[0].strip().split('\n')[-1]

    # Check the account was configured correctly
    account = Account.one(Q.name == 'hangar51')
    assert account.backend['access_key'] == 'AKIAIW5ILOAT5ZJ5XWJQ'
    assert account.backend['secret_key'] == \
            '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'
    assert account.backend['bucket'] == 'hangar51test'
示例#12
0
    def purge(self):
        """Deletes the asset along with all related files."""
        from models.accounts import Account

        # Make sure we have access to the associated account frame
        if not isinstance(self.account, Account):
            self.account = Account.one(Q._id == self.account)

        # Get the backend required to delete the asset
        backend = self.account.get_backend_instance()

        # Delete the original file
        backend.delete(self.store_key)

        # Delete all variation files
        for variation in self.variations:
            backend.delete(variation.store_key)

        self.delete()
示例#13
0
    def run(self, name):

        # Validate the parameters
        form = DeleteAccountForm(name=name)
        if not form.validate():
            self.err(**form.errors)
            return

        # Find the account to be deleted
        account = Account.one(Q.name == form.data['name'])

        # Confirm the account deletion
        if not self.confirm(
                'Enter the following string to confirm you want to \
delete this account deletion', account.name):
            return

        # Delete the account
        account.delete()

        self.out(('Account deleted', 'bold_green'))
示例#14
0
    def run(self, name):

        # Validate the parameters
        form = GenerateNewAccountAPIKeyForm(name=name)
        if not form.validate():
            self.err(**form.errors)
            return

        # Find the account to generate a new API key for
        account = Account.one(Q.name == form.data['name'])

        # Confirm the account deletion
        if not self.confirm(
                'Enter the following string to confirm you want to \
generate a new API key for this account', account.name):
            return

        # Generate a new API key for the account
        account.api_key = account.generate_api_key()
        account.update('modified', 'api_key')

        self.out(('New key generated: ' + account.api_key, 'bold_green'))