Пример #1
0
 def _connect(self):
     """Get the SqliteDb object to use."""
     if get_thread_id() not in self._dbs:
         if os.path.exists(self._filename):
             self._open_db()
         else:
             self._create_db()
     return self._dbs[get_thread_id()]
Пример #2
0
 def current_context(cls):
     thread_id = get_thread_id()
     if thread_id in cls._context_stacks:
         stack = cls._context_stacks[thread_id]
         if stack:
             return stack[-1]
     return None
Пример #3
0
    def set_current(self) -> None:
        """Set this hook as the active hook in this thread

        This method is called by a layout before entering the render method
        of this hook's associated component.
        """
        _current_life_cycle_hook[get_thread_id()] = self
Пример #4
0
def current_hook() -> "LifeCycleHook":
    """Get the current :class:`LifeCycleHook`"""
    try:
        return _current_life_cycle_hook[get_thread_id()]
    except KeyError as error:
        msg = "No life cycle hook is active. Are you rendering in a layout?"
        raise RuntimeError(msg) from error
Пример #5
0
 def unregister(cls, context, *, thread_id=None):
     if thread_id is None:
         thread_id = get_thread_id()
     try:
         cls._context_stacks[thread_id].remove(context)
     except KeyError:
         # Sometimes, cleanup can fail due to a race condition
         # If it's gone, it's gone.  No need to raise an exception.
         pass
Пример #6
0
 def __nonzero__(self):
     if (get_thread_id() not in self._dbs and not os.path.exists(self._filename)):
         return False
     try:
         with self._connect() as con:
             rows = con.execute("select * from file limit 1")
             return bool(list(rows))
     except CoverageException:
         return False
Пример #7
0
    def _create_db(self):
        """Create a db file that doesn't exist yet.

        Initializes the schema and certain metadata.
        """
        self._dbs[get_thread_id()] = db = SqliteDb(self._filename)
        with db:
            db.executescript(SCHEMA)
            db.execute("insert into coverage_schema (version) values (?)",
                       (SCHEMA_VERSION,))
            db.executemany(
                "insert into meta (key, value) values (?, ?)",
                [
                    ('sys_argv', str(getattr(sys, 'argv', None))),
                    ('version', __version__),
                    ('when', datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')),
                ]
            )
Пример #8
0
    def loads(self, data):
        """Deserialize data from :meth:`dumps`

        Use with a newly-created empty :class:`CoverageData` object.  It's
        undefined what happens if the object already has data in it.

        Arguments:
            data: A byte string of serialized data produced by :meth:`dumps`.

        .. versionadded:: 5.0

        """
        if data[:1] != b'z':
            raise CoverageException(
                f"Unrecognized serialization: {data[:40]!r} (head of "
                f"{len(data)} bytes)")
        script = zlib.decompress(data[1:])
        self._dbs[get_thread_id()] = db = SqliteDb(self._filename)
        with db:
            db.executescript(script)
        self._read_db()
        self._have_used = True
Пример #9
0
    def _read_db(self):
        """Read the metadata from a database so that we are ready to use it."""
        with self._dbs[get_thread_id()] as db:
            try:
                schema_version, = db.execute_one(
                    "select version from coverage_schema")
            except Exception as exc:
                raise CoverageException(
                    f"Data file {self._filename!r} doesn't seem to be a coverage "
                    f"data file: {exc}")
            else:
                if schema_version != SCHEMA_VERSION:
                    raise CoverageException(
                        f"Couldn't use data file {self._filename!r}: wrong "
                        f"schema: {schema_version} instead of {SCHEMA_VERSION}")

            for row in db.execute("select value from meta where key = 'has_arcs'"):
                self._has_arcs = bool(int(row[0]))
                self._has_lines = not self._has_arcs

            for path, file_id in db.execute("select path, id from file"):
                self._file_map[path] = file_id
Пример #10
0
 def register(cls, context, *, thread_id=None):
     if thread_id is None:
         thread_id = get_thread_id()
     if thread_id not in cls._context_stacks:
         cls._context_stacks[thread_id] = []
     cls._context_stacks[thread_id].append(context)
Пример #11
0
 def unset_current(self) -> None:
     """Unset this hook as the active hook in this thread"""
     # this assertion should never fail - primarilly useful for debug
     assert _current_life_cycle_hook[get_thread_id()] is self
     del _current_life_cycle_hook[get_thread_id()]
Пример #12
0
 def unregister(cls, context, *, thread_id=None):
     if thread_id is None:
         thread_id = get_thread_id()
     cls._context_stacks[thread_id].remove(context)
Пример #13
0
 def _open_db(self):
     """Open an existing db file, and read its metadata."""
     self._dbs[get_thread_id()] = SqliteDb(self._filename)
     self._read_db()