File: execcontext.py

package info (click to toggle)
rss2email 1%3A3.14-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,260 kB
  • sloc: python: 2,565; xml: 156; sh: 6; makefile: 2
file content (51 lines) | stat: -rw-r--r-- 1,660 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import subprocess
import sys
import tempfile
from configparser import ConfigParser
from pathlib import Path
from typing import Dict, Any

# We run the r2e in the dir above this script, not the system-wide
# installed version, which you probably don't mean to test.
r2e_path = str(Path(__file__).absolute().parent.parent.parent.joinpath("r2e"))


class ExecContext:
    """Creates temporary config, data file and lets you call r2e with them
    easily. Cleans up temp files afterwards.

    Example:

    with ExecContext(config="[DEFAULT]\nto=me@example.com") as context:
        context.call("run", "--no-send")

    """

    def __init__(self, config: str):
        self._tmpdir = tempfile.TemporaryDirectory()
        self.cfg_path = Path(self._tmpdir.name, "rss2email.cfg")
        self.data_path = Path(self._tmpdir.name, "rss2email.json")
        self.opml_path = Path(self._tmpdir.name, "rss2email.opml")

        self.cfg_path.write_text(config)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._tmpdir.cleanup()

    def call(self, *args):
        return subprocess.run(
            [sys.executable, r2e_path, "-c", str(self.cfg_path), "-d", str(self.data_path)] + list(args),
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True)

    def change_config(self, params: Dict[str, Any]) -> None:
        config = ConfigParser()
        config.read(str(self.cfg_path))
        for name, value in params.items():
            config['DEFAULT'][name] = str(value)
        with self.cfg_path.open('w') as file:
            config.write(file)