-
Notifications
You must be signed in to change notification settings - Fork 1
/
moliana.py
1537 lines (1168 loc) · 50.6 KB
/
moliana.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 -*-
#
# Copyright (C) 2016 Jens Möckel <[email protected]>, All Rights
# Reserved
#
# Implemented by Jens Möckel
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
"""
MOLIANA - MOdelica LIbrary ANAlyser for Dymola.
Analysation of modelica libraries based on Dymolas checkModel()
This module provides
DymolaMode():
Automated execution of Dymolas checkModel()
Report():
Representation of results
Converter():
Converts content of Report instances to HTML files and vice versa
EXAMPLES:
Several examples are provided on 'https://github.com/jmoeckel/moliana/wiki/Examples'.
API:
Each class contains a full documentation of the provided API. Furthermore, an
overview is given on 'https://github.com/jmoeckel/moliana/wiki/UserInterface'.
SOFTWARE REQUIREMENTS:
- This module has been implemented and tested with Python 3.4.3 on a Windows 7
and Windows 10 platform
- DymolaMode requires Dymola 2016 or newer.
"""
import os;
import subprocess;
import win32ui;
import dde;
import time;
##############################################################################
class DymolaMode(object):
"""
Returns a new DymolaMode instance.
Instance provides the possibility to apply automated Dymolas checkModel()
to a Modelica library.
NOTE:
This will only work with Dymola 2016 and newer as the Dymola fuction
'getLastError' does not provide necesary information in older versions.
ATTRIBUTES:
modelica_lib_path (string):
Path to a Modelica library
dymola_path(string):
Path to the Dymola installation, e.g. dymola.exe
OPTIONAL ATTRIBUTES:
dymola_pedantic (bool, default=False):
If true, checkModel() is executed in pedantic mode
modelica_lib_firstlevel (string, default=''):
A subpackage of the library. checkModel() is applied to this package
(and all packages/models in this one).
Note, that if your chosen Top-Level package is e.g. a third-level
package, modelica_lib_firstlevel must include the complete path in the
library.
Example:
Given structure: lib > A > B. Then:
modelica_lib_path = '...\lib'
modelica_lib_firstlevel = 'A\B'
modelica_lib_depth (int, default=1):
How many levels should be listet in the report, e.g. level 1 will list
all top-level packages/models, level 2 additionally all second-level
packages/models and so on.
Note1:
Level of displayed packageshas no influence on how many levels are
actually checked - checkModel() is always applied to all packages/
models in modelica_lib_firstlevel
Note2:
Setting modelica_lib_depth to '-1' will show all packages/models in
the report.
report_path(string, default=[chosen first level]):
path attribute of a report instance
report_name (string, default='report'):
name attribute of a report instance
report_mode (string, default='full'):
mode attribute of a report instance
report_disp (list of dictionaries, default=
[{'Key':'Checked Library', 'Val':[chosen first level in Modelica syntax]},
{'Key':'Pedantic Mode', 'Val': self.dymola_pedantic},
{'Key':'Level of Detail', 'Val': self.modelica_lib_depth}])):
{'Key':Branch', 'Val': [Either name of branch or 'no git']}
disp attribute of a report instance
report_colors (dictionary, default={'cTrue':'white','cFalse':'red', 'cNF':'yellow','cErr':'red','cWrn':'yellow'})
colors attribute of a report instance
For more detailled informations regardings the reports attributes, take a
look a the documentation of the report class
API:
execute_check():
Applies Dymolas checkModel() on given library (modelica_lib_path) or
respectively chosen top level package (modelica_lib_firstlevel).
get_report():
Returns the current Report instance.
For more details take a look at the module itsself
"""
def __init__(self, modelica_lib_path, dymola_path, **kwargs):
self.modelica_lib_path = os.path.abspath(modelica_lib_path)
self.dymola_path = dymola_path
#list of all options
self._options = ['dymola_pedantic', 'modelica_lib_firstlevel',
'modelica_lib_depth', 'git_mode', 'report_path',
'report_name', 'report_mode', 'report_disp',
'report_colors']
#check if all options are allowed
_Validator('general_kwargs',kwargs,self._options)
#fill non chosen options with none
for option in self._options:
if not option in kwargs:
kwargs[option] = None
#initialize options with user input or default values
self.dymola_pedantic = kwargs['dymola_pedantic'] or False
self.modelica_lib_firstlevel = os.path.join(self.modelica_lib_path, kwargs['modelica_lib_firstlevel'] or '')
self.modelica_lib_depth = kwargs['modelica_lib_depth'] or 1
#initialize report attributes
self.report_name = kwargs['report_name']
self.report_path = kwargs['report_path']
self.report_mode = kwargs['report_mode']
self.report_colors = kwargs['report_colors']
self.report_disp = kwargs['report_disp']
#additional variables
self._Report = Report()
self._modelica_lib_firstlevel_mosyntax = self.modelica_lib_firstlevel.replace(os.path.dirname(self.modelica_lib_path)+'\\','').replace('\\','.')
self._logFP = os.path.join(self.modelica_lib_firstlevel,'checklog.Log')
self._ddeServer = None
self._ddeConv = None
if self._modelica_lib_firstlevel_mosyntax[-1]=='.':
self._modelica_lib_firstlevel_mosyntax = self._modelica_lib_firstlevel_mosyntax[:-1]
#PUBLIC API
###########################################################################
def execute_check(self,flag=None):
"""
Applies Dymolas checkModel() to chosen packages/models.
ARGUMENTS:
flag (string, default=None)
If flag is 'html', an HTML report is generated.
RETURNS:
A Report instance, which contains the results of the check.
"""
#delete old log file (if existing)
try:
os.remove(self._logFP)
except OSError:
pass
#open Dymola and load Library
self._establish_dymola_connection()
#check recursivley the library
self._manage_recursive_lib_check(self.modelica_lib_firstlevel,1)
#fill report element with data from logfile
self._fill_report()
#cleaning up
self._cleanUp()
if flag == 'html':
self._Report.generate_html()
return self._Report
def get_report(self):
"""
Returns the current Report instance of the DymolaMode instance
RETURNS:
Report instance
"""
return self._Report
#PRIVATE API
###########################################################################
def _establish_dymola_connection(self):
"""
Establish connection to Dymola and load chosen library.
Also parameter 'Advanced.PedanticModelica' is set.
"""
#Establish connection
self._ddeServer = dde.CreateServer();
self._ddeServer.Create("TestClient");
self._ddeConv = dde.CreateConversation(self._ddeServer);
#open Dymola
subprocess.Popen(self.dymola_path, stdin=subprocess.PIPE);
time.sleep(10);
self._ddeConv.ConnectTo("dymola", " ");
#open library
self._ddeConv.Exec("openModel(\"" + os.path.join(self.modelica_lib_path,'package.mo').replace('\\', '/') + "\")");
#activate Modelica pedantic check
self._ddeConv.Exec("Advanced.PedanticModelica={}".format(str(self.dymola_pedantic).lower()));
def _manage_recursive_lib_check(self, curPckDP, curLevel):
"""
Recursively assembling paths of all to be considered packages/models up
to the chosen level of detail.
ARGUMENTS:
curPckDP: path to a directory, which must be a package, e.g. containing
a file package.order (string)
curLevel: Level of curPckDP within the library starting from chosen
TopPackage (int)
"""
#only check, if it is a package
if not os.path.exists(os.path.join(curPckDP,'package.order')):
return
with open(os.path.join(curPckDP,'package.order')) as file:
lContent = file.read().splitlines();
#check if max LoD is reached
if self.modelica_lib_depth ==-1 or curLevel < self.modelica_lib_depth:
for elem in lContent:
#path for filesystem
pCurEl = os.path.join(curPckDP,elem)
#if it is dir/pck -> go one step further,
#if not, it is a mo file -> check
if os.path.isdir(pCurEl):
self._manage_recursive_lib_check(pCurEl,curLevel+1)
else:
self._executing_dymola_checkModel(pCurEl)
else:
for elem in lContent:
self._executing_dymola_checkModel(os.path.join(curPckDP,elem))
def _executing_dymola_checkModel(self, pCurEl):
"""
Applied Dymolas checkModel() to a given package/model.
Results are written to a .log file (this is executed within Dymola).
ARGUMENT:
pCurEl: path (using back-slashes) to current package/model that is
supposed to be checked by checkModel() (string)
"""
#path within library in modelica syntax
pmoCurEl = pCurEl.replace(os.path.dirname(self.modelica_lib_path)+'\\','').replace('\\','.')
pModel = pmoCurEl[pmoCurEl.index('.')+1:]
#replace \ with / to escape \t,\b etc
pathFP = self._logFP.replace('\\','/')
#actually applying the check and saving the result
moCode = ["if bCheck then ",
"s = getLastError(); ",
"indW1 = Modelica.Utilities.Strings.findLast(s,\"WARNING:\"); ",
"if indW1>0 then ",
"indW2 = Modelica.Utilities.Strings.findLast(s,\" warnings were issued\"); ",
"if indW2 >0 then ",
"nWarnings = Modelica.Utilities.Strings.substring(s,indW1+9,indW2-1); ",
"else ",
"nWarnings = \"1\"; "
"end if; ",
"Modelica.Utilities.Streams.print(\"{} True 0 \" + nWarnings,\"{}\"); ".format(pModel, pathFP),
"else ",
"Modelica.Utilities.Streams.print(\"{} True 0 0\",\"{}\"); ".format(pModel, pathFP),
"end if; ",
"else ",
"s = getLastError(); ",
"indE1 = Modelica.Utilities.Strings.findLast(s,\"ERROR:\"); ",
"if indE1>0 then ",
"indE2 = Modelica.Utilities.Strings.findLast(s,\" errors were found\"); ",
"if indE2 >0 then ",
"nErrors = Modelica.Utilities.Strings.substring(s,indE1+7,indE2-1); ",
"else ",
"nErrors = \"1\"; ",
"end if; ",
"indW1 = Modelica.Utilities.Strings.findLast(s,\"WARNING:\"); ",
"indW2 = Modelica.Utilities.Strings.findLast(s,\" warnings were issued\"); ",
"if indW2 >0 then ",
"nWarnings = Modelica.Utilities.Strings.substring(s,indW1+9,indW2-1); ",
"else ",
"nWarnings = \"1\"; "
"end if; ",
"Modelica.Utilities.Streams.print(\"{} False \" + nErrors + \" \" + nWarnings,\"{}\"); ".format(pModel, pathFP),
"else ",
"if Modelica.Utilities.Strings.findLast(s,\"Did not find model\")>0 then ",
"Modelica.Utilities.Streams.print(\"{} Not_found 0 0\",\"{}\"); ".format(pModel, pathFP),
"end if; ",
"end if; ",
"end if; "]
smoCode = " ".join("{}".format(row) for row in moCode)
self._ddeConv.Exec("bCheck = checkModel(\"{}\"); ".format(pmoCurEl))
self._ddeConv.Exec(smoCode)
def _fill_report(self):
"""
Report instance is filled with all available informations.
"""
#set reports attributes equal to user settings or default values
self._Report.name = self.report_name or 'report'
self._Report.path = self.report_path or self.modelica_lib_firstlevel
self._Report.mode = self.report_mode or 'full'
self._Report.disp = self.report_disp or [{'Key':'Checked Library', 'Val':self._modelica_lib_firstlevel_mosyntax},
{'Key':'Pedantic Mode', 'Val': self.dymola_pedantic},
{'Key':'Level of Detail', 'Val': self.modelica_lib_depth},
{'Key':'Branch', 'Val': self._get_branch(self.modelica_lib_path)}]
#set meta data
self._Report.meta = {'pck':self._modelica_lib_firstlevel_mosyntax,
'ped':self.dymola_pedantic,
'lod':self.modelica_lib_depth,
'git':self._get_branch(self.modelica_lib_path),
'viewport':'width=device-width, initial-scale=1.0, user-scalable=yes'}
#replace default colors with user input
if self.report_colors:
for key in self.report_colors:
self._Report.colors[key] = self.report_colors[key]
#read content from logfile
self._Report.cont = self._read_log(self._logFP)
def _get_branch(self,modelica_lib_path):
"""
Get the current branch of the git repository (if the chosen library is
actually one).
ARGUMENTS:
modelica_lib_path (string):
path of the modelica library.
RETURNS:
branch (string):
if modelica_lib_path is a git repository =>name of the current HEAD
else: empty string.
"""
currentDir = os.getcwd();
os.chdir(modelica_lib_path)
try:
s = subprocess.check_output('git branch',universal_newlines=True)
branch = s[s.find('*')+1:s.find('\n',s.find('*'))].strip()
except:
branch = 'no git'
os.chdir(currentDir)
return branch
def _read_log(self,logFP):
"""
Content of .log file is read and returned as a list of dictionaries
ARGUMENT:
logFP (string):
filepath of log file
RETURN:
lst (list of dictionaries):
actual results of the check
"""
#validate, that logfile exist
_Validator('general_filepath','logfile',logFP)
#read in logfile and save to cont
lst = []
with open(logFP) as file:
for line in file:
dic = {}
(pck,res,err,wrn) = line.split()
dic['Pck']=pck
dic['Res']=res.capitalize()
dic['Err']=err
dic['Wrn']=wrn
dic['colPck']= 'white'
dic['colRes']='{}'.format(self._Report.colors['cTrue'] if dic['Res']=='True' else self._Report.colors['cFalse'] if dic['Res']=='False' else self._Report.colors['cNF'])
dic['colErr']='{}'.format('white' if dic['Err']=='0' else self._Report.colors['cErr'])
dic['colWrn']='{}'.format('white' if dic['Wrn']=='0' else self._Report.colors['cWrn'])
lst.append(dic)
return lst
def _cleanUp(self):
"""
Several actions after finishing the library check, e.g. closing Dymola
or deleting the temporarily .log file
"""
#close dymola
self._ddeConv.Exec('exit()')
#shutdown server
self._ddeServer.Shutdown()
#delete log file
try:
os.remove(self._logFP)
except OSError:
pass
###########################################################################
#PYTHON-LIKE GETTER AND SETTER METHODS
###########################################################################
@property
def dymola_path(self):
return self.__dymola_path
@dymola_path.setter
def dymola_path(self,s):
_Validator('dymola_path',s)
self.__dymola_path = s
@property
def dymola_pedantic(self):
return self.__dymola_pedantic
@dymola_pedantic.setter
def dymola_pedantic(self,s):
_Validator('dymola_pedantic',s)
self.__dymola_pedantic = s
@property
def modelica_lib_path(self):
return self.__modelica_lib_path
@modelica_lib_path.setter
def modelica_lib_path(self,s):
_Validator('modelica_lib_path',s)
self.__modelica_lib_path = s
@property
def modelica_lib_firstlevel(self):
return self.__modelica_lib_firstlevel
@modelica_lib_firstlevel.setter
def modelica_lib_firstlevel(self,s):
_Validator('modelica_lib_firstlevel',s)
self.__modelica_lib_firstlevel = s
@property
def modelica_lib_depth(self):
return self.__modelica_lib_depth
@modelica_lib_depth.setter
def modelica_lib_depth(self,n):
_Validator('modelica_lib_depth',n)
self.__modelica_lib_depth = n
@property
def report_name(self):
return self.__report_name
@report_name.setter
def report_name(self,s):
_Validator('report_name',s)
self.__report_name = s
@property
def report_path(self):
return self.__report_path
@report_path.setter
def report_path(self,s):
_Validator('report_path',s)
self.__report_path = s
@property
def report_mode(self):
return self.__report_mode
@report_mode.setter
def report_mode(self,s):
_Validator('report_mode',s)
self.__report_mode = s
@property
def report_disp(self):
return self.__report_disp
@report_disp.setter
def report_disp(self,lst):
_Validator('report_disp',lst)
self.__report_disp = lst
@property
def report_colors(self):
return self.__report_colors
@report_colors.setter
def report_colors(self,dic):
_Validator('report_colors',dic)
self.__report_colors = dic
class Report(object):
"""
Returns a new Report instance. Each attribute is initialized as None
(except for colors).
ATTRIBUTES:
path (string, default=None):
Path to the directory, where the report file should be stored.
name (string, default=None):
Name of the report (without file extension).
disp (list of dictionaries default=None):
Key-value pairs of informations, that should be printed to the report.
Mandatory keys: 'Key', 'Val',
Example: disp = [{'Key':'Library', 'Val':Lib},
{'Key''Pedantic Mode', 'Val':False},
{'Key''Level of Detail', 'Val':1}]
cont (list of dictionaries, default=None):
Content of the report, so the actual results of the check including
color informations for each result.
Mandatory keys: 'Pck', 'Res', 'Err', 'Wrn'
Example: cont = [{'Pck':Lib, 'Res':'True', 'Err':'9', 'Wrn':'2'}]
mode (string, default=None):
Either an HTML report only contains the name of the package/model and
the result (mode='compact') or there are two more columns giving the
numbers of errors and warnings (mode='full').
meta (dictionairy, default=None):
Meta informations, which are used, if the report instance should be
compared to another instance. These informations are also stored in the
HTML report.
Mandatory keys:
'pck' (path of checked library)
'ped' (Dymola checkModel() mode)
'lod' (level of detail)
'viewport' (viewoptions for html)
colors (dictionary, default= {'cTrue':'white','cFalse':'red', 'cNF':'yellow','cErr':'red','cWrn':'yellow'})
Background colors of cells in the HTML report.
Mandatory keys:
'cTrue' (cells in the result-column, which contain the keyword 'True')
'cFalse' (cells in the result-column, which contain the keyword 'False')
'cNF' (cells in the result-column, which contain the keyword 'Not found')
'cErr' (cells in the errors-column, which have entries greater than 0)
'cWrn' (cells in the warnings-column, which have entries greater than 0)
API:
generate_html():
An HTML file is generated, which contains two tables. First table gives
an overview over chosen options, second table displays row-wise results
of checkModel() applied on some packages/models.
read_html(filepath=None):
A HTML file, which must correspond to the structure given by
generate_html(), is parsed and its content set as values of the report
instance.
If filepath is not given, this reports name and path are checked for a
HTML file.
compare_to(rep2):
Results of this report instance are compared to results of report
instance rep2. Both report instances must correspond to the same
library, the same level of detail and the same dymola checkModel()
mode.
For more details take a look at the module itsself
"""
def __init__(self, **kwargs):
#allowed options
options = 'name path disp cont mode meta colors'.split()
#check if all options are allowed
_Validator('general_kwargs', kwargs, options)
#fill non chosen options with none
for option in options:
if not option in kwargs:
kwargs[option] = None
#set default values
self.name = kwargs['name']
self.path = kwargs['path']
self.disp = kwargs['disp']
self.cont = kwargs['cont']
self.mode = kwargs['mode']
self.meta = kwargs['meta']
self.colors = kwargs['colors'] or {'cTrue':'white',
'cFalse':'red',
'cNF':'yellow',
'cErr':'red',
'cWrn':'yellow'}
#PUBLIC API
###########################################################################
def generate_html(self):
"""
Generates an HTML file, which contains the infomations given by the
report instance. Informations are displayed table-wise.
"""
conv = Converter()
conv.report_to_html(self)
def read_html(self, filepath=None):
"""
Parses a given HTML file (based on name and path) and stores available
information within the report instance.
OPTIONAL ARGUMENT:
filepath (string):
path to a report-html file. If not given, reports name and path
attribute are used.
"""
_filepath = os.path.abspath(filepath or '{}.html'.format(os.path.join(self.path,self.name)))
_Validator('general_filepath','HTML-path',_filepath)
conv = Converter()
name, path, disp, cont, meta, mode = conv.html_to_report_attributes(_filepath)
self.name = name
self.path = path
self.disp = disp
self.cont = cont
self.meta = meta
self.mode = mode
def compare_to(self,rep2):
"""
Compares this Report instance to the the instance rep2. An HTML is
generated, which have the same layout as the usual HTML report, but
uses different colors:
If a result of this Report instance is better than the one of of rep2,
the corresponding cell's background color is set to green.
If the result is worse, the cell's background color is set to red.
If there is no change, cell's background color remains white.
The new report has an additonal information, to which instance it has
been compared.
ARGUMENTS:
rep2 (Report):
A Report instance, which is compare to the self instance
RETURNS:
A HTML file is generated which displays the results of the comparison.
The filename is '[self.name]_compare.html'
"""
#ensure, that rep2 is a valid report instance
_Validator('report',rep2)
_Validator('report_compare',self,rep2)
rep1 = self
for dic1 in rep1.cont:
pck = dic1['Pck']
dic2 = next((item for item in rep2.cont if item['Pck'] == pck),None)
if dic2 == None:
#pck does not exist in rep2
continue
if not dic1['Res']==dic2['Res']:
if dic1['Res']=='True':
dic1['colRes']='green'
elif dic1['Res']=='False':
dic1['colRes']='red'
else:
dic1['colRes']='yellow'
else:
dic1['colRes']='white'
if rep1.mode=='full':
nWrn1 = int(dic1['Wrn'])
nWrn2 = int(dic2['Wrn'])
nErr1 = int(dic1['Err'])
nErr2 = int(dic2['Err'])
if nWrn1>nWrn2:
dic1['colWrn']='red'
elif nWrn1<nWrn2:
dic1['colWrn']='green'
else:
dic1['colWrn']='white'
if nErr1>nErr2:
dic1['colErr']='red'
elif nErr1<nErr2:
dic1['colErr']='green'
else:
dic1['colErr']='white'
if rep1.meta['git'] == rep2.meta['git']:
rep1.disp.append({'Key':'Compared to', 'Val': rep2.name})
else:
rep1.disp.append({'Key':'Compared to', 'Val': rep2.meta['git']})
rep1.name = '{}_compare'.format(rep1.name)
rep1.generate_html()
###########################################################################
#PYTHON-LIKE GETTER AND SETTER METHODS
###########################################################################
@property
def name(self):
return self.__name
@name.setter
def name(self,s):
_Validator('report_name',s)
self.__name = s
@property
def path(self):
return self.__path
@path.setter
def path(self,s):
_Validator('report_path',s)
self.__path = s
@property
def disp(self):
return self.__disp
@disp.setter
def disp(self,lst):
_Validator('report_disp',lst)
self.__disp = lst
@property
def cont(self):
return self.__cont
@cont.setter
def cont(self,lst):
_Validator('report_cont',lst)
self.__cont = lst
@property
def mode(self):
return self.__mode
@mode.setter
def mode(self,s):
_Validator('report_mode',s)
self.__mode = s
@property
def meta(self):
return self.__meta
@meta.setter
def meta(self,dic):
_Validator('report_meta',dic)
self.__meta = dic
class Converter(object):
"""
Returns a new Converter instance.
Instance converts content of Report instances to different file formats.
API:
report_to_html(report):
Generates a HTML file based on Report instance 'report'
html_to_report(html):
Transfers content of the HTML-file 'html' into a Report instance.
html_to_report_attributes(html):
Same as html_to_report, but does not return a Report instance but its
attributes
For more details take a look at the module itsself
"""
def __init__(self):
pass
#PUBLIC API
###########################################################################
def report_to_html(self,report):
"""
Based on contents of a report instance, an HTML file is generated.
Files location is given by reports name and path.
ARGUMENTS:
report (Report):
instance, that is converted into an HTML file.
RETURNS:
If generation was successfull, TRUE is returned.
"""
_Validator('report',report)
self._generate_html(report)
return True
def html_to_report(self,html):
"""
Contents of a HTLM file are converted into a report instance.
ARGUMENTS:
html (string):
path to a report-html, which is converted into a report instance.
RETURNS:
report (Report):
resulting instance of the conversion.
"""
name, path, disp, cont, meta, mode = self._read_html(html)
report = Report()
report.name = name
report.path = path
report.disp = disp
report.cont = cont
report.meta = meta
return report
def html_to_report_attributes(self,html):
"""
Contents of a HTLM file are converted into a report instance attributes.
ARGUMENTS:
html (string):
path to a report-html, which is converted into a report instance.
RETURNS:
name, path, disp, cont, meta, mode (Attributes of Report):
resulting instance attributes of the conversion.
"""
name, path, disp, cont, meta, mode = self._read_html(html)
return name, path, disp, cont, meta, mode
#PRIVATE API
###########################################################################
def _generate_html(self,report):
"""
Generates HTML file based on a report instance
ARGUMENTS:
report (Report):
instance, that is converted into a HTML file.
RETURNS:
An HTML file is generated. Files location is given by reports name and
path
"""
sDocType = '<!doctype html>'
sTag0 = '\n<html lang=\"de\">'
sHead = self._generate_html_head(report)
sBody = self._generate_html_body(report)
sTag1 = '\n</html>'
#full string
sHtml = "{}{}{}{}{}".format(sDocType,sTag0,sHead,sBody,sTag1)
with open('{}.html'.format(os.path.join(report.path,report.name)),'w') as file:
file.write(sHtml)
def _generate_html_head(self,report):
"""
Generates HTML <head> code as a string
ARGUMENTS:
report (Report):
instance, that is converted into a HTML file.
RETURNS:
sHead (string):
the corresponding HTML-formatted string
"""
sTag0 = '\n\t<head>'
sMeta = self._generate_html_meta(report)
sTag1 = '\n\t</head>'
sHead = '{}{}{}'.format(sTag0,sMeta,sTag1)
return sHead
def _generate_html_body(self,report):
"""
Generates HTML <body> code as a string
ARGUMENTS:
report (Report):
instance, that is converted into a HTML file.
RETURNS:
sBody (string):
the corresponding HTML-formatted string
"""
sTag0 = '\n\t<body>'
sTitle = '\n\t\t<h2>{}</h2>'.format(report.name)
sTableDisp = self._generate_html_table_disp(report)
sTableCont = self._generate_html_table_content(report)
sTag1 = '\n\t</body>'
sBody = '{}{}\n{}\n{}{}'.format(sTag0,sTitle,sTableDisp,sTableCont,sTag1)
return sBody
def _generate_html_meta(self,report):
"""
Generates HTML <meta> code as a string
ARGUMENTS:
report (Report):
instance, that is converted into a HTML file.
RETURNS:
sMeta (string):
the corresponding HTML-formatted string
"""
sTemplate = '\n\t\t<meta name=\"{}\" content=\"{}\">'
sChar = '\n\t\t<meta charset = \"utf8\">'
sRows = ''.join(sTemplate.format(key, value) for key,value in sorted(report.meta.items()))
sMeta = '{}{}'.format(sChar,sRows)
return sMeta