Debian Codegraph @

tests/test_management.py

raw
1 import json
2 import os
3 import random
4 import string
5 import tempfile
6
7 import pytest
8
9 from drf_yasg import openapi
10 from drf_yasg.codecs import yaml_load
11 from drf_yasg.generators import OpenAPISchemaGenerator
12
13
14 def test_reference_schema(call_generate_swagger, db, reference_schema, compare_schemas):
15 output = call_generate_swagger(
16 format="yaml", api_url="http://test.local:8002/", user="admin"
17 )
18 output_schema = yaml_load(output)
19 compare_schemas(output_schema, reference_schema)
20
21
22 def test_non_public(call_generate_swagger, db):
23 output = call_generate_swagger(
24 format="yaml", api_url="http://test.local:8002/", private=True
25 )
26 output_schema = yaml_load(output)
27 assert len(output_schema["paths"]) == 0
28
29
30 def test_no_mock(call_generate_swagger, db):
31 output = call_generate_swagger()
32 output_schema = json.loads(output)
33 assert len(output_schema["paths"]) > 0
34
35
36 class EmptySchemaGenerator(OpenAPISchemaGenerator):
37 def get_paths(self, endpoints, components, request, public):
38 return openapi.Paths(paths={}), ""
39
40
41 def test_generator_class(call_generate_swagger, db):
42 output = call_generate_swagger(
43 generator_class_name="test_management.EmptySchemaGenerator"
44 )
45 output_schema = json.loads(output)
46 assert len(output_schema["paths"]) == 0
47
48
49 def silent_remove(filename):
50 try:
51 os.remove(filename)
52 except OSError:
53 pass
54
55
56 def test_file_output(call_generate_swagger, db):
57 prefix = os.path.join(tempfile.gettempdir(), tempfile.gettempprefix())
58 name = "".join(
59 random.choice(string.ascii_lowercase + string.digits) for _ in range(8)
60 )
61 yaml_file = prefix + name + ".yaml"
62 json_file = prefix + name + ".json"
63 other_file = prefix + name + ".txt"
64
65 try:
66 # when called with output file nothing should be written to stdout
67 assert call_generate_swagger(output_file=yaml_file) == ""
68 assert call_generate_swagger(output_file=json_file) == ""
69 assert call_generate_swagger(output_file=other_file) == ""
70
71 with pytest.raises(OSError):
72 # a second call should fail because file exists
73 call_generate_swagger(output_file=yaml_file)
74
75 # a second call with overwrite should still succeed
76 assert call_generate_swagger(output_file=json_file, overwrite=True) == ""
77
78 with open(yaml_file) as f:
79 content = f.read()
80 # YAML is a superset of JSON - that means we have to check that
81 # the file is really YAML and not just JSON parsed by the YAML parser
82 with pytest.raises(ValueError):
83 json.loads(content)
84 output_yaml = yaml_load(content)
85 with open(json_file) as f:
86 output_json = json.load(f)
87 with open(other_file) as f:
88 output_other = json.load(f)
89
90 assert output_yaml == output_json == output_other
91 finally:
92 silent_remove(yaml_file)
93 silent_remove(json_file)
94 silent_remove(other_file)