-
Notifications
You must be signed in to change notification settings - Fork 437
/
Copy pathtest_logic.py
3542 lines (3070 loc) · 113 KB
/
test_logic.py
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Tests for the Editor and REPL logic.
"""
import sys
import os
import atexit
import codecs
import contextlib
import json
import locale
import random
import re
import shutil
import subprocess
import tempfile
from unittest import mock
import uuid
import pytest
import mu.config
import mu.logic
import mu.settings
from mu.virtual_environment import venv
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtCore import pyqtSignal, QObject, Qt
from mu import __version__
SESSION = json.dumps(
{
"theme": "night",
"mode": "python",
"paths": ["path/foo.py", "path/bar.py"],
"envars": [["name", "value"]],
}
)
ENCODING_COOKIE = "# -*- coding: {} -*-{}".format(
mu.logic.ENCODING, mu.logic.NEWLINE
)
#
# Testing support functions
# These functions generate testing scenarios or mocks making
# the test more readable and easier to spot the element being
# tested from among the boilerplate setup code
#
def rstring(length=10, characters="abcdefghijklmnopqrstuvwxyz"):
letters = list(characters)
random.shuffle(letters)
return "".join(letters[:length])
def _generate_python_files(contents, dirpath):
"""Generate a series of .py files, one for each element in an iterable
contents should be an iterable (typically a list) containing one
string for each of a the number of files to be created. The files
will be created in the dirpath directory passed in which will neither
be created nor destroyed by this function.
"""
for i, c in enumerate(contents):
name = uuid.uuid1().hex
filepath = os.path.join(dirpath, "%03d-%s.py" % (1 + i, name))
#
# Write using newline="" so line-ending tests can work!
# If a binary write is needed (eg for an encoding test) pass
# a list of empty strings as contents and then write the bytes
# as part of the test.
#
with open(filepath, "w", encoding=mu.logic.ENCODING, newline="") as f:
f.write(c)
yield filepath
@contextlib.contextmanager
def generate_python_files(contents, dirpath=None):
"""
Create a temp directory and populate it with .py files, then remove it.
"""
dirpath = dirpath or tempfile.mkdtemp(prefix="mu-")
yield list(_generate_python_files(contents, dirpath))
shutil.rmtree(dirpath)
@contextlib.contextmanager
def generate_python_file(text="", dirpath=None):
"""
Create a temp directory and populate it with on .py file, then remove it.
"""
dirpath = dirpath or tempfile.mkdtemp(prefix="mu-")
for filepath in _generate_python_files([text], dirpath):
yield filepath
break
shutil.rmtree(dirpath)
@contextlib.contextmanager
def generate_session(
theme="day",
mode="python",
file_contents=None,
envars=[["name", "value"]],
minify=False,
microbit_runtime=None,
zoom_level=2,
window=None,
venv_path=None,
**kwargs
):
"""Generate a temporary session file for one test
By default, the session file will be created inside a temporary directory
which will be removed afterwards. If filepath is specified the session
file will be created with that fully-specified path and filename.
If an iterable of file contents is specified (referring to text files to
be reloaded from a previous session) then files will be created in the
a directory with the contents provided.
If None is passed to any of the parameters that item will not be included
in the session data. Once all parameters have been considered if no session
data is present, the file will *not* be created.
Any additional kwargs are created as items in the data (eg to generate
invalid file contents)
The mu.logic.get_session_path function is mocked to return the
temporary filepath from this session.
The session is yielded to the contextmanager so the typical usage is:
with generate_session(mode="night") as session:
# do some test
assert <whatever>.mode == session['mode']
"""
dirpath = tempfile.mkdtemp(prefix="mu-")
session_data = {}
if theme:
session_data["theme"] = theme
if mode:
session_data["mode"] = mode
if file_contents:
paths = _generate_python_files(file_contents, dirpath)
session_data["paths"] = list(paths)
if envars:
session_data["envars"] = envars
if minify is not None:
session_data["minify"] = minify
if microbit_runtime:
session_data["microbit_runtime"] = microbit_runtime
if zoom_level:
session_data["zoom_level"] = zoom_level
if window:
session_data["window"] = window
if venv_path:
session_data["venv_path"] = venv_path
session_data.update(**kwargs)
session = mu.settings.SessionSettings()
session.reset()
session.update(session_data)
with mock.patch("mu.settings.session", session):
yield session
shutil.rmtree(dirpath)
def mocked_view(text, path, newline):
"""Create a mocked view with path, newline and text"""
view = mock.MagicMock()
view.current_tab = mock.MagicMock()
view.current_tab.path = path
view.current_tab.newline = newline
view.current_tab.text = mock.MagicMock(return_value=text)
view.add_tab = mock.MagicMock()
view.get_save_path = mock.MagicMock(return_value=path)
view.get_load_path = mock.MagicMock()
view.add_tab = mock.MagicMock()
return view
def mocked_editor(mode="python", text=None, path=None, newline=None):
"""Return a mocked editor with a mocked view
This is intended to assist the several tests where a mocked editor
is needed but where the length of setup code to get there tends to
obscure the intent of the test
"""
view = mocked_view(text, path, newline)
ed = mu.logic.Editor(view)
ed.select_mode = mock.MagicMock()
mock_mode = mock.MagicMock()
mock_mode.save_timeout = 5
mock_mode.workspace_dir.return_value = "/fake/path"
mock_mode.api.return_value = ["API Specification"]
ed.modes = {mode: mock_mode}
return ed
@pytest.fixture(scope="module")
def prevent_settings_autosave():
"""Prevent the settings from auto-saving"""
atexit._clear()
@pytest.fixture
def mocked_session():
"""Mock the save-session functionality"""
with mock.patch.object(mu.settings, "session") as mocked_session:
yield mocked_session
def test_CONSTANTS():
"""
Ensure the expected constants exist.
"""
assert mu.config.HOME_DIRECTORY
assert mu.config.DATA_DIR
assert mu.config.WORKSPACE_NAME
@pytest.fixture
def microbit_com1():
microbit = mu.logic.Device(
0x0D28,
0x0204,
"COM1",
123456,
"ARM",
"BBC micro:bit",
"microbit",
"BBC micro:bit",
)
return microbit
@pytest.fixture
def microbit_com2():
microbit = mu.logic.Device(
0x0D28,
0x0204,
"COM2",
123456,
"ARM",
"BBC micro:bit",
"microbit",
"BBC micro:bit",
)
return microbit
@pytest.fixture
def adafruit_feather():
adafruit_feather = mu.logic.Device(
0x239A,
0x800B,
"COM1",
123456,
"ARM",
"CircuitPython",
"circuitpython",
"Adafruit Feather",
)
return adafruit_feather
@pytest.fixture
def esp_device():
esp_device = mu.logic.Device(
0x0403,
0x6015,
"COM1",
123456,
"Sparkfun",
"ESP MicroPython",
"esp",
# No board_name specified
)
return esp_device
def test_write_and_flush():
"""
Ensure the write and flush function tries to write to the filesystem and
flush so the write happens immediately.
"""
mock_fd = mock.MagicMock()
mock_content = mock.MagicMock()
with mock.patch("mu.logic.os.fsync") as fsync:
mu.logic.write_and_flush(mock_fd, mock_content)
fsync.assert_called_once_with(mock_fd)
mock_fd.write.assert_called_once_with(mock_content)
mock_fd.flush.assert_called_once_with()
def test_save_and_encode():
"""
When saving, ensure that encoding cookies are honoured, otherwise fall back
to the default encoding (UTF-8 -- as per Python standard practice).
"""
encoding_cookie = "# -*- coding: latin-1 -*-"
text = encoding_cookie + '\n\nprint("Hello")'
mock_open = mock.MagicMock()
mock_wandf = mock.MagicMock()
# Valid cookie
with mock.patch("mu.logic.open", mock_open), mock.patch(
"mu.logic.write_and_flush", mock_wandf
):
mu.logic.save_and_encode(text, "foo.py")
mock_open.assert_called_once_with(
"foo.py", "w", encoding="latin-1", newline=""
)
assert mock_wandf.call_count == 1
mock_open.reset_mock()
mock_wandf.reset_mock()
# Invalid cookie
encoding_cookie = "# -*- coding: utf-42 -*-"
text = encoding_cookie + '\n\nprint("Hello")'
with mock.patch("mu.logic.open", mock_open), mock.patch(
"mu.logic.write_and_flush", mock_wandf
):
mu.logic.save_and_encode(text, "foo.py")
mock_open.assert_called_once_with(
"foo.py", "w", encoding=mu.logic.ENCODING, newline=""
)
assert mock_wandf.call_count == 1
mock_open.reset_mock()
mock_wandf.reset_mock()
# No cookie
text = 'print("Hello")'
with mock.patch("mu.logic.open", mock_open), mock.patch(
"mu.logic.write_and_flush", mock_wandf
):
mu.logic.save_and_encode(text, "foo.py")
mock_open.assert_called_once_with(
"foo.py", "w", encoding=mu.logic.ENCODING, newline=""
)
assert mock_wandf.call_count == 1
def test_sniff_encoding_from_BOM():
"""
Ensure an expected BOM detected at the start of the referenced file is
used to set the expected encoding.
"""
with mock.patch(
"mu.logic.open", mock.mock_open(read_data=codecs.BOM_UTF8 + b"# hello")
):
assert mu.logic.sniff_encoding("foo.py") == "utf-8-sig"
def test_sniff_encoding_from_cookie():
"""
If there's a cookie present, then use that to work out the expected
encoding.
"""
encoding_cookie = b"# -*- coding: latin-1 -*-"
mock_locale = mock.MagicMock()
mock_locale.getpreferredencoding.return_value = "UTF-8"
with mock.patch(
"mu.logic.open", mock.mock_open(read_data=encoding_cookie)
), mock.patch("mu.logic.locale", mock_locale):
assert mu.logic.sniff_encoding("foo.py") == "latin-1"
def test_sniff_encoding_from_bad_cookie():
"""
If there's a cookie present but we can't even read it, then return None.
"""
encoding_cookie = "# -*- coding: silly-你好 -*-".encode("utf-8")
mock_locale = mock.MagicMock()
mock_locale.getpreferredencoding.return_value = "ascii"
with mock.patch(
"mu.logic.open", mock.mock_open(read_data=encoding_cookie)
), mock.patch("mu.logic.locale", mock_locale):
assert mu.logic.sniff_encoding("foo.py") is None
def test_sniff_encoding_fallback_to_locale():
"""
If there's no encoding information in the file, just return None.
"""
mock_locale = mock.MagicMock()
mock_locale.getpreferredencoding.return_value = "ascii"
with mock.patch(
"mu.logic.open", mock.mock_open(read_data=b"# hello")
), mock.patch("mu.logic.locale", mock_locale):
assert mu.logic.sniff_encoding("foo.py") is None
def test_sniff_newline_convention():
"""
Ensure sniff_newline_convention returns the expected newline convention.
"""
text = "the\r\ncat\nsat\non\nthe\r\nmat"
assert mu.logic.sniff_newline_convention(text) == "\n"
def test_sniff_newline_convention_local():
"""
Ensure sniff_newline_convention returns the local newline convention if it
cannot determine it from the text.
"""
text = "There are no new lines here"
assert mu.logic.sniff_newline_convention(text) == os.linesep
@pytest.mark.skip("No longer needed post PR #1200")
def test_get_session_path():
"""
Ensure the result of calling get_admin_file_path with session.json returns
the expected result.
"""
mock_func = mock.MagicMock(return_value="foo")
with mock.patch("mu.logic.get_admin_file_path", mock_func):
assert mu.logic.get_session_path() == "foo"
mock_func.assert_called_once_with("session.json")
@pytest.mark.skip("No longer needed post PR #1200")
def test_get_settings_path():
"""
Ensure the result of calling get_admin_file_path with settings.json returns
the expected result.
"""
mock_func = mock.MagicMock(return_value="foo")
with mock.patch("mu.logic.get_admin_file_path", mock_func):
assert mu.logic.get_settings_path() == "foo"
mock_func.assert_called_once_with("settings.json")
def test_extract_envars():
"""
Given a correct textual representation, get the expected list
representation of user defined environment variables.
"""
raw = "FOO=BAR\n BAZ = Q=X \n\n\n"
expected = mu.logic.extract_envars(raw)
assert expected == [["FOO", "BAR"], ["BAZ", "Q=X"]]
def test_check_flake():
"""
Ensure the check_flake method calls PyFlakes with the expected code
reporter.
"""
mock_r = mock.MagicMock()
mock_r.log = [{"line_no": 2, "column": 0, "message": "b"}]
with mock.patch(
"mu.logic.MuFlakeCodeReporter", return_value=mock_r
), mock.patch("mu.logic.check", return_value=None) as mock_check:
result = mu.logic.check_flake("foo.py", "some code")
assert result == {2: mock_r.log}
mock_check.assert_called_once_with("some code", "foo.py", mock_r)
def test_check_flake_needing_expansion():
"""
Ensure the check_flake method calls PyFlakes with the expected code
reporter.
"""
mock_r = mock.MagicMock()
msg = "'microbit.foo' imported but unused"
mock_r.log = [{"line_no": 2, "column": 0, "message": msg}]
with mock.patch(
"mu.logic.MuFlakeCodeReporter", return_value=mock_r
), mock.patch("mu.logic.check", return_value=None) as mock_check:
code = "from microbit import *"
result = mu.logic.check_flake("foo.py", code)
assert result == {}
mock_check.assert_called_once_with(
mu.logic.EXPANDED_IMPORT, "foo.py", mock_r
)
def test_check_flake_with_builtins():
"""
If a list of assumed builtin symbols is passed, any "undefined name"
messages for them are ignored.
"""
mock_r = mock.MagicMock()
mock_r.log = [
{"line_no": 2, "column": 0, "message": "undefined name 'foo'"}
]
with mock.patch(
"mu.logic.MuFlakeCodeReporter", return_value=mock_r
), mock.patch("mu.logic.check", return_value=None) as mock_check:
result = mu.logic.check_flake("foo.py", "some code", builtins=["foo"])
assert result == {}
mock_check.assert_called_once_with("some code", "foo.py", mock_r)
def test_check_real_flake_output_with_builtins():
"""
Check that passing builtins correctly suppresses undefined name errors
using real .check_flake() output.
"""
ok_result = mu.logic.check_flake("foo.py", "print(foo)", builtins=["foo"])
assert ok_result == {}
bad_result = mu.logic.check_flake("foo.py", "print(bar)", builtins=["foo"])
assert len(bad_result) == 1
def test_check_pycodestyle_E121():
"""
Ensure the expected result is generated from the PEP8 style validator.
Should ensure we honor a mu internal override of E123 error
"""
code = "mylist = [\n 1, 2,\n 3, 4,\n ]" # would have Generated E123
result = mu.logic.check_pycodestyle(code)
assert len(result) == 0
def test_check_pycodestyle_custom_override():
"""
Ensure the expected result if generated from the PEP8 style validator.
For this test we have overridden the E265 error check via a custom
override "pycodestyle" file in a directory pointed to by the content of
scripts/codecheck.ini. We should "not" get and E265 error due to the
lack of space after the #
"""
code = "# OK\n#this is ok if we override the E265 check\n"
result = mu.logic.check_pycodestyle(code, "tests/scripts/pycodestyle")
assert len(result) == 0
def test_check_pycodestyle():
"""
Ensure the expected result if generated from the PEP8 style validator.
"""
code = "import foo\n\n\n\n\n\ndef bar():\n pass\n" # Generate E303
result = mu.logic.check_pycodestyle(code)
assert len(result) == 1
assert result[6][0]["line_no"] == 6
assert result[6][0]["column"] == 0
assert " above this line" in result[6][0]["message"]
assert result[6][0]["code"] == "E303"
def test_check_pycodestyle_with_non_ascii():
"""
Ensure pycodestyle can at least see a file with non-ASCII characters
"""
code = "x='\u2005'\n"
try:
mu.logic.check_pycodestyle(code)
except Exception as exc:
assert False, "Exception was raised: %s" % exc
#
# Doesn't actually matter what pycodestyle returns; we just want to make
# sure it didn't error out
#
def test_MuFlakeCodeReporter_init():
"""
Check state is set up as expected.
"""
r = mu.logic.MuFlakeCodeReporter()
assert r.log == []
def test_MuFlakeCodeReporter_unexpected_error():
"""
Check the reporter handles unexpected errors.
"""
r = mu.logic.MuFlakeCodeReporter()
r.unexpectedError("foo.py", "Nobody expects the Spanish Inquisition!")
assert len(r.log) == 1
assert r.log[0]["line_no"] == 0
assert r.log[0]["filename"] == "foo.py"
assert r.log[0]["message"] == "Nobody expects the Spanish Inquisition!"
def test_MuFlakeCodeReporter_syntax_error():
"""
Check the reporter handles syntax errors in a humane and kid friendly
manner.
"""
msg = (
"Syntax error. Python cannot understand this line. Check for "
"missing characters!"
)
r = mu.logic.MuFlakeCodeReporter()
r.syntaxError(
"foo.py", "something incomprehensible to kids", "2", 3, "source"
)
assert len(r.log) == 1
assert r.log[0]["line_no"] == 1
assert r.log[0]["message"] == msg
assert r.log[0]["column"] == 2
assert r.log[0]["source"] == "source"
def test_MuFlakeCodeReporter_flake_matched():
"""
Check the reporter handles flake (regular) errors that match the expected
message structure.
"""
r = mu.logic.MuFlakeCodeReporter()
err = "foo.py:4:0 something went wrong"
r.flake(err)
assert len(r.log) == 1
assert r.log[0]["line_no"] == 3
assert r.log[0]["column"] == 0
assert r.log[0]["message"] == "something went wrong"
def test_MuFlakeCodeReporter_flake_real_output():
"""
Check the reporter handles real output from flake, to catch format
change regressions.
"""
check = mu.logic.check
reporter = mu.logic.MuFlakeCodeReporter()
code = "a = 1\nb = 2\nc\n"
check(code, "filename", reporter)
assert reporter.log[0]["line_no"] == 2
assert reporter.log[0]["message"] == "undefined name 'c'"
assert reporter.log[0]["column"] == 1
def test_MuFlakeCodeReporter_flake_un_matched():
"""
Check the reporter handles flake errors that do not conform to the expected
message structure.
"""
r = mu.logic.MuFlakeCodeReporter()
err = "something went wrong"
r.flake(err)
assert len(r.log) == 1
assert r.log[0]["line_no"] == 0
assert r.log[0]["column"] == 0
assert r.log[0]["message"] == "something went wrong"
def test_device__init(adafruit_feather):
assert adafruit_feather.vid == 0x239A
assert adafruit_feather.pid == 0x800B
assert adafruit_feather.port == "COM1"
assert adafruit_feather.serial_number == 123456
assert adafruit_feather.manufacturer == "ARM"
assert adafruit_feather.long_mode_name == "CircuitPython"
assert adafruit_feather.short_mode_name == "circuitpython"
assert adafruit_feather.board_name == "Adafruit Feather"
def test_device_name(esp_device, adafruit_feather):
"""
Test that devices without a boardname (such as the esp_device),
are the long mode name with " device" appended
"""
assert esp_device.name == "ESP MicroPython device"
assert adafruit_feather.name == "Adafruit Feather"
def test_device_equality(microbit_com1):
assert microbit_com1 == microbit_com1
def test_device_inequality(microbit_com1, microbit_com2):
assert microbit_com1 != microbit_com2
def test_device_ordering_lt(microbit_com1, adafruit_feather):
assert adafruit_feather < microbit_com1
def test_device_ordering_gt(microbit_com1, adafruit_feather):
assert microbit_com1 > adafruit_feather
def test_device_ordering_le(microbit_com1, adafruit_feather):
assert adafruit_feather <= microbit_com1
def test_device_ordering_ge(microbit_com1, adafruit_feather):
assert microbit_com1 >= adafruit_feather
def test_device_to_string(adafruit_feather):
assert (
str(adafruit_feather)
== "Adafruit Feather on COM1 (VID: 0x239A, PID: 0x800B)"
)
def test_device_hash(microbit_com1, microbit_com2):
assert hash(microbit_com1) == hash(microbit_com1)
assert hash(microbit_com1) != hash(microbit_com2)
def test_devicelist_index(microbit_com1):
modes = {}
dl = mu.logic.DeviceList(modes)
dl.add_device(microbit_com1)
assert dl[0] == microbit_com1
def test_devicelist_length(microbit_com1, microbit_com2):
modes = {}
dl = mu.logic.DeviceList(modes)
assert len(dl) == 0
dl.add_device(microbit_com1)
assert len(dl) == 1
dl.add_device(microbit_com2)
assert len(dl) == 2
def test_devicelist_rowCount(microbit_com1, microbit_com2):
modes = {}
dl = mu.logic.DeviceList(modes)
assert dl.rowCount(None) == 0
dl.add_device(microbit_com1)
assert dl.rowCount(None) == 1
dl.add_device(microbit_com2)
assert dl.rowCount(None) == 2
def test_devicelist_data(microbit_com1, adafruit_feather):
modes = {}
dl = mu.logic.DeviceList(modes)
dl.add_device(microbit_com1)
dl.add_device(adafruit_feather)
tooltip = dl.data(dl.index(0), Qt.ToolTipRole)
display = dl.data(dl.index(0), Qt.DisplayRole)
assert display == adafruit_feather.name
assert tooltip == str(adafruit_feather)
tooltip = dl.data(dl.index(1), Qt.ToolTipRole)
display = dl.data(dl.index(1), Qt.DisplayRole)
assert display == microbit_com1.name
assert tooltip == str(microbit_com1)
def test_devicelist_add_device_in_sorted_order(
microbit_com1, adafruit_feather
):
modes = {}
dl = mu.logic.DeviceList(modes)
dl.add_device(microbit_com1)
assert dl[0] == microbit_com1
dl.add_device(adafruit_feather)
assert dl[0] == adafruit_feather
assert dl[1] == microbit_com1
xyz_device = mu.logic.Device(
0x123B,
0x333A,
"COM1",
123456,
"ARM",
"ESP Mode",
"esp",
"xyz",
)
dl.add_device(xyz_device)
assert dl[2] == xyz_device
def test_devicelist_remove_device(microbit_com1, adafruit_feather):
modes = {}
dl = mu.logic.DeviceList(modes)
dl.add_device(microbit_com1)
assert len(dl) == 1
dl.remove_device(microbit_com1)
assert len(dl) == 0
dl.add_device(microbit_com1)
dl.add_device(adafruit_feather)
assert len(dl) == 2
dl.remove_device(adafruit_feather)
assert len(dl) == 1
dl.remove_device(microbit_com1)
assert len(dl) == 0
def test_editor_init():
"""
Ensure a new instance is set-up correctly and creates the required folders
upon first start.
"""
view = mock.MagicMock()
# Check the editor attempts to create required directories if they don't
# already exist.
with mock.patch("os.path.exists", return_value=False), mock.patch(
"os.makedirs", return_value=None
) as mkd:
e = mu.logic.Editor(view)
assert e._view == view
assert e.theme == "day"
assert e.mode == "python"
assert e.modes == {}
assert e.envars == []
assert e.minify is False
assert e.microbit_runtime == ""
# assert e.connected_devices == set()
assert e.find == ""
assert e.replace == ""
assert e.global_replace is False
assert e.selecting_mode is False
assert mkd.call_count == 1
assert mkd.call_args_list[0][0][0] == mu.logic.DATA_DIR
def test_editor_setup():
"""
An editor should have a modes attribute.
"""
view = mock.MagicMock()
e = mu.logic.Editor(view)
mock_mode = mock.MagicMock()
mock_mode.workspace_dir.return_value = "foo"
mock_modes = {"python": mock_mode}
with mock.patch("os.path.exists", return_value=False), mock.patch(
"os.makedirs", return_value=None
) as mkd, mock.patch("shutil.copy") as mock_shutil_copy, mock.patch(
"shutil.copytree"
) as mock_shutil_copytree:
e.setup(mock_modes)
assert mkd.call_count == 5
assert mkd.call_args_list[0][0][0] == "foo"
asset_len = len(mu.logic.DEFAULT_IMAGES) + len(mu.logic.DEFAULT_SOUNDS)
assert mock_shutil_copy.call_count == asset_len
assert mock_shutil_copytree.call_count == 2
assert e.modes == mock_modes
view.set_usb_checker.assert_called_once_with(
1, e.connected_devices.check_usb
)
def test_editor_connect_to_status_bar():
"""
Check that the Window status bar is connected appropriately
to Editor-pane and to modes
"""
view = mock.MagicMock()
e = mu.logic.Editor(view)
mock_python_mode = mock.MagicMock()
mock_esp_mode = mock.MagicMock()
mock_python_mode.workspace_dir.return_value = "foo"
mock_modes = {"python": mock_python_mode, "esp": mock_esp_mode}
mock_device_selector = mock.MagicMock()
with mock.patch("os.path.exists", return_value=False), mock.patch(
"os.makedirs", return_value=None
), mock.patch("shutil.copy"), mock.patch("shutil.copytree"):
e.setup(mock_modes)
sb = mock.MagicMock()
sb.device_selector = mock_device_selector
e.connect_to_status_bar(sb)
# Check device_changed signal is connected to both editor and modes
assert sb.device_selector.device_changed.connect.call_count == 3
def test_editor_restore_session_existing_runtime():
"""
A correctly specified session is restored properly.
"""
mode, theme = "python", "night"
file_contents = ["", ""]
ed = mocked_editor(mode)
with mock.patch("os.path.isfile", return_value=True):
with mock.patch.object(venv, "relocate") as venv_relocate:
with mock.patch.object(venv, "ensure"), mock.patch.object(
venv, "create"
):
with generate_session(
theme,
mode,
file_contents,
microbit_runtime="/foo",
zoom_level=5,
venv_path="foo",
):
ed.restore_session()
assert ed.theme == theme
assert ed._view.add_tab.call_count == len(file_contents)
ed._view.set_theme.assert_called_once_with(theme)
assert ed.envars == [["name", "value"]]
assert ed.minify is False
assert ed.microbit_runtime == "/foo"
assert ed._view.zoom_position == 5
assert venv_relocate.called_with("foo")
def test_editor_restore_session_missing_runtime():
"""
If the referenced microbit_runtime file doesn't exist, reset to '' so Mu
uses the built-in runtime.
"""
mode, theme = "python", "night"
file_contents = ["", ""]
ed = mocked_editor(mode)
with generate_session(theme, mode, file_contents, microbit_runtime="/foo"):
ed.restore_session()
assert ed.theme == theme
assert ed._view.add_tab.call_count == len(file_contents)
ed._view.set_theme.assert_called_once_with(theme)
assert ed.envars == [["name", "value"]]
assert ed.minify is False
assert ed.microbit_runtime == "" # File does not exist so set to ''
def test_editor_restore_session_missing_files():
"""
Missing files that were opened tabs in the previous session are safely
ignored when attempting to restore them.
"""
mode, theme = "python", "night"
ed = mocked_editor(mode)
with generate_session(theme, mode) as session:
session["paths"] = ["*does not exist*"]
ed.restore_session()
assert ed._view.add_tab.call_count == 0
def test_editor_restore_session_invalid_mode():
"""
As Mu's modes are added and/or renamed, invalid mode names may need to be
ignored (this happens regularly when changing versions when developing
Mu itself).
"""
valid_mode, invalid_mode = "python", uuid.uuid1().hex
ed = mocked_editor(valid_mode)
with generate_session(mode=invalid_mode):
ed.restore_session()
ed.select_mode.assert_called_once_with(None)
def test_editor_restore_session_no_session_file():
"""
If there's no prior session file (such as upon first start) then simply
start up the editor with an empty untitled tab.
Strictly, this isn't now a check for no session file but for an
empty session object (which might have arisen from no file)
"""
ed = mocked_editor()
ed._view.tab_count = 0
ed._view.add_tab = mock.MagicMock()
session = mu.settings.SessionSettings()
filepath = os.path.abspath(rstring())
assert not os.path.exists(filepath)
session.load(filepath)
with mock.patch.object(mu.settings, "session", session):
ed.restore_session()
ed._view.add_tab.call_count == 1
ed.select_mode.assert_called_once_with(None)
def test_editor_restore_session_invalid_file(tmp_path):
"""
A malformed JSON file is correctly detected and app behaves the same as if
there was no session file.
"""
ed = mocked_editor()
ed._view.tab_count = 0
ed._view.add_tab = mock.MagicMock()
session = mu.settings.SessionSettings()
filepath = os.path.join(str(tmp_path), rstring())
with open(filepath, "w") as f:
f.write(rstring())
session.load(filepath)
with mock.patch.object(mu.settings, "session", session):
ed.restore_session()
ed._view.add_tab.call_count == 1
ed.select_mode.assert_called_once_with(None)
def test_restore_session_open_tabs_in_the_same_order():
"""
Editor.restore_session() loads editor tabs in the same order as the 'paths'
array in the session.json file.
"""
ed = mocked_editor()
ed.direct_load = mock.MagicMock()
settings_paths = ["a.py", "b.py", "c.py", "d.py"]
with generate_session(paths=settings_paths):
ed.restore_session()
direct_load_calls_args = [
os.path.basename(args[0])
for args, _kwargs in ed.direct_load.call_args_list
]
assert direct_load_calls_args == settings_paths