• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

fiduswriter / fiduswriter / 20682683558

03 Jan 2026 08:43PM UTC coverage: 87.221% (-0.09%) from 87.306%
20682683558

push

github

web-flow
Merge pull request #1364 from fiduswriter/feature/debian

Add initial deb packaging instructions, relates to #1249

7064 of 8099 relevant lines covered (87.22%)

4.97 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.8
fiduswriter/testing/selenium_helper.py
1
import re
15✔
2
import os
15✔
3
import time
15✔
4
from urllib3.exceptions import MaxRetryError
15✔
5
from selenium.common.exceptions import ElementClickInterceptedException
15✔
6
from selenium.webdriver.support.wait import WebDriverWait
15✔
7
from selenium.webdriver.support import expected_conditions as EC
15✔
8
from selenium.webdriver.common.by import By
15✔
9
from selenium import webdriver
15✔
10
from selenium.webdriver.chrome.service import Service as ChromiumService
15✔
11
from webdriver_manager.chrome import ChromeDriverManager
15✔
12
from webdriver_manager.core.os_manager import ChromeType
15✔
13

14
from allauth.account.models import EmailAddress
15✔
15
from django.contrib.auth.hashers import make_password
15✔
16
from django.contrib.auth import get_user_model
15✔
17
from django.conf import settings
15✔
18
from django.test import Client
15✔
19
from django.contrib.contenttypes.models import ContentType
15✔
20
import logging
15✔
21

22
logger = logging.getLogger(__name__)
15✔
23

24

25
class SeleniumHelper:
15✔
26
    """
27
    Methods for manipulating django and the browser for testing purposes.
28
    """
29

30
    login_page = "/"
15✔
31

32
    def find_urls(self, string):
15✔
33
        return re.findall(
2✔
34
            (
35
                "http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|"
36
                "(?:%[0-9a-fA-F][0-9a-fA-F]))+"
37
            ),
38
            string,
39
        )
40

41
    # create django data
42
    def create_user(
15✔
43
        self, username="User", email="test@example.com", passtext="p4ssw0rd"
44
    ):
45
        User = get_user_model()
14✔
46
        user = User.objects.create(
14✔
47
            username=username,
48
            email=email,
49
            password=make_password(passtext),
50
            is_active=True,
51
        )
52
        user.save()
14✔
53

54
        # avoid the unverified-email login trap
55
        EmailAddress.objects.create(
14✔
56
            user=user, email=email, verified=True, primary=True
57
        ).save()
58

59
        return user
14✔
60

61
    # drive browser
62
    def login_user(self, user, driver, client):
15✔
63
        client.force_login(user=user)
9✔
64
        cookie = client.cookies[settings.SESSION_COOKIE_NAME]
9✔
65
        # output the cookie to the console for debugging
66
        logger.debug("cookie: %s" % cookie.value)
9✔
67
        if driver.current_url == "data:,":
9✔
68
            # To set the cookie at the right domain we load the front page.
69
            driver.get(f"{self.live_server_url}{self.login_page}")
9✔
70
            WebDriverWait(driver, self.wait_time).until(
9✔
71
                EC.presence_of_element_located((By.ID, "id-login"))
72
            )
73
        driver.add_cookie(
9✔
74
            {
75
                "name": settings.SESSION_COOKIE_NAME,
76
                "value": cookie.value,
77
                "secure": False,
78
                "path": "/",
79
            }
80
        )
81

82
    def login_user_manually(self, user, driver, passtext="p4ssw0rd"):
15✔
83
        username = user.username
×
84
        driver.delete_cookie(settings.SESSION_COOKIE_NAME)
×
85
        driver.get("{}{}".format(self.live_server_url, "/"))
×
86
        driver.find_element(By.ID, "id-login").send_keys(username)
×
87
        driver.find_element(By.ID, "id-password").send_keys(passtext)
×
88
        driver.find_element(By.ID, "login-submit").click()
×
89
        # Wait until there is an element with the ID user-preferences
90
        # which is only present on the dashboard.
91
        WebDriverWait(driver, self.wait_time).until(
×
92
            EC.presence_of_element_located((By.ID, "user-preferences"))
93
        )
94

95
    def logout_user(self, driver, client):
15✔
96
        client.logout()
×
97
        driver.delete_cookie(settings.SESSION_COOKIE_NAME)
×
98

99
    def wait_until_file_exists(self, path, wait_time):
15✔
100
        count = 0
4✔
101
        while not os.path.exists(path):
4✔
102
            time.sleep(1)
4✔
103
            count += 1
4✔
104
            if count > wait_time:
4✔
105
                break
×
106

107
    def retry_click(self, driver, selector, retries=5):
15✔
108
        count = 0
1✔
109
        while count < retries:
1✔
110
            try:
1✔
111
                WebDriverWait(driver, self.wait_time).until(
1✔
112
                    EC.element_to_be_clickable(selector)
113
                ).click()
114
                break
1✔
115
            except ElementClickInterceptedException:
1✔
116
                count += 1
1✔
117
                time.sleep(1)
1✔
118

119
    @classmethod
15✔
120
    def get_drivers(cls, number, download_dir=False, user_agent=False):
15✔
121
        # django native clients, to be used for faster login.
122
        clients = []
15✔
123
        for i in range(number):
15✔
124
            clients.append(Client())
15✔
125
        drivers = []
15✔
126
        wait_time = 0
15✔
127
        options = webdriver.ChromeOptions()
15✔
128
        options.add_argument("--kiosk-printing")
15✔
129
        options.add_argument("--safebrowsing-disable-download-protection")
15✔
130
        options.add_argument("--safebrowsing-disable-extension-blacklist")
15✔
131
        prefs = {
15✔
132
            "profile.password_manager_leak_detection": False,
133
        }
134
        if download_dir:
15✔
135
            prefs["download.default_directory"] = download_dir
5✔
136
            prefs["download.prompt_for_download"] = False
5✔
137
            prefs["download.directory_upgrade"] = True
5✔
138
        options.add_experimental_option("prefs", prefs)
15✔
139
        if user_agent:
15✔
140
            options.add_argument(f"user-agent={user_agent}")
1✔
141
        if os.getenv("CI"):
15✔
142
            options.binary_location = "/usr/bin/google-chrome-stable"
15✔
143
            if os.getenv("DEBUG_MODE") != "1":
15✔
144
                options.add_argument("--headless=new")
15✔
145
            options.add_argument("--disable-gpu")
15✔
146
            wait_time = 20
15✔
147
        else:
148
            wait_time = 6
×
149
        for i in range(number):
15✔
150
            driver_env = os.environ.copy()
15✔
151
            if os.getenv("CI") and os.getenv("DEBUG_MODE") == "1" and i < 2:
15✔
152
                driver_env["DISPLAY"] = f":{99 - i}"
×
153
            driver = webdriver.Chrome(
15✔
154
                service=ChromiumService(
155
                    ChromeDriverManager(
156
                        chrome_type=ChromeType.GOOGLE
157
                    ).install(),
158
                    env=driver_env,
159
                ),
160
                options=options,
161
            )
162
            # Set sizes of browsers so that all buttons are visible.
163
            driver.set_window_position(0, 0)
15✔
164
            driver.set_window_size(1920, 1080)
15✔
165
            drivers.append(driver)
15✔
166
        cls.drivers = drivers
15✔
167
        return {"clients": clients, "drivers": drivers, "wait_time": wait_time}
15✔
168

169
    def setUp(self):
15✔
170
        # Clear ContentType cache during testing to prevent FK constraint errors
171
        # Content types get new IDs after each test but cached values don't update
172
        ContentType.objects.clear_cache()
8✔
173
        self.addCleanup(ContentType.objects.clear_cache)
8✔
174
        return super().setUp()
8✔
175

176
    def tearDown(self):
15✔
177
        # Source: https://stackoverflow.com/a/39606065
178
        result = self._outcome.result
15✔
179
        ok = all(
15✔
180
            test != self for test, text in result.errors + result.failures
181
        )
182
        if ok:
15✔
183
            for driver in self.drivers:
15✔
184
                self.leave_site(driver)
15✔
185
        else:
186
            if not os.path.exists("screenshots"):
×
187
                os.makedirs("screenshots")
×
188
            for id, driver in enumerate(self.drivers, start=1):
×
189
                screenshotfile = (
×
190
                    f"screenshots/driver{id}-{self._testMethodName}.png"
191
                )
192
                logger.info(f"Saving {screenshotfile}")
×
193
                driver.save_screenshot(screenshotfile)
×
194
                self.leave_site(driver)
×
195
        return super().tearDown()
15✔
196

197
    def leave_site(self, driver):
15✔
198
        try:
15✔
199
            driver.execute_script(
15✔
200
                "if (window.theApp) {window.theApp.page = null;}"
201
            )
202
            driver.get("data:,")
15✔
203
        except MaxRetryError:
1✔
204
            pass
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc