Jenkins Job DSL: Creating parameter object in function - jenkins-job-dsl

I want to write a function (in a jenkins job DSL) which returns a reusable set of parameters for job defintions. Like this:
def pars(name) {
return parameters {
booleanParam(name, true)
}
}
pipelineJob("Test1") {
pars("name")
}
pipelineJob("Test2") {
pars("name2")
}
This does not work, but can I somehow rewrite the example so that it does work?

parameters can not be called in your helper method, but you can create a closure in a helper method.
Try this:
def pars(name) {
return {
booleanParam(name, true)
}
}
pipelineJob("Test1") {
parameters pars("name")
}
Or this:
def pars(name) {
return {
parameters {
booleanParam(name, true)
}
}
}
pipelineJob("Test1").with pars("name")

Related

Flutter: generic list handles different key, value pairs

I have a class that has a generic List as property, that I have to initialize, and that has a function that returns a card using that list:
class buildCard{
buildCard(this.list);
final List list;
Widget buildCard(int position) {
return Card(child: ListTile(title: list[position].name,),);
}
Now, as you can see, I use
list[position].name
that works for the majority of the stuff that I have, but, in case I will have a list which doesn't have "name" as key, I will have some troubles. How can I avoid this problem?
You can use is to check the type
Widget buildCard() {
if(list[position].name is List) {
return Card(child: ListTile(title: list[position][0].name,),); // or similar - I don't know your exact structure
} else {
return Card(child: ListTile(title: list[position].name,),);
}
}
You have to mix both previous answers to get what you want (credit goes to #GünterZöchbauer)
abstract class Named {
String name;
}
class Person implements Named {
String name;
Person(this.name);
}
class NotAPerson {
String noName;
NotAPerson(this.noName);
}
class BuildCard {
BuildCard(this.list);
final List list;
Widget buildCard(int position) {
if(list[position] is Named) {
return Card(child: ListTile(title: list[position].name,),);
} else {
return Card(child: ListTile(title: list[position].noName,),);
}
}
}
main() {
BuildCard b = BuildCard([Person, NotAPerson]);
b.buildCard(0); // Will access name
b.buildCard(1); // Will not access name
}
You could constrain your List so only objects that have the name property can be passed in.
abstract class Named {
Widget name;
}
class buildCard {
buildCard(this.list);
final List<Named> list;
Widget buildCard(int position) {
return Card(child: ListTile(title: list[position].name,),);
}
}

Ember CLI Mirage: How to filter out return value?

This is how I get all data in config.js:
this.get('/rentals', function (schema, request) {
if (request.queryParams.value) {
// The code should be here...
} else {
return schema.rentals.all();
}
}
I looked at documentation, but there's no way to get filtered ones. Apparently there are commands like all(), find(), findBy(), create(), etc. But there's nothing that filters out and returns. Any help?
Figured out: filter could be used with all().
this.get('/rentals', function (schema, request) {
if (request.queryParams.value) {
let filteredRentals = schema.rentals.all().filter(function (i) {
return i.attrs.value.toLowerCase().indexOf(request.queryParams.value.toLowerCase()) !== -1;
});
return filteredRentals;
}
return schema.rentals.all();
});

Helper binding not updating

I have a helper like so:
import Ember from 'ember';
export function bootstrapModelStatus(model) {
if(model.get('isDeleted')) {return 'danger'};
if(model.get('isError')) { return 'danger'};
if(!model.get('isValid')) { return 'warning'};
if(model.get('isSaving')) { return 'info'};
if(model.get('isNew')) { return 'default'};
if(model.get('isDirty')) { return 'warning'};
if(model.get('isLoaded')) { return 'success'};
return 'error';
}
export default Ember.Handlebars.makeBoundHelper(bootstrapModelStatus);
And it is bound to a DS.Model like so:
{{bootstrap-model-status model}}
The trouble is that the above does not update when the state of the model changes. Instead I had to do the following as a bit of a hack.
{{bootstrap-model-status model model.currentState.stateName}}
Is there a better way of doing this?
You can tell the helper to redisplay when a property of the model you passed in changes - see here
In your case, that would mean the following:
import Ember from 'ember';
export function bootstrapModelStatus(model) {
if(model.get('isDeleted')) {return 'danger'};
if(model.get('isError')) { return 'danger'};
if(!model.get('isValid')) { return 'warning'};
if(model.get('isSaving')) { return 'info'};
if(model.get('isNew')) { return 'default'};
if(model.get('isDirty')) { return 'warning'};
if(model.get('isLoaded')) { return 'success'};
return 'error';
}
export default Ember.Handlebars.makeBoundHelper(bootstrapModelStatus,
'isDeleted', 'isError', 'isValid', 'isSaving', 'isNew', 'isDirty', 'isLoaded'
);

Unit test filter with a mocked service

I'm using Grails 2.3.8 and trying to create a unit test for a filter that uses a service.
The filter:
class LicenseFilters {
def licenseService
def filters = {
all(controller:'*', action:'*') {
before = {
if(!licenseService.checkLicense()){
redirect(controller:"licenseExpired")
return false
}
}
}
}
}
The spec, first attempt:
#TestFor(ExecutionTraceController)
#Mock(LicenseFilters)
class LicenseFiltersSpec extends Specification{
void "Test filter redirects when license is wrong"() {
given:
LicenseFilters bean=applicationContext.getBean("com.nortia.sgmentia.license.LicenseFilters")
bean.licenseService=this.buildLicenseServiceStub(false)
when:
withFilters(action:"list") {
controller.list()
}
then:
response.redirectedUrl == '/licenseExpired'
}
private LicenseService buildLicenseServiceStub(boolean ok){
LicenseService result=Stub(LicenseService)
result.checkLicense() >> ok
return result
}
}
But it turns out (by debugging) that the bean that I grab from the context it is NOT the same one that receives the request thus I still get a NPE.
In a second attempt I try using defineBeans:
void "Test filter redirects when license is wrong"() {
given:
defineBeans {
licenseService(MethodInvokingFactoryBean){
targetObject = this
targetMethod= "buildLicenseServiceStub"
arguments=[false]
}
}
when:
withFilters(action:"list") {
controller.list()
}
then:
response.redirectedUrl == '/licenseExpired'
}
But the mocked bean is neither bean instanciated nor inyected.
Should I try to inyect the service manually into the filter??
There was this issue https://jira.grails.org/browse/GRAILS-8976 but it is closed.
I came across a similar situation and was able to fix it by adding the service to the #Mock annotation, i.e. #Mock([LicenseFilters, LicenseService]).
In your case the spec would look something like the following:
#TestFor(ExecutionTraceController)
#Mock([LicenseFilters, LicenseService])
class LicenseFiltersSpec extends Specification {
void "Test filter redirects when license is wrong"() {
given:
defineBeans {
licenseService(MethodInvokingFactoryBean) {
targetObject = this
targetMethod = "buildLicenseServiceStub"
arguments = [false]
}
}
when:
withFilters(action: "list") {
controller.list()
}
then:
response.redirectedUrl == '/licenseExpired'
}
private LicenseService buildLicenseServiceStub(boolean ok) {
LicenseService result = Stub(LicenseService)
result.checkLicense() >> ok
return result
}
}
Note: that mocking the service in this manner will, by default, inject an instance of the actual LicenseService into your filter. So, if the above defineBeans block is removed the actual implementation of LicenseService.checkLicense() will be called.
I finally found a workaround to make it work going with the second approach (using defineBeans).
The service is not being autowired into the filter so I finally did it manually with a pseudo-singleton:
class LicenseFilters {
def licenseService
def filters = {
all(controller:'*', action:'*') {
before = {
if(!this.licenseService){
this.licenseService=applicationContext.getBean("licenseService")
}
if(!this.licenseService.checkLicense()){
redirect(controller:"licenseExpired")
return false
}
}
}
}
}
Quite ugly but a solution at least.
Hope it helps someone out there.

Upgrading Spock unit tests from Grails 1.3.9 to Grails 2.3.9. But edit() test is failing

I am updating unit tests in a Grails project. We were originally using version 1.3.9 and now we are updating to version 2.3.9. I am using Spock.
I keep getting this error:
results:
junit.framework.AssertionFailedError: Condition not satisfied:
controller.edit() == [filterCategoryInstance: filterCategoryInstance]
| | | |
| null false John
com.xxxxxx.xxxxx.FilterCategoryController#20574000
Here is the controller code:
#Secured(["hasAnyRole('CM_ADMIN')"])
def edit() {
def filterCategoryInstance = FilterCategory.get(params.id)
if (!filterCategoryInstance) {
flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'dpFilterCategory.label', default: 'FilterCategory'), params.id])}"
redirect(action: "list")
}
else {
return [filterCategoryInstance: filterCategoryInstance]
}
}
and here is the test code:
#Mock([FilterCategory, FilterCategoryTag])
#TestFor(FilterCategoryController)
#TestMixin(DomainClassUnitTestMixin)
class FilterCategoryControllerSpec extends ExtendedControllerSpec {
def 'edit action: existing FilterCategory'() {
setup:
mockI18N(FilterCategoryController)
params.id = filterCategoryInstance.id
expect:
controller.edit() == [filterCategoryInstance: filterCategoryInstance]
where:
tag = new FilterCategoryTag(name: 'tag1')
filterCategoryInstance = new FilterCategory(name: "John",
submissionText:"John", sortOrder:0, 'filterCategoryTags': [tag])
}
And here is the ExtendedControllerSpec code. I hope I have included enough code:
I have looked at the following web pages for guidance:
#Mixin(MetaClassMixin)
class ExtendedControllerSpec extends Specification {
def props
protected void setup() {
//super.setup()
props = new Properties()
File file = new File("grails-app/i18n/messages.properties")
if (file.exists()) {
def stream = new FileInputStream(file)
props.load stream
stream.close()
}
mockI18N(controller)
}
def mockI18N = { controller ->
controller.metaClass.message = { Map map ->
if (!map.code)
return ""
if (map.args) {
def formatter = new MessageFormat("")
if (props.getProperty(map.code)) {
formatter.applyPattern props.getProperty(map.code)
}
return formatter.format(map.args.toArray())
} else {
if (props && props.hasProperty(map.code)) {
return props.getProperty(map.code)
} else {
return map.code
}
}
}
}
/**
* add dynamic methods in test setup.
*/
protected void addDynamicMethods() {
registerMetaClass(String)
String.metaClass.mixin StringUtils
}
protected GrailsUser mockGrailsUser() {
return Mock(GrailsUser)
}
...
/**
* must call AFTER mockDpSercurityService
*/
protected void setHasRoleTrue() {
if (controller?.dpSecurityService?.metaClass) {
controller.dpSecurityService.metaClass.hasRole = {return true}
}
}
protected void setHasRoleFalse() {
if (controller?.dpSecurityService?.metaClass) {
controller.dpSecurityService.metaClass.hasRole = {return false}
}
}
protected void mockUserService() {
controller.dpUserService = new MockFor(UserService)
}
}
http://sanjaykanwar.blogspot.com/2012/07/grails-controller-test-with-spock.html
http://naleid.com/blog/2012/05/01/upgrading-to-grails-2-unit-testing
Looks like the if branch gets executed in edit() instead of the else branch because FilterCategory does not get saved and therfore does not get a proper id.