livecode urlProgress for mobile download file - livecode

i am using the bellow code to download a file from my ftp server.The file is downloaded on Mobile devices.
i am try to use a progress bar to show up the amount of data downloaded
The problem is always i get "cached".
this is my code
constant FTPHOST = "myIp"
constant FTPUSER = "user"
constant FTPPASS = "password"
global sDownloadStart
on mouseUp
put "test.zip" into tFileName
put "ftp://" & FTPUSER & ":" & FTPPASS & "#" & FTPHOST & "/" & tFileName into pUrl
-- start the download process, telling Rev to call the "downloadComplete" handler when finished
Load URL pUrl with message "urlProgress"
set the startvalue of sb "progressbar" to 0
end mouseUp
on urlProgress pURL, pStatus, pBytesDone, pBytesTotal
put pStatus into fld "pf1"
switch item 1 of pStatus
      case "loading"
set the thumbPosition of sb "Progressbar" to round((pBytesDone / pBytesTotal) * 100)
         put the round of (item 1 of pBytesDone / 1024)&& "KB Downloaded" into field "status"
         break
      case "cached"
     --   if pStatus is "cached" then
-- work out a file name for saving this file to the desktop
set the itemDel to slash
put "binfile:" & specialfolderpath("documents") & "/test.zip" into myPath
//put "data.file" into tFileName
put url pUrl into url myPath
answer "Download completed" with ok
-- to save memory, now unload the URL from memory
-- this also means that if you want to run the test again, it does not just use a cached version
unload pURL
--end if
         break
      case "error"
      if pStatus = "error" or pStatus = "timeout" then
answer error "The file could not be downloaded." with "ok"
end if
         break
     
   end switch
end urlProgress

Your urlProgresshandler is called after the loading of the URL finishes. To get a different status, you have to call another message or call the message in a different way, e.g.
on mouseUp
//delete URL "binfile:" & specialfolderpath("documents") & "/data.file"
put "data.file" into tFileName
put "ftp://" & FTPUSER & ":" & FTPPASS & "#" & FTPHOST & "/" & tFileName into pUrl
-- start the download process, telling Rev to call the "downloadComplete" handler when finished
// the callback message has only 2 parameters: url and urlStatus
Load URL pUrl with message "downloadComplete"
send "urlProgress pUrl" to me in 200 millisecs
end mouseUp
on urlProgress pUrl //,pStatus, pMessage,pbytesR,pbytesT
put urlStatus(pUrl) into pStatus
if item 1 of pUrl is "loading" then
put item 2 of pStatus into pBytesR
put item 3 of pStatus into pbytesT
put item 1 of pStatus into pStatus
send "urlProgress pUrl" to me in 200 millisecs
end if
end urlProgress
on downloadComplete theUrl,theUrlStatus
if theUrlStatus is "cached" then
-- work out a file name for saving this file to the desktop
set the itemDel to slash
put "binfile:" & specialfolderpath("documents") & "/data.file" into myPath
put "data.file" into tFileName
put url theUrl into url myPath
answer "Download completed" with ok
-- to save memory, now unload the URL from memory
-- this also means that if you want to run the test again, it does not just use a cached version
unload pURL
end if
-- check if there was a problem with the download
if pStatus = "error" or pStatus = "timeout" then
put libUrlErrodData(theUrl) into myErr
answer error "The file could not be downloaded."&& myErr with "ok"
end if
end downloadComplete
Let me know if this works (it should). If not, I'll have another look.

Related

Converting Dictionary to Yaml Object - not preserving quotations

I am trying to dynamically create stubby.yml configuration file. I have a template yaml file as follows:
resolution_type: GETDNS_RESOLUTION_STUB
dns_transport_list:
  - GETDNS_TRANSPORT_TLS
tls_authentication: GETDNS_AUTHENTICATION_REQUIRED
tls_query_padding_blocksize: 128
edns_client_subnet_private : 1
round_robin_upstreams: 1
idle_timeout: 10000
listen_addresses:
  - 10.7.0.1
appdata_dir: "/var/cache/stubby"
I am trying to append this native yaml configuration
upstream_recursive_servers:
  - address_data: 185.228.168.168
    tls_auth_name: "family-filter-dns.cleanbrowsing.org"
  - address_data: 185.228.169.168
    tls_auth_name: "family-filter-dns.cleanbrowsing.org"
The stubby configuration will not work without the tls_auth_name values being wrapped in quotations, and also appdata_dir. Quotations are being stripped and i cannot figure out how to dump the yaml without the " being stripped. Even chatgpt is struggling with this one!
def get_dns_config(dns_option) -> dict:
    # return stubby.yml configuration
    with open('dns.yml', 'r') as f:
        data = yaml.safe_load(f)
    with open('dns_template.yml', 'r') as f:
        template = yaml.safe_load(f)
       
    template['upstream_recursive_servers'] = data[dns_option]['servers']
    logging.debug(json.dumps(template, indent=4))
    logging.debug(yaml.safe_dump(template, default_flow_style=False,indent=2))
    return yaml.safe_dump(template, default_flow_style=False,indent=2)
This is the dict after adding the upstream_recursive_servers value:
{
"resolution_type": "GETDNS_RESOLUTION_STUB",
"dns_transport_list": [
"GETDNS_TRANSPORT_TLS"
],
"tls_authentication": "GETDNS_AUTHENTICATION_REQUIRED",
"tls_query_padding_blocksize": 128,
"edns_client_subnet_private": 1,
"round_robin_upstreams": 1,
"idle_timeout": 10000,
"listen_addresses": [
"10.7.0.1"
],
"appdata_dir": "/var/cache/stubby",
"upstream_recursive_servers": [
{
"address_data": "185.228.168.168",
"tls_auth_name": "family-filter-dns.cleanbrowsing.org"
},
{
"address_data": "185.228.169.168",
"tls_auth_name": "family-filter-dns.cleanbrowsing.org"
}
]
}
This is the result from yaml.safe_load()
appdata_dir: /var/cache/stubby
dns_transport_list:
- GETDNS_TRANSPORT_TLS
edns_client_subnet_private: 1
idle_timeout: 10000
listen_addresses:
- 10.7.0.1
resolution_type: GETDNS_RESOLUTION_STUB
round_robin_upstreams: 1
tls_authentication: GETDNS_AUTHENTICATION_REQUIRED
tls_query_padding_blocksize: 128
upstream_recursive_servers:
- address_data: 185.228.168.168
tls_auth_name: family-filter-dns.cleanbrowsing.org
- address_data: 185.228.169.168
tls_auth_name: family-filter-dns.cleanbrowsing.org
Apologies for the long post - didn't want to miss anything out.
In the YAML file the record
"family-filter-dns.cleanbrowsing.org"
denotes the string family-filter-dns.cleanbrowsing.org without quotes: the quotes at the beginning and at the end are part of the representation, but aren't a part of the data.
For make the record to denote the string "family-filter-dns.cleanbrowsing.org" (with quotes) you could write whole that string inside single quotes:
'"family-filter-dns.cleanbrowsing.org"'
That way is described in YAML specification in the Example 2.17.
Alternatively, you may write whole that string inside double quotes, but escape the inner double quotes:
"\"family-filter-dns.cleanbrowsing.org\""

How to change the default download directory in the current running chrome driver session

How do i change the default download directory in the current running driver session? as i need to change the download directory many times to store particular file at particular location using 'for' loop.
below are the code which the tried to change the default directory of already running chrome driver session:
os.getcwd()
os.chdir("C:\\Site_tracker\\Output")
direc = ['S1_2g3g4g', 'S2_2g3g4g','S3_2g3g4g']
for i in direc:
if not os.path.exists(i):
os.makedirs(i)
download_path=os.path.abspath(i)
print(download_path)
chr_Options.add_experimental_option('prefs', {
"download.default_directory": "download_path", #Change default directory for downloads
"download.prompt_for_download": False, #To auto download the file
"download.directory_upgrade": True,
"plugins.always_open_pdf_externally": True})
driver1=webdriver.Chrome(chrome_options=chr_Options)
Download directory is usually set when you create a browser instance by option setting
"download.default_directory"
like described here: How to use chrome webdriver in selenium to download files in python?
or as you have in snippet.
If you want to store files to different directories during one session, you have some choices, but the one, which I choose, because in same task I also need to change filenames, was store file to local /tmp directory, rename and move it to final place.
import os
import shutil
CWD = os.getcwd()
TMP_DIR = CWD + "/tmpf"        # directly downloaded files
if not os.path.isdir(TMP_DIR):
    os.mkdir(TMP_DIR)
DWN_DIR = CWD + '/downloaded_files'   # renamed files from TMP_DIR
if not os.path.isdir(DWN_DIR):
    os.mkdir(DWN_DIR)
in prefs:
"download.default_directory" : TMP_DIR,
then
file_to_download.click()
old_name = os.listdir("./tmpf")[0]
old_file_name = TMP_DIR + "/" + old_name
new_file_name = DWN_DIR + '/' +  "SPECIFIC_Prefix_" + old_name.lower().replace(" ","_")
shutil.move(old_file_name, new_file_name)
print("File downloaded and moved to: ", new_file_name)

How to write not condition in alert manager route matches?

How to write not condition in alert manager route matches?
I want to execute this condition only when severity is not critical..
routes
- match_re:
severity: ^(?!critical)
receiver: teams-channel-webhook-high-priority
I tried the above regex condition .But it didnt work.
I also tried with
not_match_re:
severity: critical
Even that didnt work.
Answer:
You can make a nested tree of routes, which in effect gives you an "if ... then ... else ..." capability.
 
routes:
    - ... something to do always
      continue: true
    - match:
        severity: critical
      routes:
        - ... things to do when critical
        - ...
    - ... things to do when not critical
    - ...
Leaving out the "match" condition entirely makes a rule match always.
Note that "continue: true" carries on to the next rule after a match, but only at the same level.  It will only fall out to the parent ruleset if no matches occur.
Or of course, you can explicitly match all non-critical severities e.g. match_re: severity: 'debug|informational|warning'
match and match_re have been deprecated in route in favor of using matcher
matchers takes a list of conditions (and) and supports regex match =~ and NOT match !~ operators.
route:
# root route
routes:
- receiver: recvA
matchers:
- severity!~"^critical$"
- receiver: recvB
# route:receiverB with no matchers will always match if the previous routes don't

VBA read large Linux-formatted text file starting from specific line without reading whole file into memory

I have a large Linux-formatted (i.e. linefeed character for a new line) text file that is a "status" file for a program as it runs. This file is updated while the program is running. It outputs some useful messages and periodic header information, but also lines of numerical status data separated by spaces. Because it is a piece of commercial software (Abaqus /Explicit), I can't do anything to modify how it writes to this status file.
I wrote a VBA script awhile back that opens the file, reads it in as a whole via "Input$", splits the file into lines via "Split(Data, vbLF)", and parses each line to extract the numerical status data and place it into an Excel spreadsheet for me to view and analyze. The problem is that, as the program continues to run, this file gets larger and larger to the point that reading the whole file into Excel is becoming impractical.
I've been trying to figure out a quick way to read the file starting from the line I left off on, without reading the entire thing to memory. I tried to save EOF() to a "helper" cell on the spreadsheet and use that with "Seek" and "Line Input" to jump right to the spot I left off on, but that won't work because "Line Input" doesn't recognize the linefeed character as a new line, only carriage return or carriage return-linefeed.
I spent some time going through other posts and it seemed like the only other solutions required reading the whole file in. Does anyone have any ideas as to how this could be done WITHOUT reading the whole file in?
Thanks for your time!
'perhaps this could be modified for new start
Sub read_bookmark()
Dim linein, tline, endmark, linevalid, filelen, fread
Dim chx As Byte
Dim fpath, mes, a
On Error GoTo ErrHand
mes = "Enter path & filename of Bookmark import file."
'fpath = InputBox(mes, "", "c:\temp\bookmarks_12_8_18.html")
fpath = "c:\temp\test.txt"
If Len(fpath) = 0 Or (Len(Dir(fpath)) = 0) Then
MsgBox ("File not found. Program canceled")
End
End If
tline = ""
linein = ""
endmark = False
linevalid = False
Open fpath For Binary Access Read As #1
filelen = LOF(1) ' Get length of file.
For fread = 1 To filelen
Get #1, , chx
If chx = 13 Or chx = 10 Then
endmark = True
ElseIf endmark = True Then 'wait till no more endmarks
endmark = False
tline = linein
linevalid = True
linein = Chr(chx) 'keep chr after endmarks
Else
linein = linein + Chr(chx)
End If
If linevalid = True Then
'proc tline
tline = ""
linevalid = False
End If
Next
'proc last linein chrs
MsgBox ("Processing Complete")
Exit Sub
ErrHand: ' Error-handling routine.
Close #1
MsgBox "Error in HTML read " + Error(Err)
End
End Sub

How to use SoapUI/Groovy to add Test Results to Quality Center Test Run

I had a scenario where I need to add my test results from a SoapUI test case to a related test case in HP Quality Center. How could I go about doing this with Groovy.
Quality Center offers an OTA API to interface with it; however, it is written to use the Microsoft COM structure which Java/Groovy has no native way to consume. Lucky, there is a Groovy library, Scriptom, that allows Groovy to consume COM interfaces.
After getting every setup, this is the sample code that I came up with:
import org.codehaus.groovy.scriptom.*
def tstCaseName = "NAME_OF_TESTCASE"
tstCaseName = tstCaseName.replaceAll(/[ ]/) { match ->
"*"
}
Scriptom.inApartment
{
// Create an entry point for QC
def tdc = new ActiveXObject ('TDApiOle80.TDConnection')
// Connect to QC, Login with Credentials, connect to Project
tdc.InitConnectionEx('http://qc.example.com/qcbin')
tdc.Login('USER_NAME', 'PASSWORD')
tdc.Connect('DOMAIN_NAME','PROJECT_NAME')
// Find the set of tests in the Test Plan
tsFolder = tdc.TestSetTreeManager.NodeByPath('Root\\PATH\\TO\\TEST\\CALENDAR\\Spaces are allowed')
tsList = tsFolder.FindTestSets('NAME_OF_TEST_CALENDAR')
tsObject = tsList.Item(1)
// Get the list of TestCases in the Test Plan and filter it down to the one Test Case we are interested in
TSTestFact = tsObject.TSTestFactory
tstSetFilter = TSTestFact.Filter
tstSetFilter.Filter["TS_NAME"] = '*' + tstCaseName
TestSetTestsList = TSTestFact.NewList(tstSetFilter.Text)
tsInstance = TestSetTestsList.Item(1)
// Create a new Test Run
newRun= tsInstance.RunFactory.AddItem('Run_Auto')
newRun.Status = 'Not Completed'
newRun.Post()
newRun.CopyDesignSteps()
newRun.Post()
// Populate Auto Run Test step Data
def tsStepData = new Object[3]
tsStepData[0]='Auto Data'
tsStepData[1]='Not Completed'
tsStepData[2]='Results from Automated Test'
// Create new Test Step in the run with our Auto Run Data
tsSteps = newRun.StepFactory.AddItem(tsStepData)
tsSteps.Field['ST_ACTUAL'] = 'These are the actual results from my test!!'
tsSteps.post()
}
I had issues with the scriptom and being new to Groovy but having experience with Quality Center I wrote a tear down script for my SoapUI test that writes my results to a flat file and then I use the VBScript to pull the data in.
These scripts use hard coded values but hopefully will get you started:
VAPI-XP Script - http://ryanoglesby.net/2013/08/23/executing-soapui-from-quality-center-part-1/
'*******************************************************************
'Debug, CurrentTestSet, CurrentTest, CurrentRun
'Debug, CurrentTestSet, CurrentTSTest, CurrentRun
'**************************************************************************
Sub Test_Main(Debug, CurrentTestSet, CurrentTest, CurrentRun )
' *** VBScript Limitation ! ***
' "On Error Resume Next" statement suppresses run-time script errors.
' To handle run-time error in a right way, you need to put "If Err.Number <> 0 Then"
' after each line of code that can cause such a run-time error.
On Error Resume Next
'Clear output window
TDOutput.Clear
'**************************************************************************
' Define the path for SOAPUI executable bat file and Project xml
' Project xml contains the test case(s) that need to be executed
'**************************************************************************
Dim trPath 'Path to test runner bat file
Dim soapResults 'Result file generated by SoapUI Groovy Script
Dim projFP 'SoapUI Project File Path
Dim spath 'Result File - Currently not using
Dim tf 'Test Factory Object
Dim ts 'Test ID
Dim TSuite 'SoapUI Test Suite Name
Dim Tcase 'SoapUI Test Case Name
Dim resultsP 'SoapUI output Report Location - Currently Not using
projFP = "C:\SOME\FILE\PATH\soapui-project.xml"
spath = "C:\File.txt"
trPath = "C:\program files\SmartBear\SoapUI-Pro-4.5.2\bin\testrunner.bat"
soapResults = "C:\Groovy_Report\test1.txt"
'Strings for SoapUI Execution
TSuite="SOAPUI_TESTSUITE_NAME"
Tcase="SOAPUI_TESTCASE_NAME"
resultsP="C:\SoapResults\" & Tcase
Set tf = TDConnection.TestFactory
Set ts = tf.Item(Field("TS_TEST_ID"))
'**************************************************************************
' Invoke SOAPUI and execute the selected project
'**************************************************************************
invokeSOAPUIClient trPath, projFP, TSuite, Tcase, resultsP, CurrentTest, CurrentRun
'**************************************************************************
' Get the Results from the text file in to Run Steps of the test case
'**************************************************************************
'wait 1 second to allow for larger files to complete writing
TDOutput.Print "Start Wait 10"
XTools.Sleep 1000
TDOutput.Print "END Wait 10"
'Get Result file and write to run steps
getResultsToQC CurrentRun, soapResults
'**************************************************************************
' handle run-time errors
'**************************************************************************
If Not Debug Then
If Err.Number <> 0 Then
TDOutput.Print "Run-time error - Execute SOAPUI:Enter SuB - [" & Err.Number & "] : " & Err.Description
CurrentRun.Status = "Failed"
CurrentTest.Status = "Failed"
Else
CurrentRun.Status = "Passed" 'Need Function here to determine if all steps passed
CurrentTest.Status = "Passed" 'Need Function here to determine if all steps passed
End If
End If
End Sub
'**************************************************************************
' Sub for executing SOAPUI with the selected project
'**************************************************************************
' soapuiTestrunnerPath: TestRunner .bat file
' projectLocation: Project file location
'**************************************************************************
Sub invokeSOAPUIClient(soapuiTestrunnerPath, projectLocation, TSuite, Tcase, resultsP, CurrentTest, CurrentRun)
'**************************************************************************
' Execute SOAPUI from the command line
' Output Test Values for reference - Not Required
'**************************************************************************
TDOutput.Print "TSuite: " & TSuite
TDOutput.Print "Tcase: " & Tcase
TDOutput.Print "resultsP: " & resultsP
set fileSystem = CreateObject("Scripting.FileSystemObject")
'**************************************************************************
' Raise error if SOAPUI is not installed in the host where program is
' runned or if the path of executable bat file provided is not correct
'**************************************************************************
If ( not fileSystem.FileExists(soapuiTestrunnerPath)) then
Err.Raise 8
Err.Description = "soapUI testrunner not found: " + soapuiTestrunnerPath
End if
'**************************************************************************
'args will be the options that you wish to pass to the TestRunner
'for a full list of options call the test runner from the command prompt with
'no options
'**************************************************************************
Dim args
'args = "-s" & chr(34) & TSuite & chr(34) & " -c" & chr(34) & TCase & chr(34) & " -Drpath=" & resultsP & " -r -a -I "& chr(34) & projectLocation & chr(34) &""
args = "-s" & TSuite & " -c" & TCase & " -M -j -F XML -R test.xml -f " & resultsP & " -r -g -A -I "& chr(34) & projectLocation & chr(34) &""
XTools.run soapuiTestrunnerPath, args, -1, true
End Sub
'**************************************************************************
' Sub for Adding Results to QC - Parent to addRunData() function
' function will parse the result file generated by SoapUI Groovy Script &
' add the run details for the Soap UI test to the QC run
'**************************************************************************
' sFile: File path to Groovy Script Results "C:\Groovy_Report\test1.txt"
' Currently this value is HARD CODED
'**************************************************************************
sub getResultsToQC(CurrentRun, sFile)
Set objFS = CreateObject("Scripting.FileSystemObject")
'Create object for result file
Set objFile = objFS.GetFile(sFile)
'OPen Stream to read in file
Set ts = objFile.OpenAsTextStream(1,-2)
'Loop through file line by line
Do Until ts.AtEndOfStream
'Create string value for current line
strLine = ts.ReadLine
'TDOutput.Print strLine
'Split values based on delimiter (Set in groovy Script)
ArrSplit=Split(strLine, "|")
size = Ubound(ArrSplit)
'Determine action for array values
'Size = 6 is a report value that will have pass/fail
'Size <> 6 is a info value and will have status = N/A
if(size=6) Then
'StepName
sStepName = ArrSplit(1) & "-" & ArrSplit(2)
'Clean Step Status and determine pass/fail
sSplit = Split(ArrSplit(4),":")
sValue = Trim(sSplit(1))
if(sValue="VALID")Then
sStatus = "Passed"
Elseif (sValue="FAILED") then
sStatus = "Failed"
Else
sStatus = "N\A"
End If
'Step Description
sDescription = ArrSplit(5)
'Step Expected
sExpected = ArrSplit(3)
'Step Actual
sActual = Trim(ArrSplit(6))
'Add run result to current execution run
addRunData CurrentRun, sStepName, sStatus, sDescription, sExpected, sActual
else
'Added in case other options arise in the future
if(Trim(ArrSplit(0)) = "INFO") Then
sStepName = "INFO - " & ArrSplit(1)
sStatus = "N/A"
sDescription = ArrSplit(1)
sExpected = "N/A"
sActual = ArrSplit(2)
addRunData CurrentRun, sStepName, sStatus, sDescription, sExpected, sActual
End If
End if
Loop
ts.Close
end sub
'**************************************************************************
' Sub for adding Test Steps to the current run
' function will add the run details for the Soap UI test to the QC run
'**************************************************************************
' sStepName: Passed from getResultsToQC - String to display the step name
' sStatus: Passed from getResultsToQC - String to determine step status
' sDescription: Passed from getResultsToQC - String to describe step
' sExpected: Passed from getResultsToQC - String to show expected value
' sActual: Passed from getResultsToQC - String to show actual value
'**************************************************************************
Sub addRunData(CurrentRun, sStepName, sStatus, sDescription, sExpected, sActual )
Dim objRun
Set objRun = CurrentRun
'Create Step object and add values to Object array
Set objStep = objRun.StepFactory.AddItem(null)
objStep.Field("ST_STEP_NAME")= sStepName
objStep.Field("ST_STATUS") = sStatus
objStep.Field("ST_DESCRIPTION") = sDescription
objStep.Field("ST_EXPECTED") = sExpected
objStep.Field("ST_ACTUAL") = sActual
objStep.Post
Set objStep = Nothing
end sub
Groovy SoapUI TearDown Script - http://ryanoglesby.net/2013/08/28/executing-soapui-from-quality-center-part-2-groovy-teardown-script/
import jxl.*
import jxl.write.*
import java.lang.*
import com.eviware.soapui.support.XmlHolder
//*********************************************************************
//Define Array to hold reporting data
//*********************************************************************
def reportInfo = []
//*********************************************************************
//Define test name
//*********************************************************************
def testName= testRunner.testCase.name.toString()
def fpath = context.expand( '${projectDir}' )
def tcase = testRunner.testCase
//*********************************************************************
//Get number of Test steps
//*********************************************************************
def size = testRunner.testCase.getTestStepCount();
//*********************************************************************
//loop through test steps
//*********************************************************************
for(int i = 0; i<size; i++){
//*********************************************************************
//get Step Name
//*********************************************************************
name = tcase.getTestStepAt(i).getName()
//*********************************************************************
//create test step object
//*********************************************************************
testStep = testRunner.getTestCase().getTestStepByName(“$name”)
//*********************************************************************
//Get test step type
//*********************************************************************
def stepType = testStep.config.type
//*********************************************************************
//Determine course of action for each step type
//*********************************************************************
if(stepType==”datasink”){
//*********************************************************************
//Info Step as we won’t be running assertions on this step type
//Data will be added to reportInfo Array
//*********************************************************************
def info = “INFO | Data Sink Step | “+name
reportInfo << info
}else if(stepType==”groovy”){
//*********************************************************************
//Info Step as we won’t be running assertions on this step type
//Data will be added to reportInfo Array
//*********************************************************************
def info = “INFO | Groovy Script Step | “+name
reportInfo << info
}else if(stepType==”request”){
//*********************************************************************
//Report Step as we WILL be running assertions on this step type
//Data will be added to reportInfo Array
//*********************************************************************
//Create List of Assertion names, Counter == alist Size, and
//Assertion status
//*********************************************************************
def assertionNameList = testStep.getAssertionList().name
def counter = assertionNameList.size()
def assertionStatus = testStep.getAssertionList()
//*********************************************************************
//Loop through assertionList
//*********************************************************************
for(j=0;j<counter;j++)
{
def iAssertionName = assertionNameList[j]
def iAssertionStatus = testStep.getAssertionAt(j).getStatus().toString()
def tstep = testStep.getName()
if(iAssertionName==”SOAP Response”){
//*********************************************************************
//If Assertion type is SOAP Response Capture Step Status and XML
//*********************************************************************
def response = context.expand( ‘${‘+tstep+’#Response}’ )
response = response.replace(“\n”, “”)
response = response.replace(“\r”, “”)
def type = testStep.getAssertionAt(j).config.type
def reportString = “Report | ” + tstep + ” | ” + iAssertionName + ” | Expected Success Response |” + “Status: ” + iAssertionStatus + ” | ” + type + ” | ” + response
log.info reportString
reportInfo << reportString
}else{
//*********************************************************************
//If Assertion type is NOT SOAP Response Capture:
// Step Status
// Expected Value
// Assertion Type
// Actual (If Error=Error Message Else = Expected)
//*********************************************************************
def expect = testStep.getAssertionAt(j).expectedContent
def expectedValue = context.expand(expect)
def gStatus = testStep.getAssertionAt(j).status
gStatus = gStatus.toString()
def gAssert = testStep.getAssertionAt(j)
def gType = testStep.getAssertionAt(j).config.type
if(gStatus!=’FAILED’){
def reportString = “Report | ” + tstep + ” | ” + iAssertionName + ” | Expected: ” + expectedValue + “|” + ” Status: ” + gStatus + “|” + ” Type: ” + gType + “|” + expectedValue
log.info reportString
reportInfo << reportString
}else{
for( e in testStep.getAssertionAt(j).errors ){
def reportString = “Report | ” + tstep + ” | ” + iAssertionName + ” | Expected: ” + expectedValue + “|” + ” Status: ” + gStatus + “|” + ” Type: ” + gType + “|” + ” Error [" + e.message + "]”
log.info reportString
reportInfo << reportString
}
}
}
}
}else{
//*********************************************************************
//We will want to log a message for this step
//for currently unhandled step types
//*********************************************************************
}
}
//*********************************************************************
//capture execution time
//*********************************************************************
def gTimeInfo = “INFO | TIME | “+testRunner.getTimeTaken()
reportInfo << gTimeInfo
log.info gTimeInfo
//*********************************************************************
//create report for test
//*********************************************************************
//Folder within directory to save results to. If folder does not exist
//we will create it
//*********************************************************************
def folder = “Groovy_Report”
//*********************************************************************
//Directory to place create folder in or location of Folder
//*********************************************************************
def dir = “c:/”
//*********************************************************************
//Define and execute folder creation method
//*********************************************************************
def c
c = createFolder(dir,folder)
//*********************************************************************
//Define test file name and create report file
//*********************************************************************
def fName = “test1″
createfile(c,”fName”,”.txt”,reportInfo)
//*********************************************************************
//Create File Method
//*********************************************************************
//Input:
// dir: root folder directory
// filenm: name of file to be created minus the extension
// ext: file extension to be used
// info: array of strings containing your file data
//*********************************************************************
public void createfile(def dir, def filenm, def ext, def info){
new File(“$dir/$filenm$ext”).withWriter { out ->
info.each {
out.println it
}
}
}
//*********************************************************************
//Create File Method
//*********************************************************************
//Input:
// dir: root folder directory
// folder: folder to add to directory
//Output:
// String: directory root for file creation
//*********************************************************************
public String createFolder(def dir,def folder){
File f = new File(“$dir/$folder”);
f.mkdirs();
return “$dir/$folder”
}

Resources