dicom-validator 0.9.dev0__tar.gz → 0.9.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/PKG-INFO +3 -3
  2. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/README.md +2 -2
  3. dicom_validator-0.9.1/dicom_validator/__init__.py +1 -0
  4. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/command_line_utils.py +5 -1
  5. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/dump_dcm_info.py +3 -5
  6. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/spec_reader/condition.py +4 -4
  7. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/spec_reader/condition_grammar.py +27 -28
  8. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/spec_reader/edition_reader.py +44 -12
  9. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/spec_reader/enum_parser.py +8 -11
  10. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/spec_reader/part3_reader.py +4 -7
  11. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/spec_reader/spec_reader.py +6 -6
  12. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tests/spec_reader/test_condition_parser.py +12 -12
  13. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tests/spec_reader/test_edition_reader.py +57 -5
  14. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tests/spec_reader/test_part3_reader.py +3 -3
  15. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tests/test_cmdline_tools.py +1 -1
  16. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tests/utils.py +1 -1
  17. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tests/validator/conftest.py +7 -4
  18. dicom_validator-0.9.1/dicom_validator/tests/validator/test_condition_value_index.py +129 -0
  19. dicom_validator-0.9.1/dicom_validator/tests/validator/test_dicom_file_validator.py +219 -0
  20. dicom_validator-0.9.1/dicom_validator/tests/validator/test_error_handler.py +219 -0
  21. dicom_validator-0.9.1/dicom_validator/tests/validator/test_html_filename.py +40 -0
  22. dicom_validator-0.9.1/dicom_validator/tests/validator/test_html_links.py +107 -0
  23. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tests/validator/test_iod_validator.py +42 -2
  24. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tests/validator/test_iod_validator_func_groups.py +3 -4
  25. dicom_validator-0.9.1/dicom_validator/tests/validator/test_validation_result.py +59 -0
  26. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/validate_iods.py +1 -1
  27. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/validator/dicom_file_validator.py +48 -26
  28. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/validator/error_handler.py +122 -65
  29. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/validator/html_error_handler.py +31 -83
  30. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/validator/iod_validator.py +38 -31
  31. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/validator/validation_result.py +5 -4
  32. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator.egg-info/PKG-INFO +3 -3
  33. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator.egg-info/SOURCES.txt +4 -0
  34. dicom_validator-0.9.dev0/dicom_validator/__init__.py +0 -1
  35. dicom_validator-0.9.dev0/dicom_validator/tests/validator/test_dicom_file_validator.py +0 -110
  36. dicom_validator-0.9.dev0/dicom_validator/tests/validator/test_error_handler.py +0 -62
  37. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/LICENSE +0 -0
  38. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/py.typed +0 -0
  39. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/spec_reader/__init__.py +0 -0
  40. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/spec_reader/condition_parser.py +1 -1
  41. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/spec_reader/part4_reader.py +0 -0
  42. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/spec_reader/part6_reader.py +0 -0
  43. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/spec_reader/serializer.py +0 -0
  44. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tag_tools.py +0 -0
  45. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tests/__init__.py +0 -0
  46. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tests/spec_reader/__init__.py +0 -0
  47. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tests/spec_reader/conftest.py +0 -0
  48. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tests/spec_reader/test_condition.py +1 -1
  49. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tests/spec_reader/test_enum_parser.py +1 -1
  50. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tests/spec_reader/test_part4_reader.py +1 -1
  51. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tests/spec_reader/test_part6_reader.py +0 -0
  52. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tests/spec_reader/test_spec_reader.py +0 -0
  53. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/tests/validator/__init__.py +0 -0
  54. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/validator/__init__.py +0 -0
  55. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator/validator/dicom_info.py +0 -0
  56. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator.egg-info/dependency_links.txt +0 -0
  57. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator.egg-info/entry_points.txt +0 -0
  58. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator.egg-info/requires.txt +0 -0
  59. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/dicom_validator.egg-info/top_level.txt +0 -0
  60. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/pyproject.toml +0 -0
  61. {dicom_validator-0.9.dev0 → dicom_validator-0.9.1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dicom-validator
3
- Version: 0.9.dev0
3
+ Version: 0.9.1
4
4
  Summary: Python DICOM validator using input from DICOM specs in docbook format
5
5
  Author-email: mrbean-bremen and contributors <hansemrbean@googlemail.com>
6
6
  License: MIT
@@ -206,8 +206,8 @@ from pathlib import Path
206
206
  from dicom_validator.spec_reader.edition_reader import EditionReader
207
207
 
208
208
  reader = EditionReader() # uses the default location <user home>/dicom-validator
209
- # if the edition is not downloaded yet, load_dicom_info will download and process it
210
- dicom_info = reader.load_dicom_info("2025b") # could also use "current" for the current standard
209
+ # if the edition is not downloaded yet, dicom_info_for_edition will download and process it
210
+ dicom_info = reader.dicom_info_for_edition("2025b") # could also use "current" for the current standard
211
211
  ```
212
212
  Using this DICOM information, you can validate a DICOM file, or all DICOM files
213
213
  in a given directory:
@@ -164,8 +164,8 @@ from pathlib import Path
164
164
  from dicom_validator.spec_reader.edition_reader import EditionReader
165
165
 
166
166
  reader = EditionReader() # uses the default location <user home>/dicom-validator
167
- # if the edition is not downloaded yet, load_dicom_info will download and process it
168
- dicom_info = reader.load_dicom_info("2025b") # could also use "current" for the current standard
167
+ # if the edition is not downloaded yet, dicom_info_for_edition will download and process it
168
+ dicom_info = reader.dicom_info_for_edition("2025b") # could also use "current" for the current standard
169
169
  ```
170
170
  Using this DICOM information, you can validate a DICOM file, or all DICOM files
171
171
  in a given directory:
@@ -0,0 +1 @@
1
+ __version__ = "0.9.1"
@@ -33,7 +33,11 @@ def add_edition_args(parser: argparse.ArgumentParser) -> None:
33
33
  def dicom_info_from_args(args: argparse.Namespace) -> DicomInfo | None:
34
34
  """Retrieve DICOM info using edition related parser arguments."""
35
35
  if not os.path.exists(args.standard_path):
36
- print(f"Invalid standard path {args.standard_path} - aborting")
36
+ try:
37
+ Path(args.standard_path).mkdir(parents=True)
38
+ except OSError:
39
+ print(f"Failed to create {args.standard_path} - aborting")
40
+ return None
37
41
  if args.revision:
38
42
  edition_str = args.revision
39
43
  warnings.warn(
@@ -8,10 +8,10 @@ import re
8
8
  import sys
9
9
  from collections.abc import Iterable, Sequence
10
10
 
11
- from pydicom import config, dcmread, Dataset, DataElement
11
+ from pydicom import DataElement, Dataset, config, dcmread
12
12
  from pydicom.errors import InvalidDicomError
13
13
 
14
- from dicom_validator.command_line_utils import dicom_info_from_args, add_edition_args
14
+ from dicom_validator.command_line_utils import add_edition_args, dicom_info_from_args
15
15
  from dicom_validator.validator.dicom_info import DicomInfo
16
16
 
17
17
 
@@ -108,9 +108,7 @@ class DataElementDumper:
108
108
 
109
109
  def print_sequence(self, sequence: Iterable[Dataset]) -> None:
110
110
  indent = 2 * self.level
111
- format_string = "{{}}Item {{:<{}}} [Dataset with {{}} element(s)]".format(
112
- 56 - indent
113
- )
111
+ format_string = f"{{}}Item {{:<{56 - indent}}} [Dataset with {{}} element(s)]"
114
112
  for i, dataset in enumerate(sequence):
115
113
  print(format_string.format(" " * indent, i + 1, len(dataset)))
116
114
  self.level += 1
@@ -1,11 +1,11 @@
1
1
  import enum
2
- from typing import Optional, Any, Union
2
+ from typing import Any
3
3
 
4
4
  from pydicom.tag import BaseTag
5
5
 
6
6
  from dicom_validator.tag_tools import tag_name_from_id
7
7
 
8
- ValuesType = list[Union[str, int]]
8
+ ValuesType = list[str | int]
9
9
 
10
10
 
11
11
  class ConditionType(str, enum.Enum): # replace later with StrEnum from Python 3.11
@@ -111,7 +111,7 @@ class Condition:
111
111
  tag: str | None
112
112
  the ID of the required tag in the form '(####,####)' or None
113
113
  index: int
114
- the index of the tag for multivalued tags or 0
114
+ the 1-based index of the tag for multivalued tags or 0
115
115
  values: list[str] | None
116
116
  a list of values the tag shall have if the condition
117
117
  is fulfilled, or None
@@ -177,7 +177,7 @@ class Condition:
177
177
 
178
178
  @classmethod
179
179
  def read_condition(
180
- cls, condition_dict: dict, condition: Optional["Condition"] = None
180
+ cls, condition_dict: dict, condition: "Condition | None" = None
181
181
  ) -> "Condition":
182
182
  """Create or update a Condition object from a condition dict.
183
183
  Parameters
@@ -3,31 +3,31 @@ from re import RegexFlag
3
3
  from urllib.parse import ParseResult
4
4
 
5
5
  from pyparsing import (
6
- ParserElement,
6
+ AtLineStart,
7
+ CaselessKeyword,
8
+ Combine,
9
+ DelimitedList,
7
10
  Group,
11
+ Keyword,
8
12
  OneOrMore,
9
- Suppress,
10
- Combine,
11
13
  Opt,
14
+ ParseException,
15
+ ParserElement,
16
+ Regex,
17
+ Suppress,
12
18
  Word,
13
- nums,
14
- alphanums,
15
- DelimitedList,
16
19
  ZeroOrMore,
17
- ParseException,
20
+ alphanums,
18
21
  alphas,
19
- CaselessKeyword,
20
- Keyword,
21
- Regex,
22
- AtLineStart,
22
+ nums,
23
23
  )
24
24
 
25
25
  from dicom_validator.spec_reader.condition import (
26
- ConditionOperator,
27
- ConditionMeaning,
28
26
  Condition,
29
- is_binary_condition,
27
+ ConditionMeaning,
28
+ ConditionOperator,
30
29
  ConditionType,
30
+ is_binary_condition,
31
31
  )
32
32
 
33
33
 
@@ -52,7 +52,7 @@ class ConditionGrammar:
52
52
  # pyparsing is quite slow, so for some performance improvement
53
53
  # we use packrat parsing for caching, and Regex where possible
54
54
  # to reduce the number of function calls
55
- ParserElement.enablePackrat()
55
+ ParserElement.enable_packrat()
56
56
  value_grammar = self._value_grammar(self._tag_expression_grammar(is_value=True))
57
57
  tag_expression_grammar = self._tag_expression_grammar(is_value=False)
58
58
  simple_condition_grammar = (
@@ -209,7 +209,7 @@ class ConditionGrammar:
209
209
  tag_index = 0
210
210
  index = 0
211
211
  if result[0] in ("1", "2", "3", "4"):
212
- tag_index = int(result[0]) - 1
212
+ tag_index = int(result[0])
213
213
  index += 1
214
214
  values: list = result[index + 1 :] # type: ignore[assignment]
215
215
  return self._validate_condition(
@@ -377,10 +377,10 @@ class ConditionGrammar:
377
377
  value_index3 = Regex(r"(, )?Value (?P<index>\d)").set_parse_action(
378
378
  lambda r: r.index
379
379
  )
380
- prefix1_regex = "((the|a) )?[vV]alue( (of|for))?"
380
+ prefix1_regex = "((the|a) )?[Vv]alue( (of|for))?"
381
381
  prefix2_regex = "(the|either|Attribute)?"
382
382
  tag_expr_prefix = Suppress(
383
- Regex(f"({prefix1_regex}|{prefix2_regex})( the( [vV]alue))?")
383
+ Regex(f"({prefix1_regex}|{prefix2_regex})( the( [Vv]alue))?")
384
384
  ) + Opt(tag_id)
385
385
  tag_name_expr = Opt(value_index1 | value_index2 | tag_expr_prefix) + tag_name
386
386
  action = (
@@ -485,18 +485,17 @@ class ConditionGrammar:
485
485
  expr_index = 0
486
486
  tag_index = 0
487
487
  if len(tag_expr) > 1 and is_index(tag_expr[expr_index]):
488
- tag_index = int(tag_expr[expr_index]) - 1
488
+ tag_index = int(tag_expr[expr_index])
489
489
  expr_index += 1
490
490
  tag_name = tag_expr[expr_index]
491
491
  expr_index += 1
492
- if len(tag_expr) > expr_index:
493
- if is_index(tag_expr[expr_index]):
494
- tag_index = int(tag_expr[expr_index]) - 1
495
- expr_index += 1
492
+ if len(tag_expr) > expr_index and is_index(tag_expr[expr_index]):
493
+ tag_index = int(tag_expr[expr_index])
494
+ expr_index += 1
496
495
  tag_id = tag_expr[expr_index] if len(tag_expr) > expr_index else None
497
496
  expr_index += 1
498
497
  if len(tag_expr) > expr_index and is_index(tag_expr[expr_index]):
499
- tag_index = int(tag_expr[expr_index]) - 1
498
+ tag_index = int(tag_expr[expr_index])
500
499
  tag = self._tag_id_from_id_and_name(tag_id, tag_name)
501
500
  if tag is None:
502
501
  raise ParseException(f"Not a valid tag expression: {tag_expr}")
@@ -509,12 +508,12 @@ class ConditionGrammar:
509
508
 
510
509
  if not tag_id:
511
510
  # tag name only - look it up
512
- for tag_id, entry in self.dict_info.items():
511
+ for info_tag_id, entry in self.dict_info.items():
513
512
  if entry["name"] == tag_name:
514
- return tag_id
515
- for tag_id, entry in self.uid_dict_info.items():
513
+ return info_tag_id
514
+ for info_tag_id, entry in self.uid_dict_info.items():
516
515
  if entry["name"] == tag_name:
517
- return tag_id
516
+ return info_tag_id
518
517
  return None
519
518
 
520
519
  # we have both tag name and ID
@@ -6,9 +6,9 @@ import re
6
6
  import sys
7
7
  import time
8
8
  from abc import ABC
9
- from pathlib import Path
10
-
11
9
  from collections.abc import Iterable
10
+ from pathlib import Path
11
+ from urllib.error import ContentTooShortError
12
12
  from urllib.request import urlretrieve
13
13
 
14
14
  from dicom_validator import __version__
@@ -19,6 +19,14 @@ from dicom_validator.spec_reader.serializer import DefinitionEncoder
19
19
  from dicom_validator.validator.dicom_info import DicomInfo
20
20
 
21
21
 
22
+ class InvalidEditionError(ValueError):
23
+ pass
24
+
25
+
26
+ class EditionLoadError(RuntimeError):
27
+ pass
28
+
29
+
22
30
  class EditionParser(html_parser.HTMLParser, ABC):
23
31
  edition_re = re.compile(r"\d\d\d\d[a-h]")
24
32
 
@@ -126,7 +134,7 @@ class EditionReader:
126
134
  self.logger.info("Getting DICOM editions...")
127
135
  self.retrieve(self.path / self.html_filename)
128
136
  self.write_to_json()
129
- except BaseException as exception:
137
+ except (OSError, ContentTooShortError) as exception:
130
138
  self.logger.warning("Failed to get DICOM editions: %s", str(exception))
131
139
 
132
140
  def retrieve(self, html_path: Path) -> None:
@@ -158,9 +166,9 @@ class EditionReader:
158
166
  editions_path = self.editions_path()
159
167
  if editions_path.exists():
160
168
  if update:
161
- today = datetime.datetime.today()
169
+ today = datetime.datetime.now(tz=datetime.timezone.utc)
162
170
  modified_date = datetime.datetime.fromtimestamp(
163
- editions_path.stat().st_mtime
171
+ editions_path.stat().st_mtime, tz=datetime.timezone.utc
164
172
  )
165
173
  # no need to update the edition dir more than once a month
166
174
  update = (today - modified_date).days > 30
@@ -255,9 +263,7 @@ class EditionReader:
255
263
  return edition_str == editions[-1]
256
264
  if len(edition_str) == 4:
257
265
  return editions[-1].startswith(edition_str)
258
- if edition_str == "current":
259
- return True
260
- return False
266
+ return edition_str == "current"
261
267
 
262
268
  def get_edition_and_path(self, edition_str: str) -> tuple[str | None, Path | None]:
263
269
  """Resolve an edition selector and return its local base path.
@@ -299,14 +305,12 @@ class EditionReader:
299
305
  if file_path.exists():
300
306
  return True
301
307
  edition_part = "current" if self.is_current(edition) else edition
302
- url = "{0}{1}/source/docbook/part{2:02}/part{2:02}.xml".format(
303
- self.base_url, edition_part, chapter
304
- )
308
+ url = f"{self.base_url}{edition_part}/source/docbook/part{chapter:02}/part{chapter:02}.xml"
305
309
  try:
306
310
  self.logger.info(f"Downloading DICOM spec {edition} PS3.{chapter}...")
307
311
  urlretrieve(url, file_path)
308
312
  return True
309
- except BaseException as exception:
313
+ except (OSError, AttributeError, ContentTooShortError) as exception:
310
314
  self.logger.error(f"Failed to download {url}: {exception}")
311
315
  if file_path.exists():
312
316
  try:
@@ -355,6 +359,34 @@ class EditionReader:
355
359
  self.load_info(edition, self.module_info_json),
356
360
  )
357
361
 
362
+ def dicom_info_for_edition(self, edition: str) -> DicomInfo:
363
+ """Looks up the edition, downloads and processes the DICOM files if needed,
364
+ and returns the existing or newly created DICOM info object.
365
+
366
+ Parameters
367
+ ----------
368
+ edition : str
369
+ Edition identifier (e.g., '2025c' or 'current').
370
+
371
+ Raises
372
+ ------
373
+ InvalidEditionError
374
+ If the `edition` argument has an invalid format or value.
375
+
376
+ EditionLoadError
377
+ If the edition could not be loaded. This could be due to a download error,
378
+ or an error while parsing the DICOM files.
379
+ """
380
+ valid_edition = self.get_edition(edition)
381
+ if valid_edition is None:
382
+ raise InvalidEditionError(f"Invalid DICOM edition {edition} - aborting")
383
+ destination = self.get_edition_path(valid_edition)
384
+ if destination is None:
385
+ raise EditionLoadError(
386
+ f"Failed to get DICOM edition {valid_edition} - aborting"
387
+ )
388
+ return self.load_dicom_info(valid_edition)
389
+
358
390
  def json_files_exist(self, edition: str) -> bool:
359
391
  """Check if all expected JSON files exist for the given edition.
360
392
 
@@ -1,20 +1,18 @@
1
- import re
1
+ from __future__ import annotations
2
2
 
3
+ import re
3
4
  from collections.abc import Callable
4
- from typing import Optional
5
5
 
6
- from pydicom.valuerep import VR, INT_VR, STR_VR
6
+ from pydicom.valuerep import INT_VR, STR_VR, VR
7
7
 
8
8
  from dicom_validator.spec_reader.condition_parser import ConditionParser
9
9
 
10
10
  try:
11
11
  import lxml.etree as ElementTree
12
12
  except ImportError:
13
- import xml.etree.ElementTree as ElementTree
14
-
15
- from dicom_validator.spec_reader.condition import ValuesType, ConditionType, Condition
13
+ from xml.etree import ElementTree
16
14
 
17
- OptionalElement = Optional[ElementTree.Element]
15
+ from dicom_validator.spec_reader.condition import Condition, ConditionType, ValuesType
18
16
 
19
17
 
20
18
  class EnumParser:
@@ -31,7 +29,7 @@ class EnumParser:
31
29
 
32
30
  def __init__(
33
31
  self,
34
- find_section: Callable[[str], OptionalElement],
32
+ find_section: Callable[[str], ElementTree.Element | None],
35
33
  condition_parser: ConditionParser,
36
34
  ) -> None:
37
35
  self._find_section = find_section
@@ -45,9 +43,8 @@ class EnumParser:
45
43
  var_lists = node.findall(self.docbook_ns + "variablelist")
46
44
  enum_lists = [self.parse_variable_list(e) for e in var_lists]
47
45
  enum_lists = [e for e in enum_lists if e]
48
- if not enum_lists:
49
- if linked_enums := self.parse_linked_variablelists(node):
50
- enum_lists.extend(linked_enums)
46
+ if not enum_lists and (linked_enums := self.parse_linked_variablelists(node)):
47
+ enum_lists.extend(linked_enums)
51
48
 
52
49
  if enum_lists:
53
50
  if vr == VR.AT:
@@ -6,21 +6,20 @@ The information is taken from PS3.3 in docbook format as provided by ACR NEMA.
6
6
 
7
7
  import copy
8
8
  import logging
9
- from itertools import groupby
10
-
11
9
  import sys
10
+ from itertools import groupby
12
11
 
13
12
  from dicom_validator.spec_reader.condition import (
14
13
  Condition,
15
- ConditionType,
16
14
  ConditionOperator,
15
+ ConditionType,
17
16
  )
18
17
  from dicom_validator.spec_reader.condition_parser import ConditionParser
19
18
  from dicom_validator.spec_reader.enum_parser import EnumParser
20
19
  from dicom_validator.spec_reader.spec_reader import (
21
20
  SpecReader,
22
- SpecReaderParseError,
23
21
  SpecReaderLookupError,
22
+ SpecReaderParseError,
24
23
  )
25
24
 
26
25
  # Some conditions from the spec are hard to parse with a few general rules.
@@ -421,9 +420,7 @@ class Part3Reader(SpecReader):
421
420
  title_node = self._find(sections_node, ["title"])
422
421
  if title_node is not None:
423
422
  title = title_node.text
424
- if any(
425
- [title.endswith(title_ending) for title_ending in title_endings]
426
- ):
423
+ if any(title.endswith(title_ending) for title_ending in title_endings):
427
424
  found_nodes.append(sections_node)
428
425
  if depth > 0:
429
426
  found_nodes.extend(
@@ -3,16 +3,14 @@ SpecReader reads information from DICOM standard files in docbook format as
3
3
  provided by ACR-NEMA.
4
4
  """
5
5
 
6
- from typing import Optional
6
+ from __future__ import annotations
7
7
 
8
8
  try:
9
9
  import lxml.etree as ElementTree
10
10
  except ImportError:
11
- import xml.etree.ElementTree as ElementTree
11
+ from xml.etree import ElementTree
12
12
  from pathlib import Path
13
13
 
14
- OptionalElement = Optional[ElementTree.Element]
15
-
16
14
 
17
15
  class SpecReaderError(Exception):
18
16
  pass
@@ -65,14 +63,16 @@ class SpecReader:
65
63
  )
66
64
  return self._doc_trees.get(self.part_nr)
67
65
 
68
- def get_doc_root(self) -> OptionalElement:
66
+ def get_doc_root(self) -> ElementTree.Element | None:
69
67
  """Return the XML root element of the current part, or `None` if unavailable."""
70
68
  doc_tree = self._get_doc_tree()
71
69
  if doc_tree:
72
70
  return doc_tree.getroot()
73
71
  return None
74
72
 
75
- def _find(self, node: ElementTree.Element, elements: list[str]) -> OptionalElement:
73
+ def _find(
74
+ self, node: ElementTree.Element, elements: list[str]
75
+ ) -> ElementTree.Element | None:
76
76
  search_string = "/".join([self.docbook_ns + element for element in elements])
77
77
  if node is not None:
78
78
  return node.find(search_string)
@@ -1,6 +1,6 @@
1
1
  import pytest
2
2
 
3
- from dicom_validator.spec_reader.condition import ConditionType, ConditionOperator
3
+ from dicom_validator.spec_reader.condition import ConditionOperator, ConditionType
4
4
  from dicom_validator.spec_reader.condition_parser import ConditionParser
5
5
 
6
6
 
@@ -265,7 +265,7 @@ class TestValueConditionParser:
265
265
  )
266
266
  assert result.type == ConditionType.MandatoryOrNotAllowed
267
267
  assert result.tag == "(0008,0008)"
268
- assert result.index == 2
268
+ assert result.index == 3
269
269
  assert result.operator == ConditionOperator.EqualsValue
270
270
  assert result.values == ["GATED", "GATED TOMO", "RECON GATED TOMO"]
271
271
 
@@ -285,7 +285,7 @@ class TestValueConditionParser:
285
285
  )
286
286
  assert result.type == ConditionType.MandatoryOrUserDefined
287
287
  assert result.tag == "(0054,1000)"
288
- assert result.index == 1
288
+ assert result.index == 2
289
289
  assert result.operator == ConditionOperator.EqualsValue
290
290
  assert result.values == ["REPROJECTION"]
291
291
 
@@ -296,7 +296,7 @@ class TestValueConditionParser:
296
296
  )
297
297
  assert result.type == ConditionType.MandatoryOrUserDefined
298
298
  assert result.tag == "(0008,0008)"
299
- assert result.index == 0
299
+ assert result.index == 1
300
300
  assert result.operator == ConditionOperator.EqualsValue
301
301
  assert result.values == ["ORIGINAL"]
302
302
 
@@ -371,7 +371,7 @@ class TestValueConditionParser:
371
371
  assert result.type == ConditionType.MandatoryOrUserDefined
372
372
  assert result.tag == "(0008,0008)"
373
373
  assert result.operator == ConditionOperator.EqualsValue
374
- assert result.index == 2
374
+ assert result.index == 3
375
375
  assert result.values == ["WHOLE BODY", "STATIC"]
376
376
 
377
377
  def test_is_with_one_letter_values(self, parser):
@@ -696,7 +696,7 @@ class TestValueConditionParser:
696
696
  )
697
697
  assert result.type == ConditionType.MandatoryOrUserDefined
698
698
  assert result.tag == "(0008,0008)"
699
- assert result.index == 0
699
+ assert result.index == 1
700
700
  assert result.operator == ConditionOperator.EqualsValue
701
701
  assert result.values == ["DERIVED"]
702
702
 
@@ -761,7 +761,7 @@ class TestValueConditionParser:
761
761
  assert result.operator == ConditionOperator.EqualsValue
762
762
  assert result.tag == "(0008,0008)"
763
763
  assert result.values == ["FLUENCE"]
764
- assert result.index == 2
764
+ assert result.index == 3
765
765
 
766
766
  def test_third_value(self, parser):
767
767
  result = parser.parse(
@@ -783,7 +783,7 @@ class TestValueConditionParser:
783
783
  assert result.operator == ConditionOperator.EqualsValue
784
784
  assert result.tag == "(0008,0008)"
785
785
  assert result.values == ["SIMULATOR", "PORTAL"]
786
- assert result.index == 2
786
+ assert result.index == 3
787
787
 
788
788
  def test_is_not_and_not(self, parser):
789
789
  result = parser.parse(
@@ -1093,13 +1093,13 @@ class TestCompositeConditionParser:
1093
1093
  assert len(result.or_conditions) == 2
1094
1094
  assert result.or_conditions[0].operator == ConditionOperator.EqualsValue
1095
1095
  assert result.or_conditions[0].tag == "(0008,0008)"
1096
- assert result.or_conditions[0].index == 0
1096
+ assert result.or_conditions[0].index == 1
1097
1097
  assert result.or_conditions[0].values == ["DERIVED"]
1098
1098
  and_conditions = result.or_conditions[1].and_conditions
1099
1099
  assert len(and_conditions) == 2
1100
1100
  assert and_conditions[0].operator == ConditionOperator.EqualsValue
1101
1101
  assert and_conditions[0].tag == "(0008,0008)"
1102
- assert and_conditions[0].index == 0
1102
+ assert and_conditions[0].index == 1
1103
1103
  assert and_conditions[0].values == ["ORIGINAL"]
1104
1104
  assert and_conditions[1].operator == ConditionOperator.EqualsValue
1105
1105
  assert and_conditions[1].tag == "(0008,0068)"
@@ -1140,11 +1140,11 @@ class TestCompositeConditionParser:
1140
1140
  assert len(result.and_conditions) == 2
1141
1141
  assert result.and_conditions[0].tag == "(0008,0008)"
1142
1142
  assert result.and_conditions[0].operator == ConditionOperator.EqualsValue
1143
- assert result.and_conditions[0].index == 3
1143
+ assert result.and_conditions[0].index == 4
1144
1144
  assert result.and_conditions[0].values == ["TRANSMISSION"]
1145
1145
  assert result.and_conditions[1].tag == "(0008,0008)"
1146
1146
  assert result.and_conditions[1].operator == ConditionOperator.NotEqualsValue
1147
- assert result.and_conditions[1].index == 2
1147
+ assert result.and_conditions[1].index == 3
1148
1148
  assert result.and_conditions[1].values == [
1149
1149
  "TOMO",
1150
1150
  "GATED TOMO",
@@ -1,16 +1,19 @@
1
1
  import os
2
2
  import time
3
+ from collections.abc import Generator
3
4
  from pathlib import Path
4
5
  from typing import Any
5
-
6
- from collections.abc import Generator
7
6
  from unittest.mock import patch
8
7
  from xml.etree import ElementTree
9
8
 
10
9
  import pytest
11
10
 
12
11
  from dicom_validator import __version__
13
- from dicom_validator.spec_reader.edition_reader import EditionReader
12
+ from dicom_validator.spec_reader.edition_reader import (
13
+ EditionLoadError,
14
+ EditionReader,
15
+ InvalidEditionError,
16
+ )
14
17
  from dicom_validator.tests.validator.conftest import CURRENT_EDITION
15
18
 
16
19
  pytestmark = pytest.mark.usefixtures("fs")
@@ -278,7 +281,7 @@ def test_get_non_existing_edition(
278
281
  def test_failing_download(retrieve_mock, fs, base_path, edition_path, caplog):
279
282
  reader = MemoryEditionReader(base_path, "")
280
283
  fs.create_file(edition_path, contents='["2014a", "2014c", "2015a"]')
281
- retrieve_mock.side_effect = BaseException
284
+ retrieve_mock.side_effect = OSError
282
285
  assert reader.get_edition_path("2014c") is None
283
286
  assert "Failed to download" in caplog.text
284
287
 
@@ -300,7 +303,56 @@ def test_partial_download(retrieve_mock, fs, base_path, edition_path):
300
303
 
301
304
  @patch("dicom_validator.spec_reader.edition_reader.urlretrieve")
302
305
  def test_failing_retrieval(retrieve_mock, base_path, edition_path, caplog):
303
- retrieve_mock.side_effect = AttributeError
306
+ retrieve_mock.side_effect = OSError
304
307
  reader = EditionReader(base_path)
305
308
  assert reader.get_editions() is None
306
309
  assert "Failed to get DICOM editions" in caplog.text
310
+
311
+
312
+ def test_dicom_info_for_edition_invalid_edition(base_path):
313
+ reader = MemoryEditionReader(base_path, "")
314
+ with pytest.raises(InvalidEditionError):
315
+ reader.dicom_info_for_edition("invalid")
316
+
317
+
318
+ @patch("dicom_validator.spec_reader.edition_reader.urlretrieve")
319
+ def test_dicom_info_for_edition_failing_download(
320
+ retrieve_mock, fs, base_path, edition_path
321
+ ):
322
+ reader = MemoryEditionReader(base_path, "")
323
+ fs.create_file(edition_path, contents='["2014a", "2014c", "2015a"]')
324
+ retrieve_mock.side_effect = AttributeError
325
+ with pytest.raises(EditionLoadError):
326
+ reader.dicom_info_for_edition("2014c")
327
+
328
+
329
+ def test_dicom_info_for_existing_edition(fs, fixture_path, standard_path, edition_path):
330
+ root_dir = fs.add_real_directory(standard_path).path
331
+ reader = EditionReader(root_dir)
332
+ dicom_info = reader.dicom_info_for_edition("2015b")
333
+ assert dicom_info.dictionary
334
+ assert dicom_info.iods
335
+ assert dicom_info.modules
336
+
337
+
338
+ @patch("dicom_validator.spec_reader.edition_reader.urlretrieve")
339
+ @patch("dicom_validator.spec_reader.spec_reader.ElementTree", ElementTree)
340
+ def test_dicom_info_for_edition_download_edition(
341
+ retrieve_mock, fs, fixture_path, standard_path, edition_path
342
+ ):
343
+ def retrieve(url, path):
344
+ source = str(path).replace("2014c", "dummy").replace("standard" + os.sep, "")
345
+ fs.add_real_file(source, target_path=path)
346
+
347
+ root_dir = fs.add_real_directory(standard_path).path
348
+ fs.add_real_directory(fixture_path / "dummy", target_path=standard_path / "dummy")
349
+ root_path = Path(root_dir)
350
+ reader = EditionReader(root_path)
351
+ retrieve_mock.side_effect = lambda url, path: retrieve(url, path)
352
+ json_path = root_path / "2014c" / "json"
353
+ assert not json_path.exists()
354
+ dicom_info = reader.dicom_info_for_edition("2014c")
355
+ assert json_path.exists()
356
+ assert dicom_info.dictionary
357
+ assert dicom_info.iods
358
+ assert dicom_info.modules
@@ -4,12 +4,12 @@ from xml.etree import ElementTree
4
4
 
5
5
  import pytest
6
6
 
7
- from dicom_validator.spec_reader.condition import ConditionType, ConditionOperator
7
+ from dicom_validator.spec_reader.condition import ConditionOperator, ConditionType
8
8
  from dicom_validator.spec_reader.part3_reader import Part3Reader
9
9
  from dicom_validator.spec_reader.spec_reader import (
10
+ SpecReaderFileError,
10
11
  SpecReaderLookupError,
11
12
  SpecReaderParseError,
12
- SpecReaderFileError,
13
13
  )
14
14
 
15
15
 
@@ -229,7 +229,7 @@ class TestReadPart3:
229
229
  # Include Table C.18.1-1 “Numeric Measurement Macro Attributes”
230
230
  # if and only if Value Type (0040,A040) is NUM.
231
231
  assert "C.18.1-1" in [d["ref"] for d in description["include"]]
232
- include = [d for d in description["include"] if d["ref"] == "C.18.1-1"][0]
232
+ include = next(d for d in description["include"] if d["ref"] == "C.18.1-1")
233
233
  condition = include["cond"]
234
234
  assert condition.type == ConditionType.MandatoryOrNotAllowed
235
235
  assert condition.operator == ConditionOperator.EqualsValue