File: test_export_openapi_schema.py

package info (click to toggle)
django-ninja 1.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 11,280 kB
  • sloc: python: 15,956; javascript: 1,689; makefile: 39; sh: 25
file content (55 lines) | stat: -rw-r--r-- 1,759 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import json
import tempfile
from io import StringIO
from pathlib import Path
from unittest.mock import patch

import pytest
from django.core.management import call_command
from django.core.management.base import CommandError

from ninja.management.commands.export_openapi_schema import Command as ExportCmd


def test_export_default():
    output = StringIO()
    call_command(ExportCmd(), stdout=output)
    json.loads(output.getvalue())  # if no exception, then OK
    assert len(output.getvalue().splitlines()) == 1


def test_export_indent():
    output = StringIO()
    call_command(ExportCmd(), indent=1, stdout=output)
    assert len(output.getvalue().splitlines()) > 1


def test_export_to_file():
    with tempfile.TemporaryDirectory() as tmp:
        output_file = Path(tmp) / "result.json"
        call_command(ExportCmd(), output=output_file)
        json.loads(Path(output_file).read_text())


def test_export_custom():
    with pytest.raises(CommandError):
        call_command(ExportCmd(), api="something.that.doesnotexist")

    with pytest.raises(CommandError) as e:
        call_command(ExportCmd(), api="django.core.management.base.BaseCommand")
    assert (
        str(e.value)
        == "django.core.management.base.BaseCommand is not instance of NinjaAPI!"
    )

    call_command(ExportCmd(), api="demo.urls.api_v1")
    call_command(ExportCmd(), api="demo.urls.api_v2")


@patch("ninja.management.commands.export_openapi_schema.resolve")
def test_export_default_without_api_endpoint(mock):
    mock.side_effect = AttributeError()
    output = StringIO()
    with pytest.raises(CommandError) as e:
        call_command(ExportCmd(), stdout=output)
    assert str(e.value) == "No NinjaAPI instance found; please specify one with --api"