From 323ea928f6abe540a52c7ebf0f924e4fe496c5ee Mon Sep 17 00:00:00 2001
From: Marko Mecina <marko.mecina@univie.ac.at>
Date: Thu, 16 Mar 2023 17:44:40 +0100
Subject: [PATCH] add interactive test report function to plain test script
 generator

---
 Ccs/ccs_function_lib.py   | 14 +++++----
 Tst/json_to_barescript.py | 28 +++++++++++++++--
 Tst/tst/tst.py            | 63 +++++++++++++++++++++++++++++----------
 3 files changed, 81 insertions(+), 24 deletions(-)

diff --git a/Ccs/ccs_function_lib.py b/Ccs/ccs_function_lib.py
index 8ebfaaf..b09dbc8 100644
--- a/Ccs/ccs_function_lib.py
+++ b/Ccs/ccs_function_lib.py
@@ -4854,12 +4854,13 @@ class TestReport:
 
         self.report[self.step_rowid[str(step)]][3] = result
 
-    def export(self, reportdir=None):
-        if reportdir is None:
-            reportfile = self.specfile.replace('.csv_PIPE', '-TR-{:03d}.csv_PIPE'.format(self.version)).replace('/testspec/', '/testrep/')
-        else:
-            reportdir += '/' if not reportdir.endswith('/') else ''
-            reportfile = reportdir + self.specfile.split('/')[-1].replace('.csv_PIPE', '-TR-{:03d}.csv_PIPE'.format(self.version))
+    def export(self, reportdir=None, reportfile=None):
+        if reportfile is None:
+            if reportdir is None:
+                reportfile = self.specfile.replace('.csv_PIPE', '-TR-{:03d}.csv_PIPE'.format(self.version)).replace('/testspec/', '/testrep/')
+            else:
+                reportdir += '/' if not reportdir.endswith('/') else ''
+                reportfile = reportdir + self.specfile.split('/')[-1].replace('.csv_PIPE', '-TR-{:03d}.csv_PIPE'.format(self.version))
 
         self.report[1][3] += ' TR-{:03d}, MIB v{}'.format(self.version, self.idb_version)
         self.report[2][3] = time.strftime('%Y-%m-%d')
@@ -4869,6 +4870,7 @@ class TestReport:
         with open(reportfile, 'w') as fd:
             fd.write(buf + '\n')
         logger.info('Report written to {}.'.format(reportfile))
+        print('Report written to {}.'.format(reportfile))
 
 
 class TestReportGUI(Gtk.MessageDialog):
diff --git a/Tst/json_to_barescript.py b/Tst/json_to_barescript.py
index 0946c95..cf9c8bb 100755
--- a/Tst/json_to_barescript.py
+++ b/Tst/json_to_barescript.py
@@ -14,7 +14,7 @@ import json
 import sys
 
 
-def run(jfile, outfile):
+def run(jfile, outfile, reportfunc=False, specfile=None):
 
     if os.path.isfile(jfile):
         data = json.load(open(jfile, 'r'))
@@ -34,18 +34,37 @@ def run(jfile, outfile):
     script += '#--------------------------------------------\n\n'
     script += '# COMMENT: {}\n\n\n'.format(data['_comment'].replace('\n', '\n# '))
 
+    if reportfunc:
+        if specfile is None:
+            specfile = '{}-TS-{}.csv_PIPE'.format(data['_name'], data['_spec_version'])
+        script += 'specfile = "{}"\n'.format(specfile)
+        script += 'rep_version = 1\n'
+        script += 'mib_version = "3.4"\n'
+        script += 'ask_tc_exec = True\n'
+        script += 'report = cfl.TestReport(specfile, rep_version, mib_version, gui=True)\n\n'
+
     script += '# Precond.\n# {}\n'.format(data['_precon_descr'])
     # script += '{}\n\n\n'.format(data['_precon_code'].strip())  # Add the precondition code
 
     for step in data['sequences'][0]['steps']:
         comment = '# COMMENT: {}\n'.format(step['_step_comment'].strip()) if step['_step_comment'] != '' else ''
 
+        if reportfunc:
+            step_tag = 'Step {}'.format(step['_step_number'])
+            exec_step = 'report.execute_step("{}", ask=ask_tc_exec)\n'.format(step_tag)
+            verif_step = 'report.verify_step("{}")\n'.format(step_tag)
+        else:
+            exec_step = ''
+            verif_step = ''
+
         txt = '# STEP {}\n' \
               '# {}\n' \
+              '{}' \
               '{}\n' \
-              '# VERIFICATION: {}\n{}\n\n'.format(step['_step_number'], step['_description'].strip(),
+              '# VERIFICATION: {}\n{}{}\n\n'.format(step['_step_number'], step['_description'].strip(), exec_step,
                                                   step['_command_code'].strip(),
                                                   step['_verification_description'].strip(),
+                                                  verif_step,
                                                   # step['_verification_code'].strip(), # Add verification code
                                                   comment)
 
@@ -54,6 +73,9 @@ def run(jfile, outfile):
     script += '# Postcond.\n# {}\n'.format(data['_postcon_descr'])
     # script += data['_postcon_code'].strip()  # Add the postcondition code
 
+    if reportfunc:
+        script += '\nreport.export()\n\n'
+
     if outfile[-1] == '/':  # If path is given not the actual filename
         outfile = outfile + data['_name'] + '-TS' + '-'.join(data['_spec_version']) + '.py'
 
@@ -70,4 +92,4 @@ if __name__ == '__main__':
         outputfile = os.getcwd() + '/'
         #outputfile = '/'.join(json_file_path[:-len(json_file_path.split('/')[-1])-1]) + '/'  # This would take the json File path
 
-    run(json_file_path, outputfile)
+    run(json_file_path, outputfile, reportfunc=False)
diff --git a/Tst/tst/tst.py b/Tst/tst/tst.py
index 5106f09..70a0c0a 100755
--- a/Tst/tst/tst.py
+++ b/Tst/tst/tst.py
@@ -886,13 +886,13 @@ class TstAppWindow(Gtk.ApplicationWindow):
         """
         Generates a compact python test file without all the additional stuff from on_generate_scripts
         """
-        dialog = Gtk.FileChooserDialog(
-            title="Save script as", parent=self, action=Gtk.FileChooserAction.SAVE)
-        dialog.add_buttons(
-            Gtk.STOCK_CANCEL,
-            Gtk.ResponseType.CANCEL,
-            Gtk.STOCK_SAVE,
-            Gtk.ResponseType.OK, )
+        # dialog = Gtk.FileChooserDialog(
+        #     title="Save script as", parent=self, action=Gtk.FileChooserAction.SAVE)
+        # dialog.add_buttons(
+        #     Gtk.STOCK_CANCEL,
+        #     Gtk.ResponseType.CANCEL,
+        #     Gtk.STOCK_SAVE,
+        #     Gtk.ResponseType.OK, )
 
         if self.current_test_instance():
             # current_json_filename = self.current_test_instance().filename
@@ -901,6 +901,8 @@ class TstAppWindow(Gtk.ApplicationWindow):
             logger.error('Small Script can not be generated without JSON file')
             return
 
+        dialog = ScriptExportDialog()
+
         outfile_basic = '{}-TS-{}.py'.format(current_model.name, current_model.spec_version)
         dialog.set_current_name(outfile_basic)
         dialog.set_current_folder(cfg.get('tst-history', 'last-folder'))
@@ -908,17 +910,13 @@ class TstAppWindow(Gtk.ApplicationWindow):
 
         response = dialog.run()
         if response == Gtk.ResponseType.OK:
-            # while response == Gtk.ResponseType.OK:
-            #     if os.path.exists(dialog.get_filename()):
-            #         if not self.existing_file_dialog(dialog.get_filename()):
-            #             response = dialog.run()
-            #             continue
-            json_to_barescript.run(current_model.encode_to_json(), dialog.get_filename())
+            report = dialog.report.get_active()
+            spec = dialog.csvspec.get_filename()
+
+            json_to_barescript.run(current_model.encode_to_json(), dialog.get_filename(), reportfunc=report, specfile=spec)
             cfg.save_option_to_file('tst-history', 'last-folder', dialog.get_current_folder())
-            # break
 
         dialog.destroy()
-        return
 
     def on_generate_csv(self, *args):
         """
@@ -1271,5 +1269,40 @@ def run():
     applica.run()
 
 
+class ScriptExportDialog(Gtk.FileChooserDialog):
+
+    def __init__(self, *args, **kwargs):
+        super().__init__(title="Save script as", action=Gtk.FileChooserAction.SAVE)
+        self.add_buttons(
+            Gtk.STOCK_CANCEL,
+            Gtk.ResponseType.CANCEL,
+            Gtk.STOCK_SAVE,
+            Gtk.ResponseType.OK, )
+
+        area = self.get_content_area()
+        hbox = Gtk.HBox()
+        hbox.set_border_width(10)
+
+        self.report = Gtk.CheckButton.new_with_label('Reporting')
+        self.report.set_tooltip_text('Add interactive reporting')
+        self.report.connect('toggled', self.check_report)
+
+        self.csvspec = Gtk.FileChooserButton()
+        self.csvspec.set_tooltip_text('Select corresponding CSV spec file')
+        self.csvspec.set_sensitive(False)
+
+        hbox.pack_start(self.report, 0, 0, 0)
+        hbox.pack_start(self.csvspec, 1, 1, 0)
+        area.add(hbox)
+
+        self.show_all()
+
+    def check_report(self, widget, *args):
+        if widget.get_active():
+            self.csvspec.set_sensitive(True)
+        else:
+            self.csvspec.set_sensitive(False)
+
+
 if __name__ == '__main__':
     run()
-- 
GitLab