Debian Codegraph @

tests/test_export_openapi_schema.py

raw symbols SCIP
1 import json
2 import tempfile
3 from io import StringIO
4 from pathlib import Path
5 from unittest.mock import patch
6
7 import pytest
8 from django.core.management import call_command
9 from django.core.management.base import CommandError
10
11 from ninja.management.commands.export_openapi_schema import Command as ExportCmd
12
13
14 def test_export_default():
15 output = StringIO()
16 call_command(ExportCmd(), stdout=output)
17 json.loads(output.getvalue()) # if no exception, then OK
18 assert len(output.getvalue().splitlines()) == 1
19
20
21 def test_export_indent():
22 output = StringIO()
23 call_command(ExportCmd(), indent=1, stdout=output)
24 assert len(output.getvalue().splitlines()) > 1
25
26
27 def test_export_to_file():
28 with tempfile.TemporaryDirectory() as tmp:
29 output_file = Path(tmp) / "result.json"
30 call_command(ExportCmd(), output=output_file)
31 json.loads(Path(output_file).read_text())
32
33
34 def test_export_custom():
35 with pytest.raises(CommandError):
36 call_command(ExportCmd(), api="something.that.doesnotexist")
37
38 with pytest.raises(CommandError) as e:
39 call_command(ExportCmd(), api="django.core.management.base.BaseCommand")
40 assert (
41 str(e.value)
42 == "django.core.management.base.BaseCommand is not instance of NinjaAPI!"
43 )
44
45 call_command(ExportCmd(), api="demo.urls.api_v1")
46 call_command(ExportCmd(), api="demo.urls.api_v2")
47
48
49 @patch("ninja.management.commands.export_openapi_schema.resolve")
50 def test_export_default_without_api_endpoint(mock):
51 mock.side_effect = AttributeError()
52 output = StringIO()
53 with pytest.raises(CommandError) as e:
54 call_command(ExportCmd(), stdout=output)
55 assert str(e.value) == "No NinjaAPI instance found; please specify one with --api"