How can I add another source to java_test_suite? - bazel

This is how I'm using the java_test_suite:
(https://github.com/bazel-contrib/rules_jvm#java_test_suite)
java_test_suite(
name = "everything-tests",
srcs = glob(["src/test/java/**/*.java"]),
runner = "junit5",
test_suffixes = ["Tests.java"],
runtime_deps = JUNIT5_DEPS,
deps = [
":everything",
...
] + deps,
)
However, what it is doing is that java_test_suite is iterating over each srcs and creating a java_test for it. The problem becomes when one of my tests has a dependency on another test class.
For example, I have a test class which extends another abstract test class like so:
public class CustomTimerTests extends BaseTimerTests
But CustomTimerTests is failing as it is not able to find BaseTimerTests because java_test_suite does not let me add BaseTimerTests as one of the sources for CustomTimerTests.
Anyone knows how to fix it?

Related

How to handle Multiple Base Path in RestAssured API Testing Framework?

In my case, I have multiple Base basePath.
Eg: Base URI- > http://reg10xx.cwx.local/API/Admin
BasePath1->/User
EndPoint->/List
The problem arises here.
Base URI-> http://reg10xx.cwx.local/API/Admin
BasePath2->/Organisation
EndPoint->/Roles.
Here is my case problem is with BasePath 1 and Base Path 2.
As in TestBase.java Class in Before Suite I have used
RestAssured.baseURI = configProperties.getBaseURI();
RestAssured.basePath = configProperties.getBasePath();
now I want to set my 2nd base path then is there any solution to this?
One solution I can think of here is to set the base URL path at the test case/helper method level rather than setting it at the class level.
Example:
RequestSpecBuilder build;
build = new RequestSpecBuilder();
build.setBaseUri ("https://maps.googleapis.com");
I am not sure what is yourbaseurl it , but you can parameterize yhe baseurl .
Then in Basepath mention the path which is common for both Admin and roles .
After that pass the path which completes the URI example -roles
import io.restassured.RestAssured;
import io.restassured.response.Response;
RestAssured.baseURI = "http://reg10xx.cwx.local/";
RestAssured.basePath = "API;
Response admin= get("Admin");
Response roles= get("Roles");

Using class from another groovy file as a type in a Jenkins pipeline script

I'm a groovy novice, so not sure if this is possible. I need something like an import, but not quite. Here is the simplified code example of what I'm trying to do:
in file FileToProcess.groovy I have
class FileToProcess implements Serializable {
String FileName
FileToProcess(fileName) {
this.FileName = fileName;
}
}
and then in a JenkinsFile I want to do something like
F1 = new FileToProcess('A');
List<FileToProcess> allFiles = new ArrayList<FileToProcess>();
allFiles.add(F1);
​for (FileToProcess file : allFiles) {
System.out.println(file.FileName);
}
Now, on StackOverflow I've found examples of how to instantiate a class from another file, for example here or here, and that solves the line
F1 = new FileToProcess('A');
but it does not show how to use that class as a type in a declaration, for example
List<FileToProcess> allFiles = new ArrayList<FileToProcess>();
gives me "unable to resolve class FileToProcess". I also know that using a class as a type like this should work, because it does when I put the class in the same JenkinsFile, so the problem seems to be just that the class is not visible in the JenkinsFile.
Is there a way to do this?
I'm not sure how you tried to setup your class libraries but I attempted the same while using a class from a pipeline shared library and it worked as intended
https://jenkins.io/doc/book/pipeline/shared-libraries/
I did do it a little differently:
assuming you places the file under src/org/Foo.groovy
import org.Foo
def list = new ArrayList<Foo>
list.add(new Foo('str1'))
list.add(new Foo('str2'))

Grails + Spock: NullPointerException when doing addTo* on an embedded hasMany field

I have domain class:
class MarketCommoditiesConfiguration extends MarketConfiguration {
static mapWith = "mongo"
static hasMany = ['commodities': Commodity]
static embedded = ['commodities']
...
Doing save after addToCommodities throws the following exception.
| java.lang.NullPointerException
at org.grails.datastore.mapping.model.types.Association.getInverseSide(Association.java:71)
at org.grails.datastore.mapping.engine.NativeEntryEntityPersister.handleEmbeddedInstance(NativeEntryEntityPersister.java:1254)
at org.grails.datastore.mapping.engine.NativeEntryEntityPersister.handleEmbeddedInstance(NativeEntryEntityPersister.java:1215)
at org.grails.datastore.mapping.engine.NativeEntryEntityPersister.handleEmbeddedToMany(NativeEntryEntityPersister.java:1188)
at org.grails.datastore.mapping.engine.NativeEntryEntityPersister.persistEntity(NativeEntryEntityPersister.java:1077)
at org.grails.datastore.mapping.engine.NativeEntryEntityPersister.persistEntity(NativeEntryEntityPersister.java:1138)
at org.grails.datastore.mapping.engine.EntityPersister.persist(EntityPersister.java:160)
at org.grails.datastore.mapping.core.AbstractSession.persist(AbstractSession.java:522)
at org.grails.datastore.gorm.GormInstanceApi.doSave(GormInstanceApi.groovy:194)
at org.grails.datastore.gorm.GormInstanceApi.save_closure5(GormInstanceApi.groovy:162)
at org.grails.datastore.mapping.core.DatastoreUtils.execute(DatastoreUtils.java:302)
at org.grails.datastore.gorm.AbstractDatastoreApi.execute(AbstractDatastoreApi.groovy:37)
at org.grails.datastore.gorm.GormInstanceApi.save(GormInstanceApi.groovy:161)
at com.apposit.terra.connect.service.MarketService.addCommodityToMarket(MarketService.groovy:248)
at com.apposit.terra.connect.service.MarketServiceSpec.Test addCommodityToMarket creates a new next month configuration if current month's configuration doesn't exist(MarketServiceSpec.groovy:164)
Putting Keyword inside #Mock annotation solved it. http://grails.1312388.n4.nabble.com/Grails-MongoDb-embedded-collection-causes-nullpointerexception-td4644098.html contains more involved discussion.
I know this is super-old, but a Google search led me here whilst
facing the same issue. Make sure that you have added #Mock(User) to
your unit test class. In my case, I had multiple levels of embedded
domain classes, and each of them had to be mocked.
- clarkdustin

Executing scripts in a grails Job

I am working on two parts of a program. One that creates small groovy scripts and another that executes them in a Job. Each script is used to convert information from a map to a Domain object. The job will then save the domain object for future use.
Here is a small example.
Domain
class Report {
Date date
Country country
}
Map
Map<String, String> map = new HashMap<String, String>();
map.put("date", "2015-04-21 11:31:11");
map.put("country", "United States");
Date Script
String script = "x.date = Date.parse('y-M-d h:m:s', y['date'])"
The script is currently executed using Eval.
Eval(report, map, script)
There are other more complicated scripts that need to look up information and make decisions based on values.
The date script works fine but when the country script executes I get an error.
Country Script
String script = "import app.Country\nx.country = Country.findByName(y['country'])"
Error
Script1.groovy: 1: unable to resolve class app.Country
It seems like the Country class is not getting loaded in the call to Eval. How can I do an import in Eval? Should I use Eval or GroovyShell?
You need to instantiate a GroovyShell passing as argument the grailsApplication class loader, see the example below:
Bootstrap.groovy
Map bindingValues = new HashMap()
bindingValues.sessionFactory = sessionFactory
bindingValues.propertyInstanceMap = propertyInstanceMap
bindingValues.dataSource = dataSource
bindingValues.ctx = grailsApplication.mainContext
GroovyShell gs = new GroovyShell(grailsApplication.classLoader, new Binding(bindingValues))
gs.evaluate new File("docs/CargaAvaliacoes.groovy")
CargaAvaliacoes.groovy
import avaliacao.Colaborador
import modelo.ModeloAvaliacao
import programa.Programa
def programa = Programa.get(1)
def modelo = ModeloAvaliacao.get(1)
def avaliadores = ["02270789332":"1020016","11388449681":"1010002","02231772331":"1010004","04247774332":"1020002"]
def avaliacaoService = ctx.getBean("avaliacaoService")
avaliadores.each {
def avaliador = Colaborador.findByCpf(it.key)
def avaliados = Colaborador.findAllBySetorAndCpfNotEqual(it.value,it.key)
avaliados.each {
avaliacaoService.cadastrar(programa, modelo, avaliador, it)
}
}
** You need to specify the grailsApplication.classLoader because this class loader is used to load the Grails domain classes.

Dependency injection or Service location with RequireJs

I'm a little confused about how I should be instantiating my objects with RequireJs. I'm using coffeescript classes which defines all my objects as typed functions? (not sure on the correct terminology)
At the moment I'm using dependency injection for my own objects, here's an example viewModel and service
I inject my service into the view model in the constructor through an options array
define 'myViewModel', [ 'jquery', 'sammy' ], ( $, sammy ) ->
class myViewModel
constructor: ( options ) ->
self = #
#service = options.service
#router = sammy( ->
#get( '/SomeRoute#:id', self.onHashUpdated )
)
#router.run()
Here I inject the alertId into the service
define 'myService', ['baseService'], ( baseService ) ->
class myService extends baseService
constructor: ( options ) ->
#alertId = options.alertId
super()
Here is my high-level page object. I do my view model instantiation and inject all the require dependencies into the view model.
require [ 'myViewModel', 'myService', 'domReady!' ], ( viewModel, service ) ->
myViewModelInstance = new viewModel
service: new service
alertId: 'some-alert-id'
I'm just not sure if this is how I should be doing it or if I should be returning a new service from the service define making it a singleton.
All the other dependencies like jquery, sammy, knockout all work like this and return working objects from require rather than types that need to be instantiated like my objects.
Is there an accepted pattern for using requireJs?
Should I be doing dependency injection or service location?
This leads onto testing the javascript and finding a library which can override requireJs and return mocked objects instead of the real dependencies.
In Jasmine I might have something like this
describe '=== my view model ===', ->
sut = null
beforeEach ->
require ['myViewModel', 'mockService'], ( viewModel, mockService ) ->
sut = new viewModel
service: new mockService
I tried out testr but the documentation is abysmal and there's not really any full examples of how to use it.
SquireJs looks like a possibility too for this kind of thing?
I've gone for the following, having each object instantiate it's own dependencies
define 'myService', ['baseService', 'alert'], ( baseService, alert ) ->
class myService extends baseService
constructor: ( options ) ->
super()
#alertId = new alert
Then using squire js for injecting sinon js mocks when I'm testing the modules.

Resources