Пример #1
0
 def test_get_testdata_file_network_outage(self, download_failure):
     """Test a network outage when using get_testdata_file."""
     fname = "693_UNCI.dcm"
     msg = (r"A download failure occurred while attempting to "
            r"retrieve 693_UNCI.dcm")
     with pytest.warns(UserWarning, match=msg):
         assert get_testdata_file(fname) is None
Пример #2
0
 def test_get_testdata_file_no_download(self, recwarn):
     """
     Test that `data_path_with_download`
     is not called when `download=False`.
     """
     fname = "693_UNCI.dcm"
     assert get_testdata_file(fname, download=False) is None
     assert not recwarn.list
Пример #3
0
 def test_get_testdata_file_external_hash_match(self):
     """Test that external source is used when hash is OK."""
     fname = "693_UNCI.dcm"
     p = self.dpath / fname
     ext_hash = calculate_file_hash(p)
     ref_hash = get_cached_filehash(p.name)
     assert ext_hash == ref_hash
     fpath = self.as_posix(get_testdata_file(fname))
     assert "data_store/data" in fpath
Пример #4
0
    def test_get_testdata_file_external_hash_mismatch(self):
        """Test that the external source is not used when hash is not OK."""
        p = self.dpath / "693_UNCI.dcm"
        with open(p, 'wb') as f:
            f.write(b"\x00\x01")

        ext_hash = calculate_file_hash(p)
        ref_hash = get_cached_filehash(p.name)
        assert ext_hash != ref_hash
        fpath = self.as_posix(get_testdata_file(p.name))
        assert ".pydicom/data" in fpath
    def test_get_testdata_file_external_ignore_hash(self):
        """Test that non-pydicom-data external source ignores hash check."""
        EXTERNAL_DATA_SOURCES['mylib'] = EXTERNAL_DATA_SOURCES['pydicom-data']
        p = self.dpath / "693_UNCI.dcm"
        with open(p, 'wb') as f:
            f.write(b"\x00\x01")

        ext_hash = calculate_file_hash(p)
        ref_hash = get_cached_filehash(p.name)
        assert ext_hash != ref_hash
        fpath = self.as_posix(get_testdata_file(p.name))
        assert "data_store/data" in fpath
Пример #6
0
 def test_get_testdata_file(self):
     """Test that file name is working properly."""
     p = Path(get_testdata_file('DICOMDIR'))
     assert "DICOMDIR" == p.name.upper()
Пример #7
0
 def test_get_testdata_file_missing(self):
     """Test no such file available."""
     fname = "MY_MISSING_FILE.dcm"
     assert get_testdata_file(fname) is None
Пример #8
0
 def test_get_testdata_file_external(self):
     """Test that external data source preferred over cache."""
     fname = "693_UNCI.dcm"
     fpath = self.as_posix(get_testdata_file(fname))
     assert "data_store/data" in fpath
Пример #9
0
 def test_get_testdata_file_local(self):
     """Test that local data path retrieved OK."""
     fname = "CT_small.dcm"
     fpath = self.as_posix(get_testdata_file(fname))
     assert "pydicom/data/test_files" in fpath
Пример #10
0
def filespec_parser(filespec: str):
    """Utility to return a dataset and an optional data element value within it

    Note: this is used as an argparse 'type' for adding parsing arguments.

    Parameters
    ----------
    filespec: str
        A filename with optional `pydicom::` prefix and optional data element,
        in format:
            [pydicom::]<filename>[::<element>]
        If an element is specified, it must be a path to a data element,
        sequence item (dataset), or a sequence.
        Examples:
            your_file.dcm
            your_file.dcm::StudyDate
            pydicom::rtplan.dcm::BeamSequence[0]
            pydicom::rtplan.dcm::BeamSequence[0].BeamLimitingDeviceSequence

    Returns
    -------
    List[Tuple[Dataset, Any]]
        Matching pairs of (dataset, data element value)
        This usually is a single pair, but a list is returned for future
        ability to work across multiple files.

    Note
    ----
        This function is meant to be used in a call to an `argparse` libary's
        `add_argument` call for subparsers, with name="filespec" and
        `type=filespec_parser`. When used that way, the resulting args.filespec
        will contain the return values of this function
        (e.g. use `ds, element_val = args.filespec` after parsing arguments)
        See the `pydicom.cli.show` module for an example.

    Raises
    ------
    argparse.ArgumentTypeError
        If the filename does not exist in local path or in pydicom test files,
        or if the optional element is not a valid expression,
        or if the optional element is a valid expression but does not exist
        within the dataset
    """
    prefix, filename, element = filespec_parts(filespec)

    # Get the pydicom test filename even without prefix, in case user forgot it
    try:
        pydicom_filename = cast(str, get_testdata_file(filename))
    except NotImplementedError:  # will get this if absolute path passed
        pydicom_filename = ""

    if prefix == "pydicom":
        filename = pydicom_filename

    # Check element syntax first to avoid unnecessary load of file
    if element and not re_file_spec_object.match(element):
        raise argparse.ArgumentTypeError(
            f"Component '{element}' is not valid syntax for a "
            "data element, sequence, or sequence item")

    # Read DICOM file
    try:
        ds = dcmread(filename, force=True)
    except FileNotFoundError:
        extra = ((f", \nbut 'pydicom::{filename}' test data file is available")
                 if pydicom_filename else "")
        raise argparse.ArgumentTypeError(f"File '{filename}' not found{extra}")
    except Exception as e:
        raise argparse.ArgumentTypeError(
            f"Error reading '{filename}': {str(e)}")

    if not element:
        return [(ds, None)]

    data_elem_val = eval_element(ds, element)

    return [(ds, data_elem_val)]
 def test_get_testdata_file(self):
     """Test that file name is working properly."""
     name = 'DICOMDIR'
     filename = get_testdata_file(name)
     assert filename and filename.endswith('DICOMDIR')