Geb Firefox Driver: why my test runs twice? - firefox

Sorry for all this code, but I don't have a clue what's making my issue, so here it goes.
I configured the geb plugin to run functional tests with JUnit. So I have in my buildConfig.groovy:
def seleniumVersion = "2.29.0"
def gebVersion = "0.7.0"
dependencies {
// specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg.
// runtime 'mysql:mysql-connector-java:5.1.5'
provided('com.oracle:oracle:11.1.0.7.0')
provided('com.oracle:i18n:10.2.0.5')
test ("org.seleniumhq.selenium:selenium-chrome-driver:$seleniumVersion") {
export = false
}
test("org.seleniumhq.selenium:selenium-firefox-driver:$seleniumVersion"){
excludes "commons-io"
export = false
}
test ("org.seleniumhq.selenium:selenium-ie-driver:$seleniumVersion") {
export = false
}
test ("org.seleniumhq.selenium:selenium-support:$seleniumVersion") {
export = false
}
test ("org.seleniumhq.selenium:selenium-remote-driver:$seleniumVersion") {
export = false
}
test ("org.codehaus.geb:geb-junit4:$gebVersion") {
export = false
}
}
plugins {
build(":tomcat:$grailsVersion") {
export = false
excludes 'svn'
}
compile (":hibernate:$grailsVersion") {
export = false
excludes 'svn'
}
build (":release:2.0.0") {
excludes 'commons-io','http-builder'
export = false
}
compile(":spring-security-core:1.2.7.3") { excludes 'svn' }
compile(":spring-security-ldap:1.0.6")
compile (":remote-control:1.3") {
export = false
}
test(":geb:$gebVersion") {
export = false
}
}
And I have a GebConfig.groovy in my conf folder:
driver = {
//def driver = new HtmlUnitDriver()
//driver.javascriptEnabled = true
//driver
def driver = new FirefoxDriver()
driver
}
environments {
// run as “grails -Dgeb.env=chrome test-app”
// See: http://code.google.com/p/selenium/wiki/ChromeDriver
chrome {
driver = { new ChromeDriver() }
}
// run as “grails -Dgeb.env=firefox test-app”
// See: http://code.google.com/p/selenium/wiki/FirefoxDriver
firefox {
driver = { new FirefoxDriver() }
}
}
I have a functional test for the login:
class LoginTests extends GebReportingTest {
#Test
void login() {
to LoginPage
at LoginPage
username = "SERGIO"
password = "SERGIO"
loginButton.click()
assert at(IndexPage)
link.click()
}
}
And this are my two pages:
class LoginPage extends Page {
static url = "login/auth"
static at = {
title ==~ /Efetuar Login/
}
static content = {
loginForm { $("form", id: "loginForm") }
username { $("input", type:"text", id:"username") }
password { $("input", type:"password", id:"password") }
loginButton{ $("input", type:"submit", id:"submit") }
}
}
class IndexPage extends Page {
static at = {
title ==~ /Security Service Index View/
}
static content = {
description { $('h1') }
link { $('a') }
}
}
For some reason my functional test run twice and don't matter how I start this:
grails test-app :functional
grails test-app -functional

It looks like the Geb plugin isn't fully compatible with Grails 2.3.x . For some reason tests get executed twice after upgrading to Geb plugin 0.9.2 .
I believe this problem is related to https://jira.grails.org/browse/GRAILS-10552 and changes made as part of https://jira.grails.org/browse/GRAILS-6352 .
In Grails 2.3.x+, the GrailsSpecTestType takes care of both Junit and Spock tests:
https://github.com/grails/grails-core/blob/bce298f0/grails-test/src/main/groovy/org/codehaus/groovy/grails/test/spock/GrailsSpecTestType.groovy#L33
It looks like the Geb plugin is adding the deprecated JUnit4GrailsTestType to execution:
https://github.com/geb/geb/blob/584738cb/integration/geb-grails/scripts/_Events.groovy#L60-L67
This is why functional tests get executed twice.
This is how I got around the problem in Geb 0.9.2 / 0.9.3 versions.
grails test-app functional:spock
It looks like Geb version 0.9.1 didn't execute the tests twice.
The difference seems to be caused by this commit:
https://github.com/geb/geb/commit/9c71e820
You should also be aware that you shouldn't have the Spock plugin installed in Grails 2.3.x/2.4.x .

Hi Not Much of a Selenium WebDriver on Ruby but It seems to be that you are starting Firefox twice as such the test runs in two instances

Related

How to start GraphQL server when running .net5 integration tests?

I believe I am missing/misunderstanding something fundamental about the way .net5 works. In setting up an integration test environment for my GraphQL API, I am missing the step on how to start the GraphQL server from said test environment.
When I run the main project, the server is started properly and I can navigate to localhost in the browser and successfully execute GraphQL queries/mutations. My goal here is to set up some automated integration tests.
I'm using NUnit as my test runner and am using WebApplicationFactory<Startup> to "start the server" as I understand it.
In my test project, I'm under the impression that WebApplicationFactory<Startup> is supposed to basically use the Startup.cs class from my main project in my test project so that I don't have to duplicate all the settings, configurations, and injected services. Please correct me if that assumption is not correct.
I've pasted the code I think is relevant.
ApiWebApplicationFactory<Startup>
public class ApiWebApplicationFactory<TStartup> : WebApplicationFactory<Startup> where TStartup : class
{
public static IConfigurationRoot Configuration { get; set; }
public ApiWebApplicationFactory()
{
var configBuilder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
Configuration = configBuilder.Build();
}
protected override void ConfigureClient(HttpClient client)
{
base.ConfigureClient(client);
client.BaseAddress = new Uri("https://localhost");
client.Timeout = new TimeSpan(0, 10, 0);
}
// Based on my assumption this class reuses everything in the Startup.cs class
// I don't actually think this is necessary, but thought it was worth trying
// the test with and without this code.
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
services
.AddGraphQLServer()
.AddQueryType<Query>()
.AddMutationType<Mutation>()
.AddType<GraphQLContentItem>()
.AddType<GraphQLFolder>();
});
}
}
OneTimesetUp
[OneTimeSetUp]
public void OneTimeSetUp()
{
_factory = new ApiWebApplicationFactory<Startup>();
_client = _factory.WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
services.AddScoped<ICacheRepository, MockCache>();
});
}).CreateClient();
var connString = ApiWebApplicationFactory<Startup>.Configuration.GetConnectionString("DefaultConnection");
var options = new DbContextOptionsBuilder<CmsContext>()
.UseMySql(connString, ServerVersion.AutoDetect(connString))
.Options;
_dbContext = new CmsContext(options);
_dbContext.Database.EnsureCreated();
}
Test
[Test]
public async Task Test()
{
// If I set a breakpoint here, I can't navigate to the URL like I'm expecting to
var graphQLHttpClient =
new GraphQLHttpClient(
new GraphQLHttpClientOptions { EndPoint = new Uri("https://localhost/graphql") },
new NewtonsoftJsonSerializer(),
_client);
var request = new GraphQLRequest
{
Query = #"
query GetCurrentSession() {
getCurrentSession() {
id
name
}
}",
OperationName = "GetCurrentSession"
};
// Error is thrown here with "Bad Request"
var response = await graphQLHttpClient.SendQueryAsync<Session>(request);
// Further code is omitted
}
Please let me know if you see what I am missing. Thanks in advance~

Gradle Environment variables. Load from file

I am new to Gradle.
Currently I have this task:
task fooTask {
doLast {
exec {
environment 'FOO_KEY', '1234567' // Load from file here!
commandLine 'fooScript.sh'
}
}
}
fooScript.sh
#!/bin/bash
echo $FOO_KEY
Everything works great. But I have env.file with all needed environment variables. This file is used in Docker builder.
env.file
FOO_KEY=1234567
Question: how can I use env.file together with Gradle environment to load all needed env. params?
What about this :
task fooTask {
doLast {
exec {
file('env.file').readLines().each() {
def (key, value) = it.tokenize('=')
environment key, value
}
commandLine 'fooScript.sh'
}
}
}
I give also my version (check if line is not empty and not a comment, also donot override env var):
file('.env').readLines().each() {
if (!it.isEmpty() && !it.startsWith("#")) {
def pos = it.indexOf("=")
def key = it.substring(0, pos)
def value = it.substring(pos + 1)
if (System.getenv(key) == null) {
environment key, value
}
}
}
But actually, I think they should add this feature as a exec plugin property! It's quite common now to use .env file.
The following code is the only one i've been able to produce and which satisfies two of the most importants requirements to provide an efficient "UNIX standard environment file import" in Android studio :
Loads a file which depends of the Build Type (at least : debug and release)
Exposes specified environment variables in the Android code, actually not as environment variables but as buildConfigFields content.
ext {
node_env = ""
}
android.applicationVariants.all { variant ->
if (variant.name == "debug") {
project.ext.set("node_env", "development")
} else if (variant.name == "release") {
project.ext.set("node_env", "production")
}
file("." + node_env + '.env').readLines().each() {
if (!it.isEmpty() && !it.startsWith("#")) {
def pos = it.indexOf("=")
def key = it.substring(0, pos)
def value = it.substring(pos + 1)
if (System.getProperty(key) == null) {
System.setProperty("env.$key", value)
}
}
}
if (variant.name == "release") {
android.signingConfigs.release.storeFile file(System.getProperty("env.ANDROID_APP_SIGNING_STOREFILE"))
android.signingConfigs.release.keyAlias System.getProperty("env.ANDROID_APP_SIGNING_KEYALIAS")
android.signingConfigs.release.storePassword System.getProperty("env.ANDROID_APP_SIGNING_STOREPASSWORD")
android.signingConfigs.release.keyPassword System.getProperty("env.ANDROID_APP_SIGNING_KEYPASSWORD")
}
android.defaultConfig.buildConfigField "String", "ANDROID_APP_URL", "\"${System.getProperty("env.ANDROID_APP_URL")}\""
}
Kotlin :
Log.i(TAG, BuildConfig.ANDROID_APP_URL)
Please let me know what you think of it as i'm not completly sure how it works, especially to select the good file to load.
There are plugins to load env vars from a .env file (e.g. this one)
So a sample build file will look something like this (Kotlin DSL)
plugins {
id("co.uzzu.dotenv.gradle") version "1.1.0"
}
tasks.withType<Test> {
useJUnitPlatform()
//will pass the env vars loaded by the plugin to the environment of the tests
environment = env.allVariables
}
I have ended up doing it in my gradlew file. A possible drawback is that the change tends to be overwritten on upgrades to gradle.
# Hack: export all variables in the .env file
#
ENV_FILE=../../.env
if [ ! -f $ENV_FILE ];then
echo "WARNING/DEV ENV Missing a ${ENV_FILE} file with environment variables (secrets)";
fi
for secret in `cat $ENV_FILE`;do export $secret;done
If you're using Spring Boot bootRun task or anything that has a runner
tasks.named('bootRun') {
doFirst {
file('.env').readLines().each() {
def (key, value) = it.tokenize('=')
environment key, value
}
}
}

Jasmine custom report is not loading all the tests under Sauce labs tab in VSTS

Automated the e2e tests in CI enabled framework with protractor and jasmine in VSTS. Used the jasmine custom reporter to load the e2e test results under sauce labs tab in VSTS build definition. But, it is not loading all the tests. It is displaying only the last e2e test ran in the build. Console log is getting printed for all the e2e tests. Please see the code below.
let sauceLabsReporter: jasmine.CustomReporter = {
specDone: (result: jasmine.CustomReporterResult): void => {
Util.log('*** sauceLabsReporter: result.fullName:', result.fullName);
Util.log('*** sauceLabsReporter: result.status:', result.status);
Util.log('*** sauceLabsReporter: result.testCaseId:', result.testCaseId);
if (result.testCaseId) {
result.fullName = `(Testcase ID: ${result.testCaseId}): ${result.fullName}`;
Util.log('*** sauceLabsReporter: UPDATED result.fullName:', result.fullName);
}
Util.updateSauceLabsJobTitle(result.fullName);
if (result.status) {
Util.updateSauceLabsTestState(result.status);
}
}
};
export function updateSauceLabsJobTitle(title: string): promise.Promise<void> {
let fullTitle: string = `${title} | (${getHostname()})`;
return browser.executeScript(`sauce:job-name=${fullTitle}`)
.then(() => browser.getSession())
.then((session: Session) => {
if (isThisVSTSBuildAgent()) {
//The VSTS Sauce Labs add-on gets information by parsing the console log.
//tslint:disable-next-line:no-console
console.log(`SauceOnDemandSessionID=${session.getId()} job-name=${fullTitle}`);
}
});
}
export function updateSauceLabsTestState(state: string): promise.Promise<{}> {
return browser.executeScript(`sauce:job-result=${state}`);
}
I work on the same project as Padma. It had to do with restartBrowserBetweenTests being set to false which conflates all tests into a single job. After setting it to true, each test became its own job.

Configure swagger in gradle build script with kotlin dsl

I'm trying to switch my simple project from Groovy to Kotlin in build scripts.
I'm using this plugin:
https://github.com/gigaSproule/swagger-gradle-plugin
I have this configuration in my build script:
swagger{
apiSource {
springmvc = false
locations = ['my.location']
schemes = ['https']
host = 'test.com:8080'
info {
title = 'My Service'
version = 'v1'
}
swaggerDirectory = "$buildDir/swagger"
}
To where shall I refer to in this situations?
Shall I do something like?
task( "swagger" ) {
...
}
It is not quite familiar for me.
Thanks.
In case anyone is still looking for this information, this is how you would do it using Gradle Kotlin DSL:
import com.benjaminsproule.swagger.gradleplugin.model.*
plugins {
id("com.benjaminsproule.swagger") version "1.0.0"
}
swagger {
apiSource(closureOf<ApiSourceExtension> {
springmvc = false
schemes = mutableListOf("https")
host = "test.com:8080"
info(closureOf<InfoExtension> {
title = "My Service"
version = "v1"
description = "My Service Description"
termsOfService = "http://www.example.com/termsOfService"
contact(closureOf<ContactExtension> {
email = "email#internet.com"
name = "A Developer"
url = "http://www.internet.com"
})
license(closureOf<LicenseExtension> {
url = "http://www.apache.org/licenses/LICENSE-2.0.html"
name = "Apache 2.0"
})
})
locations = mutableListOf("com.foo.fighting")
swaggerDirectory = "$buildDir/swagger"
})
}
I've tested it using Gradle v4.6.

URISyntaxException in gradle environment variable while testing

I have a build.gradle as follows
task setDockerHost {
group 'Docker'
description 'Gets the docker host ip from your OS'
def stdout = new ByteArrayOutputStream()
exec {
commandLine './src/main/resources/scripts/get-docker-host.sh', '60'
standardOutput = stdout
}
project.ext.set('DOCKERHOST', "$stdout")
}
tasks.withType(Test) {
doFirst { println "DockerHost is $project.DOCKERHOST" }
environment 'DOCKERHOST', "$project.DOCKERHOST"
outputs.upToDateWhen { false }
testLogging {
events 'passed', 'skipped', 'failed', 'standardOut'
}
reports.html.destination = file("${reporting.baseDir}/${name}")
}
I define a DOCKERHOST env variable as above and want to use in my groovy test class:
class MyClass extends Specification {
RESTClient client = new RESTClient("http://"+System.getenv('DOCKERHOST')+":9090/")
...
}
In the execution my println works: DockerHost is 192.168.99.100
But when I run the this test it throws:
I already tried replacing \n, \r and spaces by "". I also try removing the protocol from the URL (aka 192.168.99.10:9090) and it tells me that the same error occurs at index 0
How can I solve this?
I didn't figure it out in which char was the problem but I was able to solve it but replacing strings like crazy:
String url = ("http://" + System.getenv('DOCKERHOST') + ":9090/").replace("\n", "").replace("\r", "").replace(" ", "")
RESTClient client = new RESTClient(url)
I've spent like a day trying to figure this out... hopefully for someone else will be quicker.

Resources