Showing posts with label groovy. Show all posts
Showing posts with label groovy. Show all posts

Monday, September 24, 2018

Label not showing in Chart.js with Grails

Leave a Comment

I wish to pass data from a Grails controller to a chart.js chart in a Grails view. My code will not display the chart labels correctly. The issue is that labels (an arrayList of dates) is not being read correctly as an array of strings in Javascript which is causing Chart.js not to display.

Can anyone offer any help?

Any help would be gratefully received. Thanks in advance! My code is here:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script> <script>         var userResult = ${userResultMap as JSON};         var data = userResult.result;         var labels = userResult.dateCreated;       var config = {         type: 'line',         data: {             labels: testDate,             datasets: [{                 label: 'Clinical FRE',                 backgroundColor: '#7A564A',                 borderColor: '#7A564A',                 data: result,                 fill: false             }]         },         options: {             legend: {                 display: false             },             tooltips: {                 enabled: false             },             responsive: true,             scales: {                 yAxes: [{                     gridLines: {                         drawBorder: false,                         color: ['#9b1f22', '#9b1f22', '#ed1c24', '#ed1c24', '#f7931f', '#f7931f', '#206b36', '#206b36', '#206b36', '#206b36', '#206b36']                     },                     ticks: {                         min: 0,                         max: 100,                         stepSize: 10,                         callback: function (value) {                             return value + "%"                         }                     }                 }]             }         }     };  window.onload = function createChart(data) {     var ctx = document.getElementById('myChart').getContext('2d');     window.myLine = new Chart(ctx, config) };  </script> 

Data is sent from controller using ModelandView command:

@Secured('ROLE_USER') def home() {     try {         SecUser user = springSecurityService.currentUser         Participant p = Participant.findByUser(user)         Result userResults = Result.findByUser(user)         def userResultsList         def riskLevelMap         def iconClassMapList = []         def riskLevelMapList = []         def colourNameList = []         Map userResultMap = [:]          if (userResults!= null){             userResultsList = userResults.list()             if(userResultsList != null)             userResultsList.each {list->                 iconClassMapList.add(previousTestsService?.getIconType(list))                 riskLevelMap = riskAdviceService?.riskLevel(list.result)                 riskLevelMapList.add(riskLevelMapList)                 colourNameList.add(riskLevelMap?.colourName)             }               userResultMap.put("result",userResultsList?.result)                             userResultMap.put("dateCreated",userResultsList?.dateCreated)             println userResultMap             println userResultsList.dateCreated             println(userResultsList.dateCreated.getClass())          }          return new ModelAndView('home', [user: user, participant: p, username: user.username,userResultsList: userResultsList,iconClassMapList:iconClassMapList,colourNameList:colourNameList,userResultMap:userResultMap])      } catch (Exception ex) {         log.error(ex.printStackTrace())     } } 

Sample data: data - [13.7] labels - [2018-09-17 16:39:00.0]

4 Answers

Answers 1

You would need to convert your array, object whatever you are using to JSON for JavaScript to understand it.

<g:javascript>         var testDate = ${userResultsList.dateCreated}         var result = ${userResultsList.result as JSON}    // make sure grails.converters.JSON is imported </g:javascript> 

Answers 2

Make sure userResultsList(userListMap) data must be in the form below from the controller.

    Map userResultMap = [:]     List dateCreated = ["2018-09-17 13:07:06.0","2018-09-17 13:27:06.0","2018-09-17 14:27:06.0","2018-09-17 17:27:06.0"]     List result = [50, 56, 23, 42]     userResultMap.put("dateCreated",dateCreated)     userResultMap.put("result",result) 

Then you need to parse the userResultMap data as JSON if not parsed and do similar like this in gsp page:

<script>     var userResult = ${userResultMap as JSON};     var result = userResult.result;     var labels = userResult.dateCreated; </script> 

Answers 3

The main issue here is that grails automatically escapes values as HTML upon insertion in the GSP page. You can suppress this by adding the advice

<%@ expressionCodec="none" %> 

at the beginning of the GSP page.

Be aware that your application will be less secure after the change. Especially if the data can contain user-created input people might start messing with your application.

Here is a running example using Grails 3.3.8 based on the test data supplied by @Kumar Chapagain, thank you very much.

In the controller you don't need to package the data in a ModelAndView, as this is done automatically by Grails. Just return a map with the needed entries. I prefer to convert the map to JSON within the controller and not in the gsp page as it keeps the control where it belongs and the GSP more simple.

Controller:

package g338  import grails.converters.JSON  class ChartController {      def index() {          Map userResultMap = [:]         List dateCreated = ["2018-09-17 13:07:06.0","2018-09-17 13:27:06.0","2018-09-17 14:27:06.0","2018-09-17 17:27:06.0"]         List result = [50, 56, 23, 42]         userResultMap.put("dateCreated",dateCreated)         userResultMap.put("result",result)          [ userResultMap: userResultMap as JSON ]     } } 

gsp page: views/chart/index.gsp

<%@ expressionCodec="none" %> <!doctype html> <html> <head>     <meta name="layout" content="main"/>     <title>Welcome to Grails</title> </head> <body>     <canvas id="myChart"></canvas>     <g:javascript>     var result = ${userResultMap};     var data = result.result;     var labels = result.dateCreated;      var config = {         type: 'line',         data: {             labels: labels,             datasets: [{                 label: 'Clinical FRE',                 backgroundColor: '#7A564A',                 borderColor: '#7A564A',                 data: result,                 fill: false             }]         },         options: {             legend: {                 display: false             },             tooltips: {                 enabled: false             },             responsive: true,             scales: {                 yAxes: [{                     gridLines: {                         drawBorder: false,                         color: ['#9b1f22', '#9b1f22', '#ed1c24', '#ed1c24', '#f7931f', '#f7931f', '#206b36', '#206b36', '#206b36', '#206b36', '#206b36']                     },                     ticks: {                         min: 0,                         max: 100,                         stepSize: 10,                         callback: function (value) {                             return value + "%"                         }                     }                 }]             }         }     };      window.onload = function createChart(data) {         var ctx = document.getElementById('myChart').getContext('2d');         window.myLine = new Chart(ctx, config)     };      </g:javascript>  </body> </html> 

Answers 4

var labels = userResult.dateCreated;       var config = {         type: 'line',         data: {             labels: testDate, 

you are using labels: testDate, but assigning labels to labels try

var testDate = userResult.dateCreated; **labels: testDate** 
Read More

Thursday, August 16, 2018

Why doesn't Groovy's power assert work in a Jenkins job

Leave a Comment

Power assertions work in the /script, but do not work in a Jenkinsfile driven job. Why? Is there a way to get it to work?

In Jenkinsfile job:

assert 1 == 2  at org.codehaus.groovy.runtime.InvokerHelper.assertFailed(InvokerHelper.java:404) ... wall of stack trace 

In /script window

Assertion failed:   assert 1 == 2          |          false 

In this trivial example, it is easy to figure out what is going on. In practice, one or both of the operands of "==" will be a variable. In the /script version, it will display the values (see the link above). In the Jenkinsfile console log you just get the assert statement as is with no hints.

Added after @daggett question:

node ()   {   stage('assert')     {     try        {       two = 2       assert 1==two        }     catch(Throwable t)       {       println t       error "assert failed"       }     }   } 

output:

Assertion failed:   assert 1==two 

2 Answers

Answers 1

Not possible as far as I can see. Jenkins pipeline groovy DSL uses custom CPS interpreter during interpretation of groovy. This means that it bypasses/overrides a lot of the standard implementation of groovy, and thus also the assert implementation. The assert implementation for Jenkins Pipeline CPS can be found here, while the real groovy implementation uses this class during the assert evaluation in order to record values and print proper exception.

In order to get similar behaviour in Jenkins pipeline CPS one would either need to refactor the groovy code base and Jenkins CPS code or duplicate a lot of the functionality in the AssertionWriter class linked above.

Answers 2

This is an example of a hack that sort of works:

def ASSERT_EQ (def arg1, def arg2)   {   if (arg1 != arg2)     {     println ('arg1 = ' + arg1 + " " + arg1.getClass())     println ('arg2 = ' + arg2 + " " + arg2.getClass())     }   assert arg1 == arg2   } 

It is not nearly as robust as the normal groovy power assert.

Read More

Thursday, April 12, 2018

SoapUI LoadTest execution fail

Leave a Comment

I try to generate load test from my testcase in SoapUI. It has a lot of test steps, from which the first 10 covers the login process. LoadTest stops in a Groovy script, which should get parameter values from the previous test step's output. It is working correctly, when it is executed directly, but gives error, when it is executed as a LoadTest:

groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method java.lang.String# . Cannot resolve which method to invoke for [null] due to overlapping prototypes between: [class [B] [class [C] [class java.lang.String] groovy.lang.GroovyRuntimeException: Ambiguous method overloading for method java.lang.String# . Cannot resolve which method to invoke for [null] due to overlapping prototypes between: [class [B] [class [C] [class java.lang.String] error at line: 5 

Groovy script which causes error above:

def tc1 = testRunner.testCase.getTestStepAt(context.currentStepIndex-1); String rawData = new String(tc1.testRequest.response.rawResponseData); Reger reger = new Reger(rawData);   String myvar1 = reger.getNthMatch(/<myregex>/, 0); 

1 Answers

Answers 1

Your problem in this string:

String rawData = new String(tc1.testRequest.response.rawResponseData) 

tc1.testRequest.response.rawResponseData is null

so to prevent exception you can change this string to:

String rawData = tc1.testRequest.response.rawResponseData?.toString() 

which is null safe

Read More

Sunday, May 21, 2017

how to create correct folder directory to output files from script assertion

Leave a Comment

I have a folder structure situation I would like to require advice on. Below is a screen shot of a particular project I have:

enter image description here

Now the currently I have a piece of code where it runs a set up script from test suite level where it creates a 'Test Run' folder directory and within there all of the files created within test case level assertions go into that 'Test Run' folder. Below are the code of the test suite setup script and the code for placing files in that folder:

Test Suite setup script where it creates the 'Test Run' folder. (Each Suite has the same code but a different directory it falls under which is shown later). In this example the 'Test Run' folder falls under 'HotelAvail' folder. For the other suite, it falls under 'HotelAvailCalendar' folder:

// 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")   //Create a folder directory for the responses RootResultTestFolder = dataFolder + "\\HotelAvail\\Test Run " + folderTime + "\\" CreateResultTestFolder = new File(RootResultTestFolder) CreateResultTestFolder.mkdir()   context.setProperty( "RootResultTestFolder", RootResultTestFolder ) 

Within each test case, they contain a 'ReadData' groovy script step to create folders within the relevant 'Test Run' folder and then each test case contains a soap request to their relevant service and in their assertions, they contain the code below where it puts the file in the folder set within the folder created within Read Data:

In ReadData groovy script:

// define properties required for the script to run.  def testFolder = context.getProperty( "RootResultTestFolder")  def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)   def date = new Date() //def folderTime = date.format("yyyy-MM-dd HH-mm-ss")   RootResultFolder = testFolder + testRunner.testCase.name + "\\" CreateResultFolder = new File(RootResultFolder) CreateResultFolder.mkdir()  context.setProperty( "RootResultFolder", RootResultFolder) 

In a soap request script assertion:

def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context) def currentRow = context.getProperty("currentRow") def dataFolder = context.getProperty("RootResultFolder") def hotelCode = messageExchange.modelItem.testStep.testCase.getPropertyValue("HotelCode") def hotelCodeTrim = hotelCode.toString().replace("|", "") def serviceRequest = context.expand( '${GetHotelAvailability#Request}'  ) def serviceResponse = context.expand( '${GetHotelAvailability#Response}'  ) def date = new Date().format("yyyy-MM-dd") def time = new Date().format("HH.mm.ss") def fileName =  dataFolder + hotelCodeTrim + " Extranet_GetHotelAvailability.txt" log.info "TestRecord: " + fileName def logFile = new File(fileName)  //--- assert code goes here ----  def testResult = new StringBuffer() testResult.append "Test run on DateTime Stamp: " +date+ " " + time  testResult.append "\n\nService Request:\n\n" testResult.append(serviceRequest.toString()) testResult.append "\n\nService Response:\n\n" testResult.append(serviceResponse.toString())  // Now create and record the result file logFile.write(testResult.toString())  

So the folder directory for when i run a test at project or test suite level looks like this (example using 'HotelAvail'):

enter image description here enter image description here

The folders below is for each test case.

enter image description here

Within each folder is their relevant file, example of a file within a relevant folder:

enter image description here

So the reason I thought of this set up is that it's nice and clean per test run that instead of creating all the folders in area, it creates it within a 'Test Run' folder which belongs per test suite folder 'HotelAvail' or 'HotelAvailCalendar'.

Now more test suites will go into this project but the problem i am going to face is that if the user decides to not run at test suite level and wants to run at test case level, then the 'Test Run' folder will not be created as it is within the 'Test suite' set up script and that means the assertion will fail as it cannot find 'Test Run'. But if i put the 'Test Run' folder in all test case level setup scripts, if i run a test at test suite level, multiple 'Test run' folders will be created. If I don't have a 'Test Run' folder, then all test folders will be bunched up into one.

You can see my dilemma and I want to know what would actually be the best approach in this scenario. If somebody can provide me an example code or project it's much appreciated.

Thank you,

1 Answers

Answers 1

I suggest you place them relative to project with the following code

def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)  // define location relative to SOAPUI project. String projectPath = groovyUtils.projectPath + "/destination/"  context.setProperty( "RootResultFolder", projectPath) 
Read More

Sunday, February 5, 2017

How to retreive endpoint of a service

Leave a Comment

i want to add my project's endpoint in the project tear down script. What is the syntax in order to get the endpoint for all requests and test requests as the user will assign their endpoint via all requests and test requests before running the project?

i seen an example using test step but i don't want to retrieve it via the test step route:

testRunner.testCase.getTestStepByName("dd").getHttpRequest().getEndpoint(); 

The tear down script use either , log, context, runner nd project variables.

Thanks

Screenshots:

enter image description here

enter image description here

I removed the last digits of the endpoints in the screenshot below but there are 5 end points

enter image description here

1 Answers

Answers 1

Based on the information updated in the question, it looks like you have to access the endpoint in the TearDown Script of the project.

It also appears that you would need to execute the same set of tests against different base url of the endpoint and domain. Not sure even you might need to use the credentials accordingly.

Considering the above, it would be easy to project level properties.

Here you would go:

  • Create a project level custom property for base url, say BASE_URL as property name and value as http://10.0.0.1:8008. Of course, change it with actual value as needed with respect to the tests to be executed.
  • Similarly create another project level property for domain, say DOMAIN_NAME and provide its value according the test.
  • Double click on service / interface, click on Service Endpoints tab.
  • Remove all the existing values.
  • Add a new endpoint by clicking + icon.
  • Add ${#Project#BASE_URL} as endpoint and ${#Project#DOMAIN_NAME} as domain values
  • If required, you use the same approach for the credentials.
  • Now click on Assign button there and choose All requests and Tests option from the dropdown.
  • Similarly, do the same if you have multiple services / interfaces.

How to access the above values in TearDown Script?

log.info "Endpoint : ${project.getPropertyValue('BASE_URL')}" log.info "Domain : ${project.getPropertyValue('DOMAIN_NAME')}" 

When you want to change domain or base url, just change the values of the respective project properties before you run execute the tests against different servers / environments.

Read More

Wednesday, April 13, 2016

Spring injection in cucumber step definition in case of groovy script

Leave a Comment

It's quite convenient to implement step definitions using Groovy Script approach, but in this case it's unclear if it's possible to use Spring injection or not.

In case of Groovy script there's no class, just set of closures, like this:

this.metaClass.mixin(Hooks) this.metaClass.mixin(EN)  Given(~/^we do something$/) { ->     } 

Is there any way to use Spring with Groovy Script?

0 Answers

Read More