This repository has been archived by the owner on Dec 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 32
/
testcert.py
executable file
·5432 lines (4825 loc) · 203 KB
/
testcert.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
#!/usr/bin/python
"""Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
The main runner for tests used by the Cloud Print Logo Certification tool.
This suite of tests depends on the unittest runner to execute tests. It will log
results and debug information into a log file.
Before executing this program, edit _config.py and put in the proper values for
the printer being tested, and the test accounts that you are using. For the
primary test account, you need to add some OAuth2 tokens, a Client ID and a
Client Secret. Consult the README file for more details about setting up these
tokens and other needed variables in _config.py.
When testcert.py executes, some of the tests will require manual intervention,
therefore watch the output of the script while it's running.
test_id corresponds to an internal database used by Google, so don't change
those IDs. These IDs are used when submitting test results to our database.
"""
__version__ = '2.0'
import _log
import _sheets
import optparse
import os
import platform
import re
import sys
import time
import traceback
import unittest
from _common import Sleep
from _common import BlueText
from _common import GreenText
from _common import RedText
from _common import PromptAndWaitForUserAction
from _common import PromptUserAction
from _config import Constants
from _cpslib import GCPService
from _device import Device
from _oauth2 import Oauth2
from _ticket import CloudJobTicket, GCPConstants
from _transport import Transport
from _zconf import MDNS_Browser
from _zconf import Wait_for_privet_mdns_service
# Module level variables
_logger = None
_transport = None
_device = None
_oauth2 = None
_gcp = None
_sheet = None
def _ParseArgs():
"""Parse command line options."""
parser = optparse.OptionParser()
parser.add_option('--autorun',
help='Skip manual input',
default=Constants.AUTOMODE,
action="store_true",
dest='autorun')
parser.add_option('--no-autorun',
help='Do not skip manual input',
default=Constants.AUTOMODE,
action="store_false",
dest='autorun')
parser.add_option('--debug',
help='Specify debug log level [default: %default]',
default='info',
type='choice',
choices=['debug', 'info', 'warning', 'error', 'critical'],
dest='debug')
parser.add_option('--email',
help='Email account to use [default: %default]',
default=Constants.USER['EMAIL'],
dest='email')
parser.add_option('--if-addr',
help='Interface address for Zeroconf',
default=None,
dest='if_addr')
parser.add_option('--loadtime',
help='Seconds for web pages to load [default: %default]',
default=10,
type='float',
dest='loadtime')
parser.add_option('--logdir',
help='Relative directory for logfiles [default: %default]',
default=Constants.LOGFILES,
dest='logdir')
parser.add_option('--printer',
help='Name of printer [default: %default]',
default=Constants.PRINTER['NAME'],
dest='printer')
parser.add_option('--no-stdout',
help='Do not send output to stdout',
default=True,
action="store_false",
dest='stdout')
return parser.parse_args()
# The setUpModule will run one time, before any of the tests are run. The global
# keyword must be used in order to give all of the test classes access to
# these objects. This approach is used to eliminate the need for initializing
# all of these objects for each and every test class.
def setUpModule():
global _device
global _gcp
global _logger
global _oauth2
global _transport
# Initialize globals and constants
options, unused_args = _ParseArgs()
_logger = _log.GetLogger('LogoCert', logdir=options.logdir,
loglevel=options.debug, stdout=options.stdout)
_oauth2 = Oauth2(_logger)
# Retrieve access + refresh tokens
_oauth2.GetTokens()
# Wait to receive Privet printer advertisements. Timeout in 30 seconds
printer_service = Wait_for_privet_mdns_service(30, Constants.PRINTER['NAME'],
_logger)
if printer_service is None:
_logger.info("No printers discovered under "+ options.printer)
sys.exit()
privet_port = None
if hasattr(printer_service, 'port'):
privet_port = int(printer_service.port)
_logger.debug('Privet advertises port: %d', privet_port)
_gcp = GCPService(Constants.AUTH["ACCESS"])
_device = Device(_logger, Constants.AUTH["ACCESS"], _gcp,
privet_port= privet_port if 'PORT' not in Constants.PRINTER
else Constants.PRINTER['PORT'])
_transport = Transport(_logger)
if Constants.TEST['SPREADSHEET']:
global _sheet
_sheet = _sheets.SheetMgr(_logger, _oauth2.storage.get(), Constants)
# pylint: enable=global-variable-undefined
def LogTestSuite(name):
"""Log a test result.
Args:
name: string, name of the testsuite that is logging.
"""
print ('========================================'
'========================================')
print ' Starting %s testSuite'% (name)
print ('========================================'
'========================================')
if Constants.TEST['SPREADSHEET']:
row = [name,'','','','','','','']
_sheet.AddRow(row)
def isPrinterAdvertisingAsRegistered(service):
"""Checks the printer's privet advertisements and see if it is advertising
as registered or not
Args:
service: ServiceInfo, printer's service Info
Returns:
boolean, True = advertising as registered,
False = advertising as unregistered,
None = advertisement not found
"""
return ('id' in service.properties and
service.properties['id'] and
'online' in service.properties['cs'].lower())
def waitForAdvertisementRegStatus(name, is_wait_for_reg, timeout):
"""Wait for the device to privet advertise as registered or unregistered
Args:
name: string, device status to wait on
is_wait_for_reg: boolean, True for registered , False for unregistered
timeout: integer, seconds to wait for the service update
Returns:
boolean, True = status observed, False = status not observed.
"""
global _logger
end = time.time() + timeout
while time.time() < end:
service = Wait_for_privet_mdns_service(end-time.time(), name, _logger)
if service is None:
_logger.info("No printers discovered under " + name)
else:
is_registered = isPrinterAdvertisingAsRegistered(service)
if is_registered is is_wait_for_reg:
return True
return False
def writeRasterToFile(file_path, content):
""" Save a raster image to file
Args:
file_path: string, file path to write to
content: string, content to write
"""
f = open(file_path, 'wb')
f.write(content)
f.close()
print "Wrote Raster file:%s to disk" % file_path
def getRasterImageFromCloud(pwg_path, img_path):
""" Submit a GCP print job so that the image is coverted to a supported raster
file that can be downloaded. Then download the raster image from the cloud
and save it to disk
Args:
pwg_path: string, destination file path of the pwg_raster image
img_path: string, src file path of the image to convert from
"""
#
cjt = CloudJobTicket()
if Constants.CAPS['COLOR']:
cjt.AddColorOption(GCPConstants.COLOR)
print 'Generating pwg-raster via cloud print'
output = _gcp.Submit(_device.dev_id, img_path,
'LocalPrinting Raster Setup', cjt)
if not output['success']:
print 'ERROR: Cloud printing failed.'
raise
else:
try:
_gcp.WaitJobStateIn(output['job']['id'], _device.dev_id,
GCPConstants.IN_PROGRESS)
except AssertionError:
print 'GCP ERROR: Job not observed to be in progress.'
raise
else:
try:
res = _gcp.FetchRaster(output['job']['id'])
except AssertionError:
print "ERROR: FetchRaster() failed."
print "LocalPrinting suite cannot run without raster files."
raise
else:
writeRasterToFile(pwg_path, res)
print '[Configurable timeout] PRINTING'
_gcp.WaitJobStateIn(output['job']['id'], _device.dev_id,
GCPConstants.DONE,
timeout=Constants.TIMEOUT['PRINTING'])
def getLocalPrintingRasterImages():
""" Checks to see if the raster images used for local printing exist on the
machine, generate and store to disk if not
"""
if not os.path.exists(Constants.IMAGES['PWG1']):
print '\n%s not found.'% (Constants.IMAGES['PWG1'])
print 'Likely that this is the first time LocalPrinting suite is run.'
getRasterImageFromCloud(Constants.IMAGES['PWG1'], Constants.IMAGES['PNG7'])
if not os.path.exists(Constants.IMAGES['PWG2']):
print '\n%s not found.' % (Constants.IMAGES['PWG2'])
print 'Likely that this is the first time LocalPrinting suite is run.'
getRasterImageFromCloud(Constants.IMAGES['PWG2'], Constants.IMAGES['PDF10'])
class LogoCert(unittest.TestCase):
"""Base Class to drive Logo Certification tests."""
def shortDescription(self):
'''Overriding the docstring printout function'''
doc = self._testMethodDoc
msg = doc and doc.split("\n")[0].strip() or None
return BlueText('\n=================================='
'====================================\n' + msg + '\n')
@classmethod
def setUpClass(cls, suite=None):
options, unused_args = _ParseArgs()
cls.loadtime = options.loadtime
cls.username = options.email
cls.autorun = options.autorun
cls.printer = options.printer
cls.monochrome = GCPConstants.MONOCHROME
cls.color = (GCPConstants.COLOR if Constants.CAPS['COLOR']
else cls.monochrome)
# Refresh access token in case it has expired
_oauth2.RefreshToken()
_device.auth_token = Constants.AUTH['ACCESS']
_gcp.auth_token = Constants.AUTH['ACCESS']
suite_name = cls.__name__ if suite is None else suite.__name__
LogTestSuite(suite_name)
def ManualPass(self, test_id, test_name, print_test=True):
"""Take manual input to determine if a test passes.
Args:
test_id: integer, testid in TestTracker database.
test_name: string, name of test.
print_test: boolean, True = print test, False = not print test.
Returns:
boolean: True = Pass, False = Fail.
If self.autorun is set to true, then this method will pause and return True.
"""
if self.autorun:
if print_test:
notes = 'Manually examine printout to verify correctness.'
else:
notes = 'Manually verify the test produced the expected result.'
self.LogTest(test_id, test_name, 'Passed', notes)
Sleep('AUTO_RUN')
return True
print 'Did the test produce the expected result?'
result = ''
while result.lower() not in ['y','n']:
result = PromptAndWaitForUserAction('Enter "y" or "n"')
try:
self.assertEqual(result.lower(), 'y')
except AssertionError:
notes = PromptAndWaitForUserAction('Type in additional notes for test '
'failure, hit return when finished')
self.LogTest(test_id, test_name, 'Failed', notes)
return False
else:
self.LogTest(test_id, test_name, 'Passed')
return True
def CheckAndRefreshToken(self):
"""Refresh oauth access token and updates dependent objects accordingly"""
# Oauth Access tokens expire in 1 hr, but we refresh every 30 minutes just
# to stay on the safe side
if time.time() > Constants.AUTH['PREV_TOKEN_TIME'] + 1800:
_oauth2.RefreshToken()
_device.auth_token = Constants.AUTH['ACCESS']
_gcp.auth_token = Constants.AUTH['ACCESS']
def LogTest(self, test_id, test_name, result, notes=''):
"""Log a test result.
Args:
test_id: integer, test id in the TestTracker application.
test_name: string, name of the test.
result: string, ["Passed", "Failed", "Skipped", "Not Run"]
notes: string, notes to include with the test result.
"""
failure = False if result.lower() in ['passed','skipped','n/a'] else True
console_result = RedText(result) if failure else GreenText(result)
console_test_name = RedText(test_name) if failure else GreenText(test_name)
print '' # For spacing
_logger.info('Test ID: %s', test_id)
_logger.info('Result: %s', console_result)
_logger.info('Name: %s', console_test_name)
if notes:
console_notes = RedText(notes) if failure else GreenText(notes)
_logger.info('Notes: %s', console_notes)
if Constants.TEST['SPREADSHEET']:
row = [str(test_id), test_name, result, notes,'','','']
if failure:
# If failed, generate the cmd that to rerun this testcase
# Get module name - name of this python script
module = 'testcert'
# Get the caller's class name
testsuite = sys._getframe(1).f_locals['self'].__class__.__name__
# Since some testcases contain multiple test ids, we cannot simply use
# test_name to invoke the testcase it belongs to
# Use traceback to get a list of functions in the callstack that begins
# with test, the current testcase is the last entry on the list
pattern = r', in (test.+)\s'
testcase = [re.search(pattern, x).group(1) for x in
traceback.format_stack() if
re.search(pattern, x) is not None][-1]
row.append('python -m unittest %s.%s.%s' %(module,testsuite,testcase))
_sheet.AddRow(row)
@classmethod
def GetDeviceDetails(cls):
_device.GetDeviceDetails()
if not _device.name:
_logger.error('Error finding device via privet.')
_logger.error('Check printer model in _config file.')
raise unittest.SkipTest('Could not find device via privet.')
else:
_logger.debug('Printer name: %s', _device.name)
_logger.debug('Printer status: %s', _device.status)
for k in _device.details:
_logger.debug(k)
_logger.debug(_device.details[k])
_logger.debug('===============================')
_device.GetDeviceCDD(_device.dev_id)
for k in _device.cdd:
_logger.debug(k)
_logger.debug(_device.cdd[k])
_logger.debug('===============================')
class SystemUnderTest(LogoCert):
"""Record details about the system under test and test environment."""
def testRecordTestEnv(self):
"""Record test environment details to Google Sheets."""
test_id = '459f04a4-7109-404c-b9e3-64573a077a65'
test_name = 'Test Environment'
os_type = '%s %s' % (platform.system(), platform.release())
python_version = sys.version
notes = 'OS: %s\n' % os_type
notes += 'Python: %s\n' % python_version
notes += 'Code Version: %s' % self.getCodeVersion()
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrinterDetails(self):
"""Record printer details to Google Sheets."""
test_id = 'ec2f8266-6c3e-4ebd-a7b5-df4792a5d93a'
test_name = 'Printer Details'
notes = 'Manufacturer: %s\n' % Constants.PRINTER['MANUFACTURER']
notes += 'Model: %s\n' % Constants.PRINTER['MODEL']
notes += 'Name: %s\n' % Constants.PRINTER['NAME']
notes += 'Device Status: %s\n' % Constants.PRINTER['STATUS']
notes += 'Firmware: %s\n' % Constants.PRINTER['FIRMWARE']
notes += 'Serial Number: %s\n' % Constants.PRINTER['SERIAL']
notes += self.getCAPS()
self.LogTest(test_id, test_name, 'Passed', notes)
def getCAPS(self):
caps = 'CAPS = {\n'
for k,v in Constants.CAPS.iteritems():
caps += " '%s': %s,\n" % (k,v)
caps += '}\n'
return caps
def getCodeVersion(self):
version = 'N/A'
if os.path.isfile('version'):
with open('version', ) as f:
version = f.read()
return version
class Privet(LogoCert):
"""Verify device integrates correctly with the Privet protocol.
These tests should be run before a device is registered.
"""
@classmethod
def setUpClass(cls):
LogoCert.setUpClass(cls)
_device.assertPrinterIsUnregistered()
def testPrivetInfoAPI(self):
"""Verify device responds to PrivetInfo API requests."""
test_id = '7201b68f-de0b-4e93-a1a6-d674af9ec6ec'
test_name = 'PrivetAPI.Info'
# When a device object is initialized, it sends a request to the privet
# info API, so all of the needed information should already be set.
try:
self.assertIn('x-privet-token', _device.privet_info)
except AssertionError:
notes = 'No x-privet-token found. Error in privet info API.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'X-Privet-Token: %s' % _device.privet_info['x-privet-token']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoAPIManufacturer(self):
"""Verify device PrivetInfo API contains manufacturer field."""
test_id = '58fedd52-3bc4-472b-897e-55ee5675fa5c'
test_name = 'PrivetInfoAPI.Manufacturer'
# When a device object is initialized, it sends a request to the privet
# info API, so all of the needed information should already be set.
try:
self.assertIn('manufacturer', _device.privet_info)
except AssertionError:
notes = 'manufacturer not found in privet info.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Manufacturer: %s' % _device.privet_info['manufacturer']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoAPIModel(self):
"""Verify device PrivetInfo API contains model field."""
test_id = 'a0421845-9477-487f-8674-4203cbe6801b'
test_name = 'PrivetInfoAPI.Model'
# When a device object is initialized, it sends a request to the privet
# info API, so all of the needed information should already be set.
try:
self.assertIn('model', _device.privet_info)
except AssertionError:
notes = 'model not found in privet info.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Model: %s' % _device.privet_info['model']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoAPIFirmware(self):
"""Verify device PrivetInfo API contains firmware field."""
test_id = '4c055e06-02aa-436d-b700-80f184e84f47'
test_name = 'PrivetInfoAPI.Firmware'
# When a device object is initialized, it sends a request to the privet
# info API, so all of the needed information should already be set.
try:
self.assertIn('firmware', _device.privet_info)
except AssertionError:
notes = 'firmware not found in privet info.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Firmware: %s' % _device.privet_info['firmware']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoAPIUpdateUrl(self):
"""Verify device PrivetInfo API contains update_url field."""
test_id = 'd469199f-fcbd-4a83-90bf-772453be2b09'
test_name = 'PrivetInfoAPI.UpdateURL'
# When a device object is initialized, it sends a request to the privet
# info API, so all of the needed information should already be set.
try:
self.assertIn('update_url', _device.privet_info)
except AssertionError:
notes = '(OPTIONAL) update_url not found in privet info.'
self.LogTest(test_id, test_name, 'Skipped', notes)
raise
else:
notes = 'update_url: %s' % _device.privet_info['update_url']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoAPIVersion(self):
"""Verify device PrivetInfo API contains version field."""
test_id = '7a5c02f3-26f6-4df4-b8c8-953bedd4ba2d'
test_name = 'PrivetInfoAPI.Version'
# When a device object is initialized, it sends a request to the privet
# info API, so all of the needed information should already be set.
valid_versions = ['1.0', '1.1', '1.5', '2.0']
try:
self.assertIn('version', _device.privet_info)
except AssertionError:
notes = 'version not found in privet info.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertIn(_device.privet_info['version'], valid_versions)
except AssertionError:
notes = 'Incorrect GCP Version in privetinfo: %s' % (
_device.privet_info['version'])
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Version: %s' % _device.privet_info['version']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoDeviceState(self):
"""Verify device PrivetInfo API contains DeviceState and valid value."""
test_id = 'c3ea4263-3745-4d69-8dd4-578f5e5a336b'
test_name = 'PrivetInfoAPI.DeviceState'
valid_states = ['idle', 'processing', 'stopped']
try:
self.assertIn('device_state', _device.privet_info)
except AssertionError:
notes = 'device_state not found in privet info.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertIn(_device.privet_info['device_state'], valid_states)
except AssertionError:
notes = 'Incorrect device_state in privet info: %s' % (
_device.privet_info['device_state'])
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Device state: %s' % _device.privet_info['device_state']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoConnectionState(self):
"""Verify device PrivetInfo contains ConnectionState and valid value."""
test_id = '8ab9ac16-0c6e-47ec-a24e-c5ad4f77abb2'
test_name = 'PrivetInfoAPI.ConnectionState'
valid_states = ['online', 'offline', 'connecting', 'not-configured']
try:
self.assertIn('connection_state', _device.privet_info)
except AssertionError:
notes = 'connection_state not found in privet info.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertIn(_device.privet_info['connection_state'], valid_states)
except AssertionError:
notes = 'Incorrect connection_state in privet info: %s' % (
_device.privet_info['connection_state'])
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Connection state: %s' % _device.privet_info['connection_state']
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetAccessTokenAPI(self):
"""Verify unregistered device Privet AccessToken API returns correct rc."""
test_id = 'ffa0d9dc-840f-486a-a890-91773fc2b12d'
test_name = 'PrivetAPI.AccessToken'
api = 'accesstoken'
expected_return_code = [200, 404]
response = _transport.HTTPGet(_device.privet_url[api],
headers=_device.headers)
try:
self.assertIsNotNone(response)
except AssertionError:
notes = 'No response received from %s' % _device.privet_url[api]
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertIn(response.status_code, expected_return_code)
except AssertionError:
notes = ('Incorrect return code from %s: Got %d, Expected %d.\n'
% (_device.privet_url[api], response.status_code,
expected_return_code))
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = '%s returned response code %d' % (_device.privet_url[api],
response.status_code)
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetCapsAPI(self):
"""Verify unregistered device Privet Capabilities API returns correct rc."""
test_id = '3bd87d10-301d-43b4-b959-96ede9537526'
test_name = 'PrivetAPI.Capabilities'
api = 'capabilities'
expected_return_code = [200, 404]
response = _transport.HTTPGet(_device.privet_url[api],
headers=_device.headers)
try:
self.assertIsNotNone(response)
except AssertionError:
notes = 'No response received from %s' % _device.privet_url[api]
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertIn(response.status_code, expected_return_code)
except AssertionError:
notes = ('Incorrect return code from %s: Got %d, Expected %d.\n'
% (_device.privet_url[api], response.status_code,
expected_return_code))
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = '%s returned code %d' % (_device.privet_url[api],
response.status_code)
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetPrinterAPI(self):
"""Verify unregistered device Privet Printer API returns correct rc."""
test_id = 'c957966b-b63c-4827-94fa-1bf1fe930638'
test_name = 'PrivetAPI.Printer'
api = 'printer'
expected_return_codes = [200, 404]
response = _transport.HTTPGet(_device.privet_url[api],
headers=_device.headers)
try:
self.assertIsNotNone(response)
except AssertionError:
notes = 'No response received from %s' % _device.privet_url[api]
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertIn(response.status_code, expected_return_codes)
except AssertionError:
notes = 'Incorrect return code, found %d' % response.status_code
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = '%s returned code %d' % (_device.privet_url[api],
response.status_code)
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetUnknownURL(self):
"""Verify device returns 404 return code for unknown url requests."""
test_id = '12119bbe-7707-44f3-8743-8cde0696dcd0'
test_name = 'PrivetAPI.UnknownURL'
response = _transport.HTTPGet(_device.privet_url['INVALID'],
headers=_device.headers)
try:
self.assertIsNotNone(response)
except AssertionError:
notes = 'No response code received.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertEqual(response.status_code, 404)
except AssertionError:
notes = 'Wrong return code received. Received %d' % response.status_code
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Received correct return code: %d' % response.status_code
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetRegisterAPI(self):
"""Verify unregistered device exposes register API."""
test_id = 'f875316e-7189-4321-8ac7-bf5e1bd53d8d'
test_name = 'PrivetAPI.Register'
success = _device.StartPrivetRegister()
try:
self.assertTrue(success)
except AssertionError:
notes = 'Error starting privet registration.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Privet registration API working correctly'
self.LogTest(test_id, test_name, 'Passed', notes)
# Cancel the registration so the printer is not in an unknown state
_device.CancelRegistration()
def testPrivetRegistrationInvalidParam(self):
"""Verify device return error if invalid registration param given."""
test_id = 'b2d25268-86aa-41f5-8891-3a5e29c4dbff'
test_name = 'PrivetAPI.RegistrationInvalidParam'
url = _device.privet_url['register']['invalid']
params = {'user': Constants.USER['EMAIL']}
response = _transport.HTTPPost(url, headers=_device.headers, params=params)
try:
self.assertIsNotNone(response)
except AssertionError:
notes = 'No response received.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertEqual(response.status_code, 200)
except AssertionError:
notes = 'Response code from invalid registration params: %d' % (
response.status_code)
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
info = response.json()
try:
self.assertIn('error', info)
except AssertionError:
notes = 'Did not find error message. Error message: %s' % (
info)
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Received correct error code and response: %d\n%s' % (
response.status_code, info)
self.LogTest(test_id, test_name, 'Passed', notes)
finally:
_device.CancelRegistration()
def testPrivetInfoAPIEmptyToken(self):
"""Verify device returns code 200 if Privet Token is empty."""
test_id = '1c3d8852-0130-49e1-baab-396fabb774a9'
test_name = 'PrivetInfoAPI.EmptyToken'
response = _transport.HTTPGet(_device.privet_url['info'],
headers=_device.privet.headers_empty)
try:
self.assertIsNotNone(response)
except AssertionError:
notes = 'No response code received.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertEqual(response.status_code, 200)
except AssertionError:
notes = 'Return code received: %d' % response.status_code
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Return code: %d' % response.status_code
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoAPIInvalidToken(self):
"""Verify device returns code 200 if Privet Token is invalid."""
test_id = '83eafa05-bfe4-480a-8a24-c44e57b78252'
test_name = 'PrivetInfoAPI.InvalidToken'
response = _transport.HTTPGet(_device.privet_url['info'],
headers=_device.privet.headers_invalid)
try:
self.assertIsNotNone(response)
except AssertionError:
notes = 'No response code received.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertEqual(response.status_code, 200)
except AssertionError:
notes = 'Return code received: %d' % response.status_code
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Return code: %d' % response.status_code
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrivetInfoAPIMissingToken(self):
"""Verify device returns code 400 if Privet Token is missing."""
test_id = 'bdd2be1d-1ee1-4348-b95d-59916947e10b'
test_name = 'PrivetInfoAPI.MissingToken'
response = _transport.HTTPGet(_device.privet_url['info'],
headers=_device.privet.headers_missing)
try:
self.assertIsNotNone(response)
except AssertionError:
notes = 'No response code received.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertEqual(response.status_code, 400)
except AssertionError:
notes = 'Return code received: %d' % response.status_code
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Return code: %d' % response.status_code
self.LogTest(test_id, test_name, 'Passed', notes)
def testDeviceRegistrationInvalidClaimToken(self):
"""Verify a device will not register if the claim token is invalid."""
test_id = '80afa1d1-bd62-4534-87e6-49f9905f6973'
test_name = 'PrivetAPI.RegistrationInvalidClaimToken'
try:
self.assertTrue(_device.StartPrivetRegister())
except AssertionError:
notes = 'Error starting privet registration.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
_device.claim_token = 'INVALID'
_device.automated_claim_url = (
'https://www.google.com/cloudprint/confirm?token=INVALID')
try:
self.assertFalse(_device.SendClaimToken(Constants.AUTH['ACCESS']))
except AssertionError:
notes = 'Device accepted invalid claim token.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Device did not accept invalid claim token.'
self.LogTest(test_id, test_name, 'Passed', notes)
finally:
_device.CancelRegistration()
def testDeviceRegistrationInvalidUserAuthToken(self):
"""Verify a device will not register if the user auth token is invalid."""
test_id = 'ac798d92-4789-4e0e-ad59-da5ce5ae0be2'
test_name = 'PrivetAPI.RegistrationInvalidUserAuthToken'
try:
self.assertTrue(_device.StartPrivetRegister())
except AssertionError:
notes = 'Error starting privet registration.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
if Constants.CAPS['PRINTER_PANEL_UI'] or Constants.CAPS['WEB_URL_UI']:
PromptUserAction('ACCEPT the registration request on the Printer '
'Panel or Web UI and wait...')
try:
self.assertTrue(_device.GetPrivetClaimToken())
except AssertionError:
notes = 'Error getting claim token.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
try:
self.assertFalse(_device.SendClaimToken('INVALID_USER_AUTH_TOKEN'))
except AssertionError:
notes = 'Claim token accepted with invalid User Auth Token.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Claim token not accepted with invalid user auth token.'
self.LogTest(test_id, test_name, 'Passed', notes)
finally:
_device.CancelRegistration()
class Printer(LogoCert):
"""Verify printer provides necessary details."""
@classmethod
def setUpClass(cls):
LogoCert.setUpClass(cls)
LogoCert.GetDeviceDetails()
def testPrinterName(self):
"""Verify printer provides a name."""
test_id = '56f55e15-a170-4963-8523-eedd69877892'
test_name = 'CDD.name'
try:
self.assertIsNotNone(_device.name)
except AssertionError:
notes = 'No printer name found.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
_logger.info('Printer name found in details.')
try:
self.assertIn(Constants.PRINTER['NAME'], _device.name)
except AssertionError:
notes = 'NAME in _config.py does not match. Found %s' % _device.name
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn('name', _device.cdd)
except AssertionError:
notes = 'Printer CDD missing printer name.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
_logger.info('Printer name found in CDD.')
try:
self.assertIn(Constants.PRINTER['NAME'], _device.cdd['name'])
except AssertionError:
notes = ('NAME in _config.py does not match name in CDD. Found %s in CDD'
% _device.cdd['name'])
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Printer name: %s' % _device.name
self.LogTest(test_id, test_name, 'Passed', notes)
def testPrinterStatus(self):
"""Verify printer has online status."""
test_id = '0197ce66-ab79-4b0c-be02-c78325cda7fe'
test_name = 'CDD.Status'
try:
self.assertIsNotNone(_device.status)
except AssertionError:
notes = 'Device has no status.'
self.LogTest(test_id, test_name, 'Failed', notes)
raise
try:
self.assertIn('ONLINE', _device.status)
except AssertionError:
notes = 'Device is not online. Status: %s' % _device.status
self.LogTest(test_id, test_name, 'Failed', notes)
raise
else:
notes = 'Status: %s' % _device.status
self.LogTest(test_id, test_name, 'Passed', notes)