Debian Codegraph @

tests/schemas/test_managementcommand.py

raw
1 import io
2 import os
3 import tempfile
4
5 import pytest
6 from django.core.management import call_command
7 from django.test import TestCase
8 from django.test.utils import override_settings
9 from django.urls import path
10
11 from rest_framework.compat import uritemplate, yaml
12 from rest_framework.utils import json
13 from rest_framework.views import APIView
14
15
16 class FooView(APIView):
17 def get(self, request):
18 pass
19
20
21 urlpatterns = [
22 path('', FooView.as_view())
23 ]
24
25
26 class CustomSchemaGenerator:
27 SCHEMA = {"key": "value"}
28
29 def __init__(self, *args, **kwargs):
30 pass
31
32 def get_schema(self, **kwargs):
33 return self.SCHEMA
34
35
36 @override_settings(ROOT_URLCONF=__name__)
37 @pytest.mark.skipif(not uritemplate, reason='uritemplate is not installed')
38 class GenerateSchemaTests(TestCase):
39 """Tests for management command generateschema."""
40
41 def setUp(self):
42 self.out = io.StringIO()
43
44 @pytest.mark.skipif(yaml is None, reason='PyYAML is required.')
45 def test_renders_default_schema_with_custom_title_url_and_description(self):
46 call_command('generateschema',
47 '--title=ExampleAPI',
48 '--url=http://api.example.com',
49 '--description=Example description',
50 stdout=self.out)
51 # Check valid YAML was output.
52 schema = yaml.safe_load(self.out.getvalue())
53 assert schema['openapi'] == '3.0.2'
54
55 def test_renders_openapi_json_schema(self):
56 call_command('generateschema',
57 '--format=openapi-json',
58 stdout=self.out)
59 # Check valid JSON was output.
60 out_json = json.loads(self.out.getvalue())
61 assert out_json['openapi'] == '3.0.2'
62
63 def test_accepts_custom_schema_generator(self):
64 call_command('generateschema',
65 f'--generator_class={__name__}.{CustomSchemaGenerator.__name__}',
66 stdout=self.out)
67 out_json = yaml.safe_load(self.out.getvalue())
68 assert out_json == CustomSchemaGenerator.SCHEMA
69
70 def test_writes_schema_to_file_on_parameter(self):
71 fd, path = tempfile.mkstemp()
72 try:
73 call_command('generateschema', f'--file={path}', stdout=self.out)
74 # nothing on stdout
75 assert not self.out.getvalue()
76
77 call_command('generateschema', stdout=self.out)
78 expected_out = self.out.getvalue()
79 # file output identical to stdout output
80 with os.fdopen(fd) as fh:
81 assert expected_out and fh.read() == expected_out
82 finally:
83 os.remove(path)