Пример #1
0
    def test_count(self):
        with count_queries() as count:
            Data.create(key='k1')
            Data.create(key='k2')

        self.assertEqual(count.count, 2)

        with count_queries() as count:
            items = [item.key for item in Data.select().order_by(Data.key)]
            self.assertEqual(items, ['k1', 'k2'])

            Data.get(Data.key == 'k1')
            Data.get(Data.key == 'k2')

        self.assertEqual(count.count, 3)
Пример #2
0
    def test_count(self):
        with count_queries() as count:
            Data.create(key='k1')
            Data.create(key='k2')

        self.assertEqual(count.count, 2)

        with count_queries() as count:
            items = [item.key for item in Data.select().order_by(Data.key)]
            self.assertEqual(items, ['k1', 'k2'])

            Data.get(Data.key == 'k1')
            Data.get(Data.key == 'k2')

        self.assertEqual(count.count, 3)
Пример #3
0
def test_e2e_query_count_manifest_norewrite(client, app):
    repo_ref = registry_model.lookup_repository("devtable", "simple")
    tag = registry_model.get_repo_tag(repo_ref, "latest")
    manifest = registry_model.get_manifest_for_tag(tag)

    params = {
        "repository": "devtable/simple",
        "manifest_ref": manifest.digest,
    }

    user = model.user.get_user("devtable")
    access = [{
        "type": "repository",
        "name": "devtable/simple",
        "actions": ["pull", "push"],
    }]

    context, subject = build_context_and_subject(
        ValidatedAuthContext(user=user))
    token = generate_bearer_token(realapp.config["SERVER_HOSTNAME"], subject,
                                  context, access, 600, instance_keys)

    headers = {
        "Authorization": "Bearer %s" % token.decode("ascii"),
    }

    # Conduct a call to prime the instance key and other caches.
    conduct_call(
        client,
        "v2.write_manifest_by_digest",
        url_for,
        "PUT",
        params,
        expected_code=201,
        headers=headers,
        raw_body=manifest.internal_manifest_bytes.as_encoded_str(),
    )

    timecode = time.time()

    def get_time():
        return timecode + 10

    with patch("time.time", get_time):
        # Necessary in order to have the tag updates not occur in the same second, which is the
        # granularity supported currently.
        with count_queries() as counter:
            conduct_call(
                client,
                "v2.write_manifest_by_digest",
                url_for,
                "PUT",
                params,
                expected_code=201,
                headers=headers,
                raw_body=manifest.internal_manifest_bytes.as_encoded_str(),
            )

        assert counter.count <= 27
Пример #4
0
    def test_index_preservation(self):
        with count_queries() as qc:
            migrate(self.migrator.rename_column(
                'indexmodel',
                'first_name',
                'first'))

        queries = [log.msg for log in qc.get_queries()]
        self.assertEqual(queries, [
            # Get all the columns.
            ('PRAGMA table_info("indexmodel")', None),

            # Get the table definition.
            ('select name, sql from sqlite_master '
             'where type=? and LOWER(name)=?',
             ['table', 'indexmodel']),

            # Get the indexes and indexed columns for the table.
            ('SELECT name, sql FROM sqlite_master '
             'WHERE tbl_name = ? AND type = ? ORDER BY name',
             ('indexmodel', 'index')),
            ('PRAGMA index_list("indexmodel")', None),
            ('PRAGMA index_info("indexmodel_data")', None),
            ('PRAGMA index_info("indexmodel_first_name_last_name")', None),

            # Get foreign keys.
            ('PRAGMA foreign_key_list("indexmodel")', None),

            # Drop any temporary table, if it exists.
            ('DROP TABLE IF EXISTS "indexmodel__tmp__"', []),

            # Create a temporary table with the renamed column.
            ('CREATE TABLE "indexmodel__tmp__" ('
             '"id" INTEGER NOT NULL PRIMARY KEY, '
             '"first" VARCHAR(255) NOT NULL, '
             '"last_name" VARCHAR(255) NOT NULL, '
             '"data" INTEGER NOT NULL)', []),

            # Copy data from original table into temporary table.
            ('INSERT INTO "indexmodel__tmp__" '
             '("id", "first", "last_name", "data") '
             'SELECT "id", "first_name", "last_name", "data" '
             'FROM "indexmodel"', []),

            # Drop the original table.
            ('DROP TABLE "indexmodel"', []),

            # Rename the temporary table, replacing the original.
            ('ALTER TABLE "indexmodel__tmp__" RENAME TO "indexmodel"', []),

            # Re-create the indexes.
            ('CREATE UNIQUE INDEX "indexmodel_data" '
             'ON "indexmodel" ("data")', []),
            ('CREATE UNIQUE INDEX "indexmodel_first_last_name" '
             'ON "indexmodel" ("first", "last_name")', [])
        ])
Пример #5
0
    def test_index_preservation(self):
        with count_queries() as qc:
            migrate(
                self.migrator.rename_column('indexmodel', 'first_name',
                                            'first'))

        queries = [log.msg for log in qc.get_queries()]
        self.assertEqual(
            queries,
            [
                # Get all the columns.
                ('PRAGMA table_info("indexmodel")', None),

                # Get the table definition.
                ('select name, sql from sqlite_master '
                 'where type=? and LOWER(name)=?', ['table', 'indexmodel']),

                # Get the indexes and indexed columns for the table.
                ('SELECT name, sql FROM sqlite_master '
                 'WHERE tbl_name = ? AND type = ? ORDER BY name',
                 ('indexmodel', 'index')),
                ('PRAGMA index_list("indexmodel")', None),
                ('PRAGMA index_info("indexmodel_data")', None),
                ('PRAGMA index_info("indexmodel_first_name_last_name")', None),

                # Get foreign keys.
                ('PRAGMA foreign_key_list("indexmodel")', None),

                # Drop any temporary table, if it exists.
                ('DROP TABLE IF EXISTS "indexmodel__tmp__"', []),

                # Create a temporary table with the renamed column.
                ('CREATE TABLE "indexmodel__tmp__" ('
                 '"id" INTEGER NOT NULL PRIMARY KEY, '
                 '"first" VARCHAR(255) NOT NULL, '
                 '"last_name" VARCHAR(255) NOT NULL, '
                 '"data" INTEGER NOT NULL)', []),

                # Copy data from original table into temporary table.
                ('INSERT INTO "indexmodel__tmp__" '
                 '("id", "first", "last_name", "data") '
                 'SELECT "id", "first_name", "last_name", "data" '
                 'FROM "indexmodel"', []),

                # Drop the original table.
                ('DROP TABLE "indexmodel"', []),

                # Rename the temporary table, replacing the original.
                ('ALTER TABLE "indexmodel__tmp__" RENAME TO "indexmodel"', []),

                # Re-create the indexes.
                ('CREATE UNIQUE INDEX "indexmodel_data" '
                 'ON "indexmodel" ("data")', []),
                ('CREATE UNIQUE INDEX "indexmodel_first_name_last_name" '
                 'ON "indexmodel" ("first", "last_name")', [])
            ])
Пример #6
0
def test_e2e_query_count_manifest_norewrite(client, app):
    tag_manifest = model.tag.load_tag_manifest('devtable', 'simple', 'latest')

    params = {
        'repository': 'devtable/simple',
        'manifest_ref': tag_manifest.digest,
    }

    user = model.user.get_user('devtable')
    access = [{
        'type': 'repository',
        'name': 'devtable/simple',
        'actions': ['pull', 'push'],
    }]

    context, subject = build_context_and_subject(
        ValidatedAuthContext(user=user))
    token = generate_bearer_token(realapp.config['SERVER_HOSTNAME'], subject,
                                  context, access, 600, instance_keys)

    headers = {
        'Authorization': 'Bearer %s' % token,
    }

    # Conduct a call to prime the instance key and other caches.
    conduct_call(client,
                 'v2.write_manifest_by_digest',
                 url_for,
                 'PUT',
                 params,
                 expected_code=202,
                 headers=headers,
                 raw_body=tag_manifest.json_data)

    timecode = time.time()

    def get_time():
        return timecode + 10

    with patch('time.time', get_time):
        # Necessary in order to have the tag updates not occur in the same second, which is the
        # granularity supported currently.
        with count_queries() as counter:
            conduct_call(client,
                         'v2.write_manifest_by_digest',
                         url_for,
                         'PUT',
                         params,
                         expected_code=202,
                         headers=headers,
                         raw_body=tag_manifest.json_data)

        assert counter.count <= 27
Пример #7
0
    def test_only_select(self):
        with count_queries(only_select=True) as count:
            for i in range(10):
                Data.create(key=str(i))

            items = [item.key for item in Data.select()]
            Data.get(Data.key == '0')
            Data.get(Data.key == '9')

            Data.delete().where(
                Data.key << ['1', '3', '5', '7', '9']).execute()

            items = [item.key for item in Data.select().order_by(Data.key)]
            self.assertEqual(items, ['0', '2', '4', '6', '8'])

        self.assertEqual(count.count, 4)
Пример #8
0
    def test_only_select(self):
        with count_queries(only_select=True) as count:
            for i in range(10):
                Data.create(key=str(i))

            items = [item.key for item in Data.select()]
            Data.get(Data.key == '0')
            Data.get(Data.key == '9')

            Data.delete().where(
                Data.key << ['1', '3', '5', '7', '9']).execute()

            items = [item.key for item in Data.select().order_by(Data.key)]
            self.assertEqual(items, ['0', '2', '4', '6', '8'])

        self.assertEqual(count.count, 4)
Пример #9
0
def test_fk(build_test_client, bind_models):
    bind_models(Lineitem, Invoice)

    class LineitemController(ListAPIController):
        modelselect = Lineitem
        schema_class = LineitemSchema
        prefetch = (Invoice, )

    client = build_test_client({'/lineItems': LineitemController()})

    Lineitem.create(invoice=Invoice.create(number='1'), name='Foo', amount=432)
    Lineitem.create(invoice=Invoice.create(number='2'), name='Bar', amount=200)

    with test_utils.count_queries() as counter:
        results = client.simulate_get('/lineItems').json
        assert len(results) == 2
        foo = next(r for r in results if r['name'] == 'Foo')
        assert foo
        assert foo['amount'] == 432
        assert foo['invoice']['number'] == '1'

    assert counter.count == 2
Пример #10
0
def test_list_fk(build_test_client, bind_models):
    bind_models(Lineitem, Invoice)

    class InvoiceController(RetrieveAPIController):
        modelselect = Invoice
        schema_class = InvoiceSchema
        prefetch = (Lineitem, )

    invoice = Invoice.create(number='123')
    Lineitem.create(invoice=invoice, name='Sproket', amount=1.23)
    Lineitem.create(invoice=invoice, name='Gear', amount=2.00)
    Lineitem.create(invoice=invoice, name='Shaft', amount=3.00)
    Lineitem.create(invoice=invoice, name='Lever', amount=4.00)

    client = build_test_client({'/invoice/{id}': InvoiceController()})

    with test_utils.count_queries() as counter:
        results = client.simulate_get(f'/invoice/{invoice.id}').json
        assert results['number'] == '123'
        assert isinstance(results['lineitems'], list)
        lineitems = results['lineitems']
        assert len(lineitems) == 4
        assert lineitems[0]['name'] == 'Sproket'
    assert counter.count == 2
Пример #11
0
 def wrapper(*args, **kwargs):
     with count_queries() as counter:
         result = func(*args, **kwargs)
     print(counter.count)
     return result