~aleteoryx/muditaos

ref: 03379186f9d094b1fc29bbc19be0e742ccbbd314 muditaos/test/pytest/conftest.py -rw-r--r-- 8.1 KiB
03379186 — Bartosz [MOS-000] Fixed tests for update 3 years ago
                                                                                
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# Copyright (c) 2017-2022, Mudita Sp. z.o.o. All rights reserved.
# For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

import time

import pytest

import sys
import os.path

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))

from harness import log
from harness.harness import Harness
from harness import utils
from harness.interface.error import TestError, Error
from harness.interface.CDCSerial import Keytype, CDCSerial as serial
from harness.api.security import SetPhoneLockOff, GetPhoneLockStatus
from harness.interface.defs import key_codes


simulator_port = 'simulator'

def pytest_addoption(parser):
    parser.addoption("--port", type=str, action="store", required=False)
    parser.addoption("--timeout", type=int, action="store", default=15)
    parser.addoption("--phone_number", type=int, action="store")
    parser.addoption("--call_duration", type=int, action="store", default=30)
    parser.addoption("--sms_text", type=str, action="store", default='')
    parser.addoption("--bt_device", type=str, action="store", default='')
    parser.addoption("--passcode", type=str, action="store", default='')
    parser.addoption("--update_file_path", type=str, action="store", default='')


@pytest.fixture(scope='session')
def phone_number(request):
    phone_number = request.config.option.phone_number
    assert phone_number
    return phone_number

@pytest.fixture(scope='session')
def passcode(request):
    passcode = request.config.option.passcode
    assert passcode
    return passcode
@pytest.fixture(scope='session')
def update_file_path(request):
    update_file_path = request.config.option.update_file_path
    assert update_file_path
    return update_file_path


@pytest.fixture(scope='session')
def call_duration(request):
    call_duration = request.config.option.call_duration
    assert call_duration
    return call_duration


@pytest.fixture(scope='session')
def sms_text(request):
    sms_text = request.config.option.sms_text
    assert sms_text != ''
    return sms_text

@pytest.fixture(scope='session')
def bt_device(request):
    bt_device = request.config.option.bt_device
    return bt_device

@pytest.fixture(scope='session')
def harness(request):
    '''
    Try to init one Pure phone with serial port path or automatically
    '''
    port_name = request.config.option.port
    TIMEOUT = request.config.option.timeout

    timeout_started = time.time()

    RETRY_EVERY_SECONDS = 1.0
    try:
        if port_name is None:
            log.warning("no port provided! trying automatic detection")
            harness = None

            with utils.Timeout.limit(seconds=TIMEOUT):
                while not harness:
                    try:
                        harness = Harness.from_detect()
                    except TestError as e:
                        if e.get_error_code() == Error.PORT_NOT_FOUND:
                            log.info(f"waiting for a serial port… ({TIMEOUT- int(time.time() - timeout_started)})")
                            time.sleep(RETRY_EVERY_SECONDS)
        else:
            assert '/dev' in port_name or simulator_port in port_name

            if simulator_port in port_name:
                file = None
                with utils.Timeout.limit(seconds=TIMEOUT):
                    while not file:
                        try:
                            file = open("/tmp/purephone_pts_name", "r")
                        except FileNotFoundError as err:
                            log.info(
                                f"waiting for a simulator port… ({TIMEOUT- int(time.time() - timeout_started)})")
                            time.sleep(RETRY_EVERY_SECONDS)
                port_name = file.readline()
                if port_name.isascii():
                    log.debug("found {} entry!".format(port_name))
                else:
                    pytest.exit("not a valid sim pts entry!")

            harness = Harness(port_name)

            '''
            Wait for endpoints to initialize
            '''
            testbody = {"ui": True, "getWindow": True}
            result = None
            with utils.Timeout.limit(seconds=305):
                while not result:
                    try:
                        result = harness.endpoint_request("developerMode", "get", testbody)
                    except ValueError:
                        log.info("Endpoints not ready..")

    except utils.Timeout:
        pytest.exit("couldn't find any viable port. exiting")
    else:
        return harness

@pytest.fixture(scope='session')
def harnesses():
    '''
    Automatically init at least two Pure phones
    '''
    connected_devices = serial.find_Devices()
    harnesses = [Harness(device) for device in connected_devices]
    if not len(harnesses) >= 2:
        pytest.skip("At least two phones are needed for this test")
    assert len(harnesses) >= 2
    return harnesses

@pytest.fixture(scope='session')
def phone_unlocked(harness):
    harness.unlock_phone()
    assert not harness.is_phone_locked()

@pytest.fixture(scope='session')
def phone_locked(harness):
    harness.lock_phone()
    assert harness.is_phone_locked()

@pytest.fixture(scope='session')
def phones_unlocked(harnesses):
    for harness in harnesses:
        harness.unlock_phone()
        assert not harness.is_phone_locked()


@pytest.fixture(scope='session')
def phone_in_desktop(harness):
    # go to desktop
    if harness.get_application_name() != "ApplicationDesktop":
        harness.connection.send_key_code(key_codes["fnRight"], Keytype.long_press)
        # in some cases we have to do it twice
        if harness.get_application_name() != "ApplicationDesktop":
            harness.connection.send_key_code(key_codes["fnRight"], Keytype.long_press)
    # assert that we are in ApplicationDesktop
    assert harness.get_application_name() == "ApplicationDesktop"

@pytest.fixture(scope='function')
def phone_ends_test_in_desktop(harness):
    yield
    target_application = "ApplicationDesktop"
    target_window     = "MainWindow"
    log.info(f"returning to {target_window} of {target_application} ...")
    time.sleep(1)

    if harness.get_application_name() != target_application :
        body = {"switchApplication" : {"applicationName": target_application, "windowName" : target_window }}
        harness.endpoint_request("developerMode", "put", body)
        time.sleep(1)

        max_retry_counter = 5
        while harness.get_application_name() != target_application:
            max_retry_counter -= 1
            if max_retry_counter == 0:
                break

            log.info(f"Not in {target_application}, {max_retry_counter} attempts left...")
            time.sleep(1)
    else :
        # switching window in case ApplicationDesktop is not on MainWindow:
        body = {"switchWindow" : {"applicationName": target_application, "windowName" : target_window }}
        harness.endpoint_request("developerMode", "put", body)
        time.sleep(1)

    # assert that we are in ApplicationDesktop
    assert harness.get_application_name() == target_application
    time.sleep(1)

@pytest.fixture(scope='session')
def phone_security_unlocked(harness,passcode):
    for _ in range(2):
        try:
            GetPhoneLockStatus().run(harness)
        except TransactionError as e:
            log.info(f"transaction code: {e}")
            log.info("Phone security locked, unlocking")
            SetPhoneLockOff(passcode=passcode).run(harness)

def pytest_configure(config):
    config.addinivalue_line("markers",
                            "service_desktop_test: mark test if it's related to service-desktop API")
    config.addinivalue_line("markers",
                            "rt1051: mark test if it's target only (eg. calls, messages)")
    config.addinivalue_line("markers",
                            "usb_cdc_echo: mark test if it's intended for usb-cdc echo mode")
    config.addinivalue_line("markers",
                            "two_sim_cards: mark test in case when two sim cards are required")
    config.addinivalue_line("markers",
                            "backup: subset of backup user data tests")
    config.addinivalue_line("markers",
                            "restore: subset of restore user data tests")