Debian Codegraph @

tests/test_parser.py

raw symbols SCIP
1 # encoding: utf-8
2
3 # This file is part of requirements-parser library.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17 # SPDX-License-Identifier: Apache-2.0
18
19 import json
20 import warnings
21 from os import listdir
22 from os.path import dirname, isfile, join
23 from types import GeneratorType
24 from typing import List
25 from unittest import TestCase
26
27 from requirements import parse
28
29
30 class TestParser(TestCase):
31 _requirements_files_dir: str
32
33 @classmethod
34 def setUpClass(cls) -> None:
35 cls._requirements_files_dir = join(dirname(__file__), 'reqfiles')
36
37 def test_requirement_files(self) -> None:
38 for fn in listdir(TestParser._requirements_files_dir):
39 fp = join(TestParser._requirements_files_dir, fn)
40
41 # skip ".expected" files
42 if not isfile(fp) or not fp.endswith('.txt'):
43 continue
44
45 self._test_req_file(req_file=fn)
46
47 def _test_req_file(self, req_file: str) -> None:
48 fp = join(TestParser._requirements_files_dir, req_file)
49 with open(fp) as req_fh:
50 with warnings.catch_warnings():
51 warnings.simplefilter('ignore')
52 parsed = parse(req_fh)
53
54 if 'fail' in req_file:
55 with self.assertRaises(ValueError):
56 list([dict(r) for r in parsed])
57 else:
58 with open(fp[:-4] + '.expected', 'r') as f2:
59 self.assertIsInstance(parsed, GeneratorType)
60 self.assertEqual(json.loads(f2.read()), listify(dict(r) for r in parsed),
61 msg=f'Failed on {fp}')
62
63
64 def listify(iterable: GeneratorType) -> List:
65 out = []
66
67 for item in iterable:
68 if isinstance(item, dict):
69 for key, value in item.items():
70 if isinstance(item[key], (tuple, list)):
71 if key in ('extras', 'specs'):
72 # enforce predictability
73 item[key] = sorted(listify(value))
74 # item[key] = listify(value)
75 elif isinstance(item, (tuple, list)):
76 item = listify(item)
77 out.append(item)
78 return out