Files not being stored in folder directory - groovy

I am having issues trying to place files within a file directory I have created. I want the files to go into the created folder 'GET_Tests{Test}' but instead of going into this folder, it is placing the files on the same directory the folder is within.
I have tried a few things to try and get it working but no luck, what do I need to change in order to get the files stored within the folder?
Below is the code. One script is ReadData and the other is PrintToLogFile. ReadData creates the folder whilst PrintTologFile creates the files.
ReadData:
// define properties required for the script to run.
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def dataFolder = groovyUtils.projectPath
def date = new Date()
def folderTime = date.format("yyyy-MM-dd HH-mm-ss")
//Define an empty array list to load data from datasheet
def DataTable = [];
//Create a folder directory for the responses
RootResultFolder = dataFolder + "/Responses" + "\\GET_Tests{Test} - " + folderTime
CreateResultFolder = new File(RootResultFolder)
CreateResultFolder.mkdir()
PrintToLogFile
import groovy.json.JsonOutput
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def casename= testRunner.testCase.name
def response = testRunner.testCase.getTestStepByName("GET_Tests{Test}").getProperty("Response").getValue();
def hotelId = testRunner.testCase.getPropertyValue('hotelid')
def date = new Date().format("yyyy-MM-dd")
def time = new Date().format("HH.mm.ss")
def fileName = hotelId + " - D" +date+ " T" +time+ ".txt"
def dataFolder = context.getProperty("RootResultFolder")
def rootFolder = dataFolder + fileName
def logFile = new File(rootFolder)

An additional Groovy Script test step is not really needed to just save the response into a file. Instead a Script Assertion can be added to the same REST test step request with below, follow in-line comments.
Script Assertion
import com.eviware.soapui.support.GroovyUtils
//Save the contents to a file
def saveToFile(file, content) {
if (!file.parentFile.exists()) {
file.parentFile.mkdirs()
log.info "Directory did not exist, created"
}
file.write(content)
assert file.exists(), "${file.name} not created"
}
//Get the project path
def dataFolder = new GroovyUtils(context).projectPath
//Create today's date for storing response
def today = new Date().format("yyyy-MM-dd")
def filePrefix = "${dataFolder}/Responses/GET_Ratings_hotelId_${today}" as String
def fileNamePart = new Date().format("yyyy-MM-dd'T'HH.mm.ss")
//Check if there is response
assert context.request, "Request is empty or null"
//create file object with file name
def file = new File("${filePrefix}/hotelId_${fileNamePart}.json")
//Call above method to save the content into file
saveToFile(file, context.response)

Related

Not able to add a project ID/name to a list in Jira/Groovy/Scriptrunner

The following question I present is the following: I'm doing a code that is been tested in the Scriptrunner console and tried into Jira. What I want to reach is the following: I have an issue in any project, at any moment a workflow transition allows me to copy the current issue and all the linked issues in a new project.
The cfProjectPicker is a custom field Project Picker that allows me to select a project.
What I'm having trouble right now on the code is the following:
1- projectKey is returning null valor but projectPicker is returning the correct project selected in the custom field.
2- createNewIssue is not allowing me to recognize the "params" field as a mutable issue, and it is a mutable (if I replace with newIssue it does take it)
3- the list "issuesCopied" is not allowing me to issuesCopied.id.toString() but I'm guessing is giving error due to the point 2.
Any help regarding the matter would be much appreciated because I'm not understanding what I'm doing wrong at moment.
def issueMgr = ComponentAccessor.getIssueManager();
def issueTypeSchemeManager = ComponentAccessor.getIssueTypeSchemeManager()
def customFieldManager = ComponentAccessor.getCustomFieldManager();
def projectMgr = ComponentAccessor.getProjectManager();
def groupManager = ComponentAccessor.getGroupManager();
def issueFactory = ComponentAccessor.getIssueFactory();
IssueLinkManager issueLinkManager = ComponentAccessor.getIssueLinkManager();
def cfProjectPicker = customFieldManager.getCustomFieldObjectByName("Seleccionar Proyecto") //cf project picker
def issue = issueMgr.getIssueObject("MART1-1")
ApplicationUser user = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser() //User Admin
ApplicationUser currentUser = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()
def currentIssue = issueFactory.getIssue()
//def issue = issueMgr.getIssueObject()
def newIssue = issueFactory.getIssue()
def exit = false
// Array list of the issues created to save them
List<String> issuesCopied = new ArrayList<>();
// ***** CREATE ISSUE *****
if (issuesCopied.isEmpty()){
String projectPicker = issue.getCustomFieldValue(cfProjectPicker)
log.error("Gengar")
log.error(projectPicker)
def projectKey = projectMgr.getProjectObjByKey(projectPicker)
log.error(projectKey)
newIssue.setProjectObject(projectKey)
newIssue.setIssueType(issue.getIssueType())
newIssue.setSummary(issue.getSummary())
newIssue.setDescription(issue.getDescription())
newIssue.setReporter(currentUser)
def params = ["issue":newIssue]
log.error(params)
def createNewIssue = issueMgr.createIssueObject(user,params);
issuesCopied.add(createNewIssue.id.toString())
}

SoapUI to read request parameters from a file ( free version)

I have a file with following contents
987656
987534
I have a Groovy script as following as a test step before my test :
def myTestCase = context.testCase
new File("filepath/data1.txt").eachLine { line ->
myTestCase.setPropertyValue("inputValue", line)
inputValue = context.expand( '${#TestCase#inputValue}' )
log.info inputValue
}
The log output for the script gives me both the values from the file :
987656
987534
I have a Testcase custom property set up as "inputValue" and in my test I call the parameter as
<enr:Id>${#TestCase#inputValue}</enr:Id>
During execution the test always runs for the last value "987534" and not for both the inputs.
What should I be doing to execute the test for all the values present in the text file?
Thanks
The way to loop through values like that is to, in the eachLine loop, call the SOAP step, like this:
def myTestCase = context.testCase
new File("filepath/data1.txt").eachLine { line ->
myTestCase.setPropertyValue("inputValue", line)
inputValue = context.expand( "${#TestCase#inputValue}" )
log.info inputValue
//define the step
def soapTestStep = testRunner.testCase.getTestStepByName("YourSOAPRequestName").name
//call the step
testRunner.runTestStepByName(soapTestStep)
//if you want to do something with the response XML
def responseSOAP = context.expand("${YourSOAPRequestName#Response}")
//if you want to check a value in the response XML
def responseSection = responseSOAP =~ /someNode>(.*)<\/someNode/
def responseValue = responseSection[0][1]
log.info "response: ${responseValue}"
}

Adding values in a json file

I'm trying to add previously added integers in the json file. for discord.py
#client.command()
async def mine(ctx):
await open_account(ctx.author)
users = await get_wallet_data()
user = ctx.author
earnings = int(random.randrange(11))
em = discord.Embed(title = 'Mined NeoCoins')
em.add_field(name = 'Earnings:', value = earnings)
await ctx.send(embed = em)
wallet_amt = users[str(user.id)]['Wallet']
print(wallet_amt)
nw = wallet_amt =+ earnings
nw = users[str(user.id)]['Wallet']
print(nw)
with open('wallet.json','w') as f:
users = json.dump(users,f)
But I'm getting that same value. Not the added value
To change the values of .json files, you have to load the file first, make the edits, and then replace the file with the changed version.
Load file:
with open("filename.json", "w+") as fp:
d = json.load(fp) #load the file as an object
Make edits:
... #change the values in d
Replace file with changed version:
fp.truncate(0) #empty the file
json.dump(d, fp) #dump changed version into file
Full Code

can file be named with today's date in groovy

I am doing soapui testing, wherein i want to save request & response suffixed with todaydate.
here's my code:
// Create a File object representing the folder 'A/B'
def folder = new File( 'C:/Project/SOAPUI' )
// If it doesn't exist
if( !folder.exists() ) {
// Create all folders up-to and including B
folder.mkdirs()
}
def myOutFile = "C:/Project/SOAPUI/test_request.txt"
def request = context.expand( '${test#Request}' )
def f = new File(myOutFile)
f.write(request, "UTF-8")
=====================
I want the file name to be test_request(+today's date)
Can you suggest me some options?
Here's an option:
def myOutFile = "C:/Project/SOAPUI/test_request_${(new Date()).format('yyyy-MM-dd')}.txt"
The output looks like C:/Project/SOAPUI/test_request_2015-08-30.txt

OpenCSV - parse collection in header

I have a working setup (btw. using groovy) for OpenCSV HeaderColumnNameMappingStrategy and MyCustomBean.
def file = new FileReader(new File("sample.csv"))
def csvReader = new CSVReader(file)
def strategy = new HeaderColumnNameMappingStrategy<MyCustomBean>()
strategy.setType(MyCustomBean)
I am curious, whether it is possible to parse any collection (I guess a map) from header.
Sample csv
priority,subject,description,customFields[4]
1,first,foo,X-7
2,second,hoo,X-8
Mapped bean
class MyCustomBean {
def subject
def description
def priority
def customFields
}

Resources