コード例 #1
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_get_from_cache(mocker):
    mocker.patch.object(CacheMixin, "_db_session", DBSession)

    t = Team(id=0, team_name="test_get_from_cache")
    with mocker.patch.object(_RedisWrapper, "get", return_value=t.__rawdata__):
        m = Team.get(0)
        assert m._cached
コード例 #2
0
ファイル: test_team_audit.py プロジェクト: zhoudaqing/huskar
def test_create_team(client, db, admin_user, admin_token, webhook_backends):
    assert Team.get_by_name('foo') is None
    assert db.query(AuditLog.id).first() is None

    r = client.post('/api/team', data={'team': 'foo'},
                    headers={'Authorization': admin_token})
    assert r.status_code == 201, r.json

    team = Team.get_by_name('foo')
    audit = db.query(AuditLog).first()
    assert team is not None
    assert audit is not None
    assert audit.user.id == admin_user.id
    assert audit.action_name == 'CREATE_TEAM'
    assert json.loads(audit.action_data) == {
        'team_id': team.id,
        'team_name': 'foo',
        'team_desc': team.team_desc,
    }
    assert audit.rollback_to is None

    for result in webhook_backends:
        assert result['action_data']['team_id'] == team.id
        assert result['action_data']['team_name'] == 'foo'
        assert result['action_name'] == 'CREATE_TEAM'
コード例 #3
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_from_cache(mocker):
    t = Team(id=0, team_name='test')
    _key = 0

    with mocker.patch.object(_RedisWrapper, "mget",
                             return_value=t.__rawdata__):
        m = Team._from_cache([_key])
        assert _key in m
コード例 #4
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_get_from_db(mocker):
    t = Team(id=0, team_name="hello")

    mocker.patch.object(_RedisWrapper, "get", mocker.Mock(return_value=None))
    mocker.patch.object(CacheMixin, "_db_session", MockSession(t))

    r = Team.get(0)
    assert r is t
コード例 #5
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_mixin_set(mocker):
    t = Team(id=0, team_name="hello")

    set_raw_mock = mocker.MagicMock()
    mocker.patch.object(Team, "set_raw", set_raw_mock)

    Team.set(t, expiration_time=900)
    assert set_raw_mock.called
コード例 #6
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_cache_mixin_get_error(mocker):
    with mocker.patch.object(Team._cache_client, 'get',
                             mocker.MagicMock(side_effect=ConnectionError)):
        assert Team.get(0) is None

    with mocker.patch.object(Team._cache_client, 'get',
                             mocker.MagicMock(side_effect=TypeError)):
        assert Team.get(0) is None
コード例 #7
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_cache_mixin__from_cache_error(mocker):
    with mocker.patch.object(Team._cache_client, 'mget',
                             mocker.MagicMock(
                                     side_effect=ConnectionError)):
        assert Team._from_cache([1]) == {}

    with mocker.patch.object(Team._cache_client, 'mget',
                             mocker.MagicMock(side_effect=TypeError)):
        assert Team._from_cache([2]) == {}
コード例 #8
0
ファイル: test_team.py プロジェクト: zhoudaqing/huskar
def test_get_teams_by_admin(db, team_foo, team_bar, user_foo, user_bar):
    assert Team.get_multi_by_admin(user_foo.id) == []
    assert Team.get_multi_by_admin(user_bar.id) == []

    team_foo.grant_admin(user_foo.id)
    team_bar.grant_admin(user_foo.id)
    team_bar.grant_admin(user_bar.id)

    assert Team.get_multi_by_admin(user_foo.id) == [team_foo, team_bar]
    assert Team.get_multi_by_admin(user_bar.id) == [team_bar]
コード例 #9
0
ファイル: test_team.py プロジェクト: zhoudaqing/huskar
def test_create_team(db):
    team = Team.create('bar')
    assert team.id > 0
    assert team.team_name == 'bar'

    with raises(NameOccupiedError):
        Team.create('bar')  # name conflicts

    team = Team.create('baz')
    assert team.team_name == 'baz'
コード例 #10
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_mget_from_db(mocker):
    t1 = Team(id=0, team_name="hello")
    t2 = Team(id=1, team_name="world")

    mocker.patch.object(_RedisWrapper, "mget", mocker.Mock(return_value=None))
    mocker.patch.object(Team, "_db_session", MockSession([t1, t2]))

    r = Team.mget([0, 1, 2])
    assert len(r) == 2
    assert r[0] is t1 and r[1] is t2
コード例 #11
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_mget_get_primary_key(mocker):
    t = Team(id=0, team_name="hello")

    mocker.patch.object(_RedisWrapper, "mget", mocker.Mock(return_value=None))
    mocker.patch.object(Team, "_db_session", MockSession([t]))

    pk = mocker.MagicMock()
    mocker.patch.object(Team, "pk", pk)
    a = Team.mget([0], as_dict=True)
    assert a == {pk: t}
コード例 #12
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_get_cache_miss(mocker):
    t = Team(id=0, team_name="hello")

    mocker.patch.object(_RedisWrapper, "get", mocker.Mock(return_value=None))
    mocker.patch.object(Team, "_db_session", MockSession(t))

    incr = mocker.MagicMock()
    mocker.patch.object(Team, "_statsd_incr", incr)
    Team.get(0)
    incr.assert_called_with("miss")
コード例 #13
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_mget_from_cache(mocker):
    mocker.patch.object(CacheMixin, "_db_session", DBSession)

    t1 = Team(id=0, team_name="hello")
    t2 = Team(id=1, team_name="world")

    with mocker.patch.object(_RedisWrapper, "mget",
                             return_value=[t1.__rawdata__, t2.__rawdata__]):
        m = Team.mget([0, 1])
        assert all([t._cached for t in m])
コード例 #14
0
ファイル: test_team_audit.py プロジェクト: zhoudaqing/huskar
def test_create_team_failed(client, db, test_token):
    assert Team.get_by_name('foo') is None
    assert db.query(AuditLog.id).first() is None

    r = client.post('/api/team', data={'team': 'foo'},
                    headers={'Authorization': test_token})
    assert r.status_code == 400, r.json

    assert Team.get_by_name('foo') is None
    assert db.query(AuditLog.id).first() is None
コード例 #15
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_new_cache_mget(mocker):
    t1 = Team(id=0, team_name="hello")
    t2 = Team(id=1, team_name="world")

    mocker.patch.object(_RedisWrapper, "mget", mocker.Mock(return_value=None))
    mocker.patch.object(Team, "_db_session", MockSession([t1, t2]))

    mset_raw = mocker.MagicMock()
    mocker.patch.object(Team, "_mset_raw", mset_raw)
    Team.mget([0, 1])
    mset_raw.assert_called_with([t1, t2], nx=True)
コード例 #16
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_set_raw(mocker):
    t = Team(id=0, team_name="hello")

    mock_set = mocker.MagicMock()
    mocker.patch.object(_RedisWrapper, "set", mock_set)
    Team.set_raw(t.__rawdata__, expiration_time=900)

    mock_set.assert_called_with(
        "team|0", {'id': 0, 'status': None,
                   'team_desc': None, 'team_name': 'hello'},
        expiration_time=900)
コード例 #17
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_new_cache_get(mocker):
    t = Team(id=0, team_name="hello")

    mocker.patch.object(_RedisWrapper, "get", mocker.Mock(return_value=None))
    mocker.patch.object(CacheMixin, "_db_session", MockSession(t))

    mock_set_raw = mocker.MagicMock()
    mocker.patch.object(Team, "set_raw", mock_set_raw)
    v = Team.get(0)
    mock_set_raw.assert_called_with(v.__rawdata__, nx=True)
    assert v is t
コード例 #18
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_get_from_session(mocker):
    session = DBSession

    mocker.patch.object(CacheMixin, "_db_session", DBSession)

    team = Team(id=0, team_name="test_get_from_session")
    session.add(team)
    session.commit()
    t = Team.get(0)
    assert t is team
    session.close()
コード例 #19
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_mset(mocker):
    t1 = Team(id=0, team_name="hello")
    t2 = Team(id=1, team_name="world")

    mset = mocker.MagicMock()
    mocker.patch.object(_RedisWrapper, "mset", mset)
    Team.mset([t1, t2])

    expected = mocker.call(
        {"team|0": t1.__rawdata__, "team|1": t2.__rawdata__},
        expiration_time=Team.TABLE_CACHE_EXPIRATION_TIME)
    mset.assert_has_calls([expected])
コード例 #20
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_get_cache_hit(mocker):
    mocker.patch.object(CacheMixin, "_db_session", DBSession)

    t = Team(id=0, team_name="hello")
    raw = t.__rawdata__

    mocker.patch.object(_RedisWrapper, "get", mocker.Mock(return_value=raw))

    # get
    incr = mocker.MagicMock()
    mocker.patch.object(Team, "_statsd_incr", incr)
    Team.get(0)
    incr.assert_called_with("hit")
コード例 #21
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_cache_mixin(mocker):
    assert 'team|0' in repr(Team(id=0, team_name="hello"))
    assert Team(id=0, team_name='hello').pk_name() == 'id'
    assert Team(id=0, team_name='hello').pk_attribute().key == 'id'

    t = Team(team_name='test_cache_mixin')
    DBSession.add(t)
    DBSession.commit()
    assert len(Team.mget([t.id], force=True)) == 1

    with pytest.raises(NotImplementedError):
        CacheMixinBase._cache_client.error

    with pytest.raises(NotImplementedError):
        CacheMixinBase._db_session.error

    with mocker.patch.object(CacheMixinBase, 'RAWDATA_VERSION',
                             mocker.MagicMock(__str__=lambda x: '233')):
        assert Team.gen_raw_key(1) == 'team|1|233'

    with mocker.patch.object(Team.__mapper__, 'primary_key',
                             mocker.MagicMock(return_value=[],
                                              __nonzero__=mocker.MagicMock(
                                                  return_value=False))):
        assert Team(id=2, team_name='hello').pk_name() is None
        assert Team(id=3, team_name='hello').pk_attribute() is None
コード例 #22
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_mget_from_session(mocker):
    session = DBSession
    mocker.patch.object(CacheMixin, "_db_session", DBSession)

    t1 = Team(id=0, team_name="hello")
    t2 = Team(id=1, team_name="world")

    for t in (t1, t2):
        session.add(t)
        session.commit()

    r = Team.mget([0, 1])
    assert r[0] is t1 and r[1] is t2
    session.close()
コード例 #23
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_mget_cache_hit(mocker):
    mocker.patch.object(CacheMixin, "_db_session", DBSession)

    t1 = Team(id=0, team_name="hello")
    t2 = Team(id=1, team_name="world")
    raw = [t.__rawdata__ for t in (t1, t2)]

    mocker.patch.object(_RedisWrapper, "mget", mocker.Mock(return_value=raw))

    # get
    incr = mocker.MagicMock()
    mocker.patch.object(Team, "_statsd_incr", incr)
    Team.mget([0, 1])
    incr.assert_called_with("hit", 2)
コード例 #24
0
ファイル: organization.py プロジェクト: zhoudaqing/huskar
    def _create(self, ignore_existed=False):
        team_name = request.values['team'].strip()
        application_name = request.values['application'].strip()
        validate_fields(application_schema,
                        {'name': application_name, 'team_name': team_name})

        team = Team.get_by_name(team_name)
        if team is None:
            abort(400, 'team "%s" does not exist' % team_name)

        require_team_admin_or_site_admin(team)

        application = Application.get_by_name(application_name)
        if application is not None:
            if ignore_existed:
                return api_response()
            raise ApplicationExistedError(
                'application: {} has existed, application is globally '
                'unique'.format(application))

        try:
            application = Application.create(application_name, team.id)
        except NameOccupiedError:
            abort(400, 'The application name {0} has been occupied.'.format(
                application_name))
        audit_log.emit(
            audit_log.types.CREATE_APPLICATION, application=application,
            team=team)
        return api_response()
コード例 #25
0
ファイル: test_application.py プロジェクト: zhoudaqing/huskar
def test_application_transfer_team(db, test_application, faker):
    orig_team_id = test_application.team_id
    dest_team = Team.create(faker.name())
    test_application.transfer_team(dest_team.id)
    application = Application.get_by_name(test_application.application_name)
    assert application.team_id == dest_team.id
    assert test_application.id not in Application.get_ids_by_team(orig_team_id)
    assert test_application.id in Application.get_ids_by_team(dest_team.id)
コード例 #26
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_rawdata_sub(hook, mocker):
    m = Team(id=0, team_name="hello")

    set_raw = mocker.MagicMock()
    mocker.patch.object(CacheMixinBase, "set_raw", set_raw)
    hook._rawdata_sub(m.__rawdata__, Team)

    set_raw.assert_called_with(
        {'id': 0, 'status': None, 'team_desc': None, "team_name": "hello"})
コード例 #27
0
ファイル: test_team.py プロジェクト: zhoudaqing/huskar
def test_delete_team(client, db, admin_token, test_team, test_team_admin):
    assert db.query(Team.id).all() == [(test_team.id, )]
    assert [x.id for x in test_team.list_admin()] == [test_team_admin.id]

    r = client.delete('/api/team/%s' % test_team.team_name,
                      headers={'Authorization': admin_token})
    assert_response_ok(r)
    assert [x.id for x in test_team.list_admin()] == \
        [test_team_admin.id]
    assert Team.get(test_team.id).is_active is False
コード例 #28
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_rollback():
    session = Team._db_session

    try:
        session.add(Team(id=0, team_name="hello"))
        session.flush()
        raise TypeError()
    except:
        session.rollback()
        assert not getattr(session, "pending_write", None)
コード例 #29
0
ファイル: test_cache.py プロジェクト: zhoudaqing/huskar
def test_update_cache_fail_hook(hook, mocker):
    callback_confirm = []

    def callback(data_obj, model, pk, val):
        callback_confirm.append((data_obj, model, pk, val))

    # register callback
    Team.register_set_fail_callback(callback)
    m = Team(id=0, team_name="OK")

    mocker.patch.object(CacheMixinBase, '_cache_client', mocker.MagicMock())
    # perform an exception
    mocker.patch.object(CacheMixinBase, 'set_raw',
                        mocker.MagicMock(side_effect=Exception))

    with pytest.raises(Exception):
        hook._rawdata_sub(m.__rawdata__, Team)
    assert callback_confirm == [
        ({'id': 0, 'status': None, 'team_desc': None, 'team_name': 'OK'},
         Team, 'id', 0)]
コード例 #30
0
ファイル: organization.py プロジェクト: zhoudaqing/huskar
    def post(self):
        """Creates a new team.

        :form team: The name of creating team.
        :<header Authorization: Huskar Token (See :ref:`token`)
        :status 400: The name is invalid.
        :status 200: The team with specified name exists.
        :status 201: The team with specified name is created successfully.
        """
        g.auth.require_admin('only admin can add team')
        team_name = request.form['team'].strip()
        team = Team.get_by_name(team_name)
        if team is not None:
            return api_response(), 200

        try:
            team = Team.create(team_name)
        except NameOccupiedError:
            abort(400, 'Team %s has been archived.' % team_name)
        audit_log.emit(audit_log.types.CREATE_TEAM, team=team)
        return api_response(), 201