File: testing.py

package info (click to toggle)
python-trame 3.12.0-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 101,620 kB
  • sloc: python: 13,515; sh: 183; javascript: 93; makefile: 7
file content (56 lines) | stat: -rw-r--r-- 1,677 bytes parent folder | download | duplicates (2)
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
52
53
54
55
56
import json
import os


class TrameServerMonitor:
    """Helper class capture sever state from log"""

    def __init__(self, log_path):
        self._log_path = log_path
        self._last_state = {}
        self.port = 0
        self.update()

    def update(self):
        last_state_line = "STATE: {}"
        with open(self._log_path, "r") as f:
            for line in f.readlines():
                print(line)
                if "SERVER_PORT:" in line:
                    self.port = int(line[13:])
                if line[:7] == "STATE: ":
                    last_state_line = line

        self._last_state = json.loads(last_state_line[7:])

    def get_state(self):
        self.update()
        return self._last_state

    def get(self, name):
        self.update()
        return self._last_state.get(name)


def remove_page_urls(base_path):
    """Selenium capture page_url.txt which will change through
    tests and therefore we need to remove them."""
    for root, dirs, files in os.walk(base_path):
        if "page_url.txt" in files:
            full_path = os.path.join(root, "page_url.txt")
            os.remove(full_path)
            print(f" - remove: {full_path}")


def print_state(**kwargs):
    """Helper to print the server state in a way TrameServerMonitor can understand"""
    print("STATE:", json.dumps(kwargs), flush=True)


def enable_testing(server, *state_monitor):
    """Register state monitoring for TrameServerMonitor and port extractor"""
    server.state.change(*state_monitor)(print_state)

    @server.controller.add("on_server_ready")
    def print_server_port(**kwargs):
        print("SERVER_PORT:", server.port, flush=True)