Ejemplo n.º 1
0
def test_bestrelpath() -> None:
    curdir = Path("/foo/bar/baz/path")
    assert bestrelpath(curdir, curdir) == "."
    assert bestrelpath(curdir, curdir / "hello" /
                       "world") == "hello" + os.sep + "world"
    assert bestrelpath(curdir,
                       curdir.parent / "sister") == ".." + os.sep + "sister"
    assert bestrelpath(curdir, curdir.parent) == ".."
    assert bestrelpath(curdir, Path("hello")) == "hello"
Ejemplo n.º 2
0
def _folded_skips(
    startpath: Path, skipped: Sequence[CollectReport],
) -> List[Tuple[int, str, Optional[int], str]]:
    d: Dict[Tuple[str, Optional[int], str], List[CollectReport]] = {}
    for event in skipped:
        assert event.longrepr is not None
        assert isinstance(event.longrepr, tuple), (event, event.longrepr)
        assert len(event.longrepr) == 3, (event, event.longrepr)
        fspath, lineno, reason = event.longrepr
        # For consistency, report all fspaths in relative form.
        fspath = bestrelpath(startpath, Path(fspath))
        keywords = getattr(event, "keywords", {})
        # Folding reports with global pytestmark variable.
        # This is a workaround, because for now we cannot identify the scope of a skip marker
        # TODO: Revisit after marks scope would be fixed.
        if (
            event.when == "setup"
            and "skip" in keywords
            and "pytestmark" not in keywords
        ):
            key: Tuple[str, Optional[int], str] = (fspath, None, reason)
        else:
            key = (fspath, lineno, reason)
        d.setdefault(key, []).append(event)
    values: List[Tuple[int, str, Optional[int], str]] = []
    for key, events in d.items():
        values.append((len(events), *key))
    return values
Ejemplo n.º 3
0
    def test_toterminal_long_filenames(
        self, importasmod, tw_mock, monkeypatch: MonkeyPatch
    ) -> None:
        mod = importasmod(
            """
            def f():
                raise ValueError()
        """
        )
        excinfo = pytest.raises(ValueError, mod.f)
        path = Path(mod.__file__)
        monkeypatch.chdir(path.parent)
        repr = excinfo.getrepr(abspath=False)
        repr.toterminal(tw_mock)
        x = bestrelpath(Path.cwd(), path)
        if len(x) < len(str(path)):
            msg = tw_mock.get_write_msg(-2)
            assert msg == "mod.py"
            assert tw_mock.lines[-1] == ":3: ValueError"

        repr = excinfo.getrepr(abspath=True)
        repr.toterminal(tw_mock)
        msg = tw_mock.get_write_msg(-2)
        assert msg == str(path)
        line = tw_mock.lines[-1]
        assert line == ":3: ValueError"
Ejemplo n.º 4
0
    def pytest_report_header(self, config: Config) -> List[str]:
        line = "rootdir: %s" % config.rootpath

        if config.inipath:
            line += ", configfile: " + bestrelpath(config.rootpath, config.inipath)

        testpaths = config.getini("testpaths")
        if testpaths and config.args == testpaths:
            rel_paths = [bestrelpath(config.rootpath, x) for x in testpaths]
            line += ", testpaths: {}".format(", ".join(rel_paths))
        result = [line]

        plugininfo = config.pluginmanager.list_plugin_distinfo()
        if plugininfo:
            result.append("plugins: %s" % ", ".join(_plugin_nameversions(plugininfo)))
        return result
Ejemplo n.º 5
0
 def _makepath(self, path: Union[Path, str]) -> str:
     if not self.abspath and isinstance(path, Path):
         try:
             np = bestrelpath(Path.cwd(), path)
         except OSError:
             return str(path)
         if len(np) < len(str(path)):
             return np
     return str(path)
Ejemplo n.º 6
0
 def get_location(self, config: Config) -> Optional[str]:
     """Return the more user-friendly information about the location of a warning, or None."""
     if self.nodeid:
         return self.nodeid
     if self.fslocation:
         filename, linenum = self.fslocation
         relpath = bestrelpath(config.invocation_params.dir, absolutepath(filename))
         return f"{relpath}:{linenum}"
     return None
Ejemplo n.º 7
0
 def write_fspath_result(self, nodeid: str, res, **markup: bool) -> None:
     fspath = self.config.rootpath / nodeid.split("::")[0]
     if self.currentfspath is None or fspath != self.currentfspath:
         if self.currentfspath is not None and self._show_progress_info:
             self._write_progress_information_filling_space()
         self.currentfspath = fspath
         relfspath = bestrelpath(self.startpath, fspath)
         self._tw.line()
         self._tw.write(relfspath + " ")
     self._tw.write(res, flush=True, **markup)
Ejemplo n.º 8
0
 def get_location(self, config: Config) -> Optional[str]:
     """Return the more user-friendly information about the location of a warning, or None."""
     if self.nodeid:
         return self.nodeid
     if self.fslocation:
         if isinstance(self.fslocation, tuple) and len(self.fslocation) >= 2:
             filename, linenum = self.fslocation[:2]
             relpath = bestrelpath(
                 config.invocation_params.dir, absolutepath(filename)
             )
             return "{}:{}".format(relpath, linenum)
         else:
             return str(self.fslocation)
     return None
Ejemplo n.º 9
0
    def _locationline(self, nodeid, fspath, lineno, domain):
        def mkrel(nodeid):
            line = self.config.cwd_relative_nodeid(nodeid)
            if domain and line.endswith(domain):
                line = line[: -len(domain)]
                values = domain.split("[")
                values[0] = values[0].replace(".", "::")  # don't replace '.' in params
                line += "[".join(values)
            return line

        # collect_fspath comes from testid which has a "/"-normalized path.

        if fspath:
            res = mkrel(nodeid)
            if self.verbosity >= 2 and nodeid.split("::")[0] != fspath.replace(
                "\\", nodes.SEP
            ):
                res += " <- " + bestrelpath(self.startpath, fspath)
        else:
            res = "[location]"
        return res + " "
Ejemplo n.º 10
0
 def __missing__(self, path: Path) -> str:
     r = bestrelpath(self.path, path)
     self[path] = r
     return r