import pytest

from app.exts import db
from app.models import {{ metadata | join(', ') }}

from .import BaseTest


{% for model_name, Model in metadata.items() -%}
class Test{{ model_name }}(BaseTest):

    @pytest.fixture
    def instance(self):
        instance = {{ model_name }}(
            {%- for c in Model.columns -%}
            {{ c.field }}={{ c.test }}{%- if not loop.last -%}, {% endif -%}
            {%- endfor -%})
        db.session.add(instance)
        db.session.flush()
        db.session.commit()
        return instance

    def test_list(self, client):
        resp = client.get('/api/{{ Model.plural }}{{ tail_slash }}')
        assert resp.status_code == 200
        assert set(resp.json.keys()) == {'items', 'page', 'page_size', 'total'}

    def test_retrieve(self, client, instance):
        resp = client.get(f'/api/{{ Model.plural }}/{instance.id}{{ tail_slash }}')
        assert resp.status_code == 200
        assert set(resp.json.keys()) == {
            'created_at', 'id', 'updated_at'{%- for c in Model.columns -%}, '{{ c.field }}'{%- endfor -%}}

    def test_create(self, client):
        payload = {
            {%- for c in Model.columns -%}
            '{{ c.field }}': {{ c.test }}{%- if not loop.last -%}, {% endif -%}
            {%- endfor -%}
        }
        resp = client.post('/api/{{ Model.plural }}{{ tail_slash }}', json=payload)
        assert resp.status_code == 201
        assert set(resp.json.keys()) == {
            'created_at', 'id', 'updated_at'{%- for c in Model.columns -%}, '{{ c.field }}'{%- endfor -%}}
        for k, v in payload.items():
            assert resp.json[k] == v

    def test_update(self, client, instance):
        payload = {
            {%- for c in Model.columns -%}
            '{{ c.field }}': {{ c.test }}{%- if not loop.last -%}, {% endif -%}
            {%- endfor -%}
        }
        resp = client.put(f'/api/{{ Model.plural }}/{instance.id}{{ tail_slash }}', json=payload)
        assert resp.status_code == 200
        assert set(resp.json.keys()) == {
            'created_at', 'id', 'updated_at'{%- for c in Model.columns -%}, '{{ c.field }}'{%- endfor -%}}
        for k, v in payload.items():
            assert resp.json[k] == v

    def test_delete(self, client, instance):
        resp = client.delete(f'/api/{{ Model.plural }}{{ tail_slash }}?ids={instance.id}')
        assert resp.status_code == 204
        assert {{ model_name }}.query.get(instance.id) is None
{% if not loop.last %}

{% endif %}
{%- endfor %}