Пример #1
0
def add(fullname, password, comment, force, copy):
    db = Database(config.path)
    try:
        login, name = split_fullname(fullname)
    except ValueError:
        message = 'invalid fullname syntax'
        raise click.ClickException(click.style(message, fg='yellow'))

    found = db.get((where("login") == login) & (where("name") == name))
    if force or not found:
        with Cryptor(config.path) as cryptor:
            encrypted = cryptor.encrypt(password)

        credential = dict(fullname=fullname,
                          name=name,
                          login=login,
                          password=encrypted,
                          comment=comment,
                          modified=datetime.now())
        db.insert(credential)
        if copy:
            pyperclip.copy(password)
    else:
        message = "Credential {} already exists. --force to overwrite".format(
            fullname)
        raise click.ClickException(click.style(message, fg='yellow'))
Пример #2
0
def search(regex):
    db = Database(config.path)
    credentials = db.search(
        where("name").matches(regex) |
        where("login").matches(regex) |
        where("comment").matches(regex))
    credentials = sorted(credentials, key=lambda x: x["name"]+x["login"])
    print_table(credentials)
Пример #3
0
def test_all():
    query = where('followers').all(where('name') == 'don')
    assert query({'followers': [{'name': 'don'}]})
    assert not query({'followers': [{'name': 'don'}, {'name': 'john'}]})

    query = where('followers').all(where('num').matches('\\d+'))
    assert query({'followers': [{'num': '123'}, {'num': '456'}]})
    assert not query({'followers': [{'num': '123'}, {'num': 'abc'}]})
Пример #4
0
def test_hash():
    d = {
        where('key1') == 2: True,
        where('key1').has('key2').has('key3'): True
    }

    assert (where('key1') == 2) in d
    assert (where('key1').has('key2').has('key3')) in d
Пример #5
0
def test_and():
    query = (
        (where('val1') == 1) &
        (where('val2') == 2)
    )
    assert query({'val1': 1, 'val2': 2})
    assert not query({'val1': 1})
    assert not query({'val2': 2})
    assert not query({'val1': '', 'val2': ''})
Пример #6
0
def test_and():
    query = (
        (where('val1') == 1) &
        (where('val2') == 2)
    )
    assert_true(query({'val1': 1, 'val2': 2}))
    assert_false(query({'val1': 1}))
    assert_false(query({'val2': 2}))
    assert_false(query({'val1': '', 'val2': ''}))
Пример #7
0
def search(regex):
    if config.search_automatic_regex and re.match("\w+", regex):
        regex = ".*{}.*".format(regex)
    db = Database(config.path)
    credentials = db.search(
        where("name").matches(regex) |
        where("login").matches(regex) |
        where("comment").matches(regex))
    credentials = sorted(credentials, key=lambda x: x["name"] + x["login"])
    print_table(credentials)
Пример #8
0
def test_has():
    query = where('key1').has('key2')
    str(query)  # This used to cause a bug...

    assert query({'key1': {'key2': {'key3': 1}}})
    assert query({'key1': {'key2': 1}})
    assert not query({'key1': 3})
    assert not query({'key1': {'key1': 1}})
    assert not query({'key2': {'key1': 1}})

    query = where('key1').has('key2') == 1

    assert query({'key1': {'key2': 1}})
    assert not query({'key1': {'key2': 2}})

    # Nested has: key exists
    query = where('key1').has('key2').has('key3')
    assert query({'key1': {'key2': {'key3': 1}}})
    # Not a dict
    assert not query({'key1': 1})
    assert not query({'key1': {'key2': 1}})
    # Wrong key
    assert not query({'key1': {'key2': {'key0': 1}}})
    assert not query({'key1': {'key0': {'key3': 1}}})
    assert not query({'key0': {'key2': {'key3': 1}}})

    # Nested has: check for value
    query = where('key1').has('key2').has('key3') == 1
    assert query({'key1': {'key2': {'key3': 1}}})
    assert not query({'key1': {'key2': {'key3': 0}}})

    # Test special methods: regex matches
    query = where('key1').has('value').matches(r'\d+')
    assert query({'key1': {'value': '123'}})
    assert not query({'key2': {'value': '123'}})
    assert not query({'key2': {'value': 'abc'}})

    # Test special methods: regex contains
    query = where('key1').has('value').contains(r'\d+')
    assert query({'key1': {'value': 'a2c'}})
    assert not query({'key2': {'value': 'a2c'}})
    assert not query({'key2': {'value': 'abc'}})

    # Test special methods: nested has and regex matches
    query = where('key1').has('x').has('y').matches(r'\d+')
    assert query({'key1': {'x': {'y': '123'}}})
    assert not query({'key1': {'x': {'y': 'abc'}}})

    # Test special method: nested has and regex contains
    query = where('key1').has('x').has('y').contains(r'\d+')
    assert query({'key1': {'x': {'y': 'a2c'}}})
    assert not query({'key1': {'x': {'y': 'abc'}}})

    # Test special methods: custom test
    query = where('key1').has('int').test(lambda x: x == 3)
    assert query({'key1': {'int': 3}})
Пример #9
0
def test_regex():
    query = where('val').matches(r'\d{2}\.')

    assert query({'val': '42.'})
    assert not query({'val': '44'})
    assert not query({'val': 'ab.'})
    assert not query({'': None})

    query = where('val').contains(r'\d+')

    assert query({'val': 'ab3'})
    assert not query({'val': 'abc'})
    assert not query({'val': ''})
    assert not query({'': None})
Пример #10
0
def test_not():
    query = ~ (where('val1') == 1)
    assert query({'val1': 5, 'val2': 2})
    assert not query({'val1': 1, 'val2': 2})

    query = (
        (~ (where('val1') == 1)) &
        (where('val2') == 2)
    )
    assert query({'val1': '', 'val2': 2})
    assert query({'val2': 2})
    assert not query({'val1': 1, 'val2': 2})
    assert not query({'val1': 1})
    assert not query({'val1': '', 'val2': ''})
Пример #11
0
def test_not():
    query = ~ (where('val1') == 1)
    assert_true(query({'val1': 5, 'val2': 2}))
    assert_false(query({'val1': 1, 'val2': 2}))

    query = (
        (~ (where('val1') == 1)) &
        (where('val2') == 2)
    )
    assert_true(query({'val1': '', 'val2': 2}))
    assert_true(query({'val2': 2}))
    assert_false(query({'val1': 1, 'val2': 2}))
    assert_false(query({'val1': 1}))
    assert_false(query({'val1': '', 'val2': ''}))
Пример #12
0
def test_regex():
    query = where('val').matches(r'\d{2}\.')

    assert_true(query({'val': '42.'}))
    assert_false(query({'val': '44'}))
    assert_false(query({'val': 'ab.'}))
    assert_false(query({'': None}))
Пример #13
0
def update(fullname, name, login, password, comment):
    db = Database(config.path)
    credential = get_credential_or_abort(db, fullname)
    values = credential.copy()

    if any([name, login, password, comment]):
        values["name"] = name if name else credential["name"]
        values["login"] = login if login else credential["login"]
        values["password"] = password if password else credential["password"]
        values["comment"] = comment if comment else credential["comment"]
    else:
        values["name"] = click.prompt("Name", default=credential["name"])
        values["login"] = click.prompt("Login", default=credential["login"])
        values["password"] = click.prompt("Password",
                                          hide_input=True,
                                          default=credential["password"],
                                          confirmation_prompt=True,
                                          show_default=False,
                                          prompt_suffix=" [*****]: ")
        values["comment"] = click.prompt("Comment",
                                         default=credential["comment"])

    if values != credential:
        values["fullname"] = make_fullname(values["login"], values["name"])
        values["modified"] = datetime.now()
        if values["password"] != credential["password"]:
            with Cryptor(config.path) as cryptor:
                values["password"] = cryptor.encrypt(password)
        db = Database(config.path)
        db.update(values, (where("fullname") == credential["fullname"]))
Пример #14
0
def get_credential_or_abort(db, fullname):
    try:
        login, name = split_fullname(fullname)
        query = (where("name") == name) & (where("login") == login)
    except ValueError:
        query = where('name') == fullname

    credential = db.get(query)
    if not credential:
        message = "Credential '{}' not found".format(fullname)
        raise click.ClickException(click.style(message, fg='red'))
    elif db.count(query) > 1:
        message = "Multiple matches for '{}'".format(fullname)
        raise click.ClickException(click.style(message, fg='red'))

    return credential
Пример #15
0
def remove(fullname):
    db = Database(config.path)
    credential = get_credential_or_abort(db, fullname)
    if credential:
        click.confirm(
            'Remove credential: {}'.format(click.style(fullname, 'yellow')),
            abort=True
        )
        db.remove(where('fullname') == credential["fullname"])
Пример #16
0
def test_custom_with_params():
    def test(value, minimum, maximum):
        return minimum <= value <= maximum

    query = where('val').test(test, 1, 10)

    assert query({'val': 5})
    assert not query({'val': 0})
    assert not query({'val': 11})
    assert not query({'': None})
Пример #17
0
def test_custom():
    def test(value):
        return value == 42

    query = where('val').test(test)

    assert query({'val': 42})
    assert not query({'val': 40})
    assert not query({'val': '44'})
    assert not query({'': None})
Пример #18
0
def remove(fullname, yes):
    db = Database(config.path)
    credentials = get_credential_or_abort(db, fullname, many=True)

    if credentials:
        if not yes:
            creds = ', '.join([c['fullname'] for c in credentials])
            click.confirm(
                'Remove credentials: ({})'.format(
                    click.style(creds, 'yellow')),
                abort=True
            )
        for credential in credentials:
            db.remove(where('fullname') == credential['fullname'])
Пример #19
0
def remove(fullname, yes):
    db = Database(config.path)
    credentials = get_credential_or_abort(db, fullname, many=True)

    if credentials:
        if not yes:
            creds = ', '.join([c['fullname'] for c in credentials])
            click.confirm(
                'Remove credentials: ({})'.format(
                    click.style(creds, 'yellow')),
                abort=True
            )
        for credential in credentials:
            db.remove(where('fullname') == credential['fullname'])

        fullnames = ', '.join(c['fullname'] for c in credentials)
        message = 'Removed {}'.format(fullnames)
        logger.debug(message)
        repo = Repository(config.path)
        repo.commit(message)
Пример #20
0
def test_any():
    query = where('followers').any(where('name') == 'don')

    assert query({'followers': [{'name': 'don'}, {'name': 'john'}]})
    assert not query({'followers': 1})
    assert not query({})

    query = where('followers').any(where('num').matches('\\d+'))
    assert query({'followers': [{'num': '12'}, {'num': 'abc'}]})
    assert not query({'followers': [{'num': 'abc'}]})

    query = where('followers').any(['don', 'jon'])
    assert query({'followers': ['don', 'greg', 'bill']})
    assert not query({'followers': ['greg', 'bill']})
    assert not query({})

    query = where('followers').any([{'name': 'don'}, {'name': 'john'}])
    assert query({'followers': [{'name': 'don'}, {'name': 'greg'}]})
    assert not query({'followers': [{'name': 'greg'}]})
Пример #21
0
def test_has_key():
    query = where('val3')

    assert query({'val3': 1})
    assert not query({'val1': 1, 'val2': 2})
Пример #22
0
def test_ge():
    query = where('value') >= 1
    assert query({'value': 2})
    assert query({'value': 1})
    assert not query({'value': 0})
Пример #23
0
def test_eq():
    query = where('value') == 1
    assert query({'value': 1})
    assert not query({'value': 2})
Пример #24
0
def test_ne():
    query = where('value') != 1
    assert query({'value': 2})
    assert not query({'value': 1})
 def delete_property(self, property_):
     _id = Query()
     self._db.remove(where(self._ID) == property_.id)
Пример #26
0
def test_ge():
    query = where('value') >= 1
    assert query({'value': 2})
    assert query({'value': 1})
    assert not query({'value': 0})
Пример #27
0
def test_gt():
    query = where('value') > 1
    assert query({'value': 2})
    assert not query({'value': 1})
Пример #28
0
def test_lt():
    query = where('value') < 1
    assert_true(query({'value': 0}))
    assert_false(query({'value': 1}))
Пример #29
0
def test_ge():
    query = where('value') >= 1
    assert_true(query({'value': 2}))
    assert_true(query({'value': 1}))
    assert_false(query({'value': 0}))
Пример #30
0
 def get_or_create_global(self, name, default):
     field = self.db.get(where(name) != None)
     if not field:
         field = {name: default}
         self.db.insert(field)
     return field[name]
Пример #31
0
def test_eq():
    query = where('value') == 1
    assert_true(query({'value': 1}))
    assert_false(query({'value': 2}))
Пример #32
0
def delete_plant_configuration(plant_id: str = Path(..., title="ID of plant configuration to delete")):
    """ Delete an existing plant configuration """
    plants_delete_ids = plants_configuration.remove(where('id') == plant_id)
    if (len(plants_delete_ids) == 0):
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR , detail="Not plant found for deleting")
Пример #33
0
def update_plant_configuration(
    plant_id: str = Path(..., title="ID of plant to change configuration"), 
    plant_conf: PlantConfiguration = Body(..., title="updated plant configuration", example={"id": "abc123", "sensor_type": "moisture_capacitve", "sensor_channel": 2, "plant": "My Plant", "relay_pin": 5, "activated": False, "water_duration_sec": 3, "water_iterations": 1, "max_moisture": 90, "min_moisture": 42 })
):
    """ Updates an existing plant configuration"""
    if (plant_conf.id is not None and plant_id != plant_conf.id):
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR , detail="Forbidden to change id")
    plants_update_ids = plants_configuration.update(plant_conf.dict(exclude_none=True), where('id') == plant_id)
    if (len(plants_update_ids) == 0):
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR , detail="No plant found for updating")
Пример #34
0
def test_lt():
    query = where('value') < 1
    assert query({'value': 0})
    assert not query({'value': 1})
Пример #35
0
def test_and():
    query = ((where('val1') == 1) & (where('val2') == 2))
    assert query({'val1': 1, 'val2': 2})
    assert not query({'val1': 1})
    assert not query({'val2': 2})
    assert not query({'val1': '', 'val2': ''})
Пример #36
0
def checkexistence(username):  # Case INSENSITIVE!
    db = TinyDB('users.json', indent=4)
    resp = db.search(where('username').matches(username, flags=re.IGNORECASE))
    db.close()
    return resp
Пример #37
0
def test_lt():
    query = where('value') < 1
    assert query({'value': 0})
    assert not query({'value': 1})
Пример #38
0
def test_eq():
    query = where('value') == 1
    assert query({'value': 1})
    assert not query({'value': 2})
Пример #39
0
def test_hash():
    d = {where('key1') == 2: True, where('key1').has('key2').has('key3'): True}

    assert (where('key1') == 2) in d
    assert (where('key1').has('key2').has('key3')) in d
Пример #40
0
def dbsearch(key, value):
    db = TinyDB('users.json', indent=4)
    resp = db.search(where(key) == value)
    db.close()
    return resp
Пример #41
0
def test_gt():
    query = where('value') > 1
    assert query({'value': 2})
    assert not query({'value': 1})
Пример #42
0
def test_has_key():
    query = where('val3')

    assert query({'val3': 1})
    assert not query({'val1': 1, 'val2': 2})
Пример #43
0
def test_has_key():
    query = where('val3')

    assert_true(query({'val3': 1}))
    assert_false(query({'val1': 1, 'val2': 2}))
Пример #44
0
def test_ne():
    query = where('value') != 1
    assert query({'value': 2})
    assert not query({'value': 1})
Пример #45
0
 def __exit__(self, *args):
     logging.debug('Closing %s', self.path)
     self.db.update(increment('serial'), where('serial') != None)