# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
System tests for metadata.
"""
import pytest

from google.cloud import ndb

from test_utils import retry


_retry_assertion_errors = retry.RetryErrors(AssertionError)


@pytest.mark.usefixtures("client_context")
def test_kind_metadata(dispose_of):
    from google.cloud.ndb.metadata import Kind

    class AnyKind(ndb.Model):
        foo = ndb.IntegerProperty()

    class MyKind(ndb.Model):
        bar = ndb.StringProperty()

    entity1 = AnyKind(foo=1, id="x", namespace="_test_namespace_")
    entity1.put()
    dispose_of(entity1.key._key)

    entity2 = MyKind(bar="x", id="x", namespace="_test_namespace_")
    entity2.put()
    dispose_of(entity2.key._key)

    @_retry_assertion_errors
    def query_metadata():
        query = ndb.Query(kind=Kind.KIND_NAME, namespace="_test_namespace_")
        results = query.fetch()
        kinds = [result.kind_name for result in results]
        assert all(kind in kinds for kind in ["AnyKind", "MyKind"])

    query_metadata()


@pytest.mark.usefixtures("client_context")
def test_get_kinds(dispose_of):
    from google.cloud.ndb.metadata import get_kinds

    class AnyKind(ndb.Model):
        foo = ndb.IntegerProperty()

    class MyKind(ndb.Model):
        bar = ndb.StringProperty()

    class OtherKind(ndb.Model):
        baz = ndb.IntegerProperty()

    class SomeKind(ndb.Model):
        qux = ndb.StringProperty()

    entity1 = AnyKind(foo=1)
    entity1.put()
    dispose_of(entity1.key._key)

    entity2 = MyKind(bar="a")