Why does `require 'native'` throw an exception in opalrb? - opalrb

I'm taking baby steps with opalrb, here is my main.rb:
require 'native'
def main
puts "hi from the main function in main.rb"
end
def demoButton
outputDiv = Element.find('output').get(0)
puts outputDiv.methods.sort
end
It's included within <head> after opal.js and ...opal-parser.js" onload="Opal.load('opal-parser')" but the console shows an exception thrown:
{
message: "cannot load such file -- native",
​ name: "LoadError",
​ stack: ""
}
native seems to be part of the opal standard library, so why is there a problem including it?

Add this:
<script src="https://cdn.opalrb.com/opal/current/native.js"></script>
The stdlib part (like native) of Opal isn't included in opal.js. For a full list of stdlib, take a look here:
https://cdn.opalrb.com/opal/current/index.html

Related

nodejs+selenium-driver NoSuchElementError & StaleElementReferenceError

I am doing a test based mocha. node v8.2.1, selenium-webdriver: ^3.5.0.
test.it('demoClass', () => {
driver.classes[0].findElement(By.css('.class-avatar')).click();
driver.wait(until.elementIsVisible(driver.findElement(By.css('.anticon.anticon-plus'))));
//driver.sleep(2000);
driver.findElement(By.css('.anticon.anticon-plus')).click();
})
I am getting two different types of errors, either its NoSuchElementError: no such element: Unable to locate element: or StaleElementReferenceError: stale element reference: element is not attached to the page document
But whichever error, its refer to line:
driver.findElement(By.css('.anticon.anticon-plus')).click();
When I use driver.sleep(2000), its getting resolved. In my opinion, It's the question of animation. I can get the element(.anticon.ancicon-plus) only at the time, the page's animation is completed.
what I am confused is that I use driver.wait(until.elementIsVisible()) without an error, It's obvious that I got the element. but at the next line, I can't use it. Or NoSuchElementError, or StaleElementReferenceError.
I find some answer like http://www.seleniumhq.org/exceptions/stale_element_reference.jsp,https://stackoverflow.com/questions/18225997/stale-element-reference-element-is-not-attached-to-the-page-document. But It can't help me.
when use driver.findElement, something terrible will be triggered. use javascript instead it.
driver.executeScript(function() {
while(true) {
if(!document.querySelector('.anticon.anticon-plus')){}
else {
document.querySelector('.anticon.anticon-plus').click();
break;
}
}
return true; // not neccessary
})

what is shouldFail in groovy?

How does the code within the 'shouldFail?' block work? I understand that it is a closure, but the code gets called regardless of whether or not I call is using its signature. Besides, what's the deal with the "ReadOnlyPropertyException" showing up in the parenthesis? If it is a parameter, then it is not setup as listed in the official documentation!!
Questions: What is 'shouldFail'? How should it be invoked? How to handle the exception purportedly thrown by this method/function/closure?
void test02_ReadOnlyFieldInGroovyBean() {
// You've probably noticed how Groovy automatically generates getters/setters for you. But what if you don't
// want to generate a setter because it's a read-only field? Just mark it with 'final'. Groovy will understand.
// Try to modify Ken's ssn. You should get a ReadOnlyPropertyException.
def person = new GroovyPerson('Ken', 'Kousen', '7878')
def failed = false
shouldFail (ReadOnlyPropertyException) {
// ------------ START EDITING HERE ----------------------
System.out.println(" i am in should fail")
person.ssn='8332';
// ------------ STOP EDITING HERE ----------------------
failed = false
System.out.println(" exiting should fail")
}
//def foobar=shouldFail("hjh");
//def foobar=true;
failed=shouldFail('abc');
//System.out.println("Failed: "+failed);
assert failed
// The code wrapping your additions verifies that the ReadOnlyProperty exception has been thrown.
// The curly brackets ({}) represent a closure. We'll get into what that means very soon.
}
shouldFail() (in this variant) takes a class and a closure. It runs the closure and reports a test failure if the closure does NOT exit by throwing an exception of that type. As to catching the exception, you don't - shouldFail() does that for you.
See: http://docs.groovy-lang.org/latest/html/gapi/groovy/test/GroovyAssert.html#shouldFail%28java.lang.Class,%20groovy.lang.Closure%29
(Reading the comments and the code around them, it looks like this unit test should pass because setting the .ssn property of GroovyPerson will fail as it is a read-only property, causing a ReadOnlyPropertyException.)

Error: Invalid cache option true found. Expected "memory"

this error shows in cmd using rhc tail socialinteractive
i hosted this site to openshfit i use swig and modules consolidate and swing for template
guide me to slove this error
Error: Invalid cache option true found. Expected "memory" or { get: function (ke
y) { ... }, set: function (key, value) { ... } }.
at validateOptions (/var/lib/openshift/5453580c500446bfbc000d3c/app-root/run
time/repo/node_modules/swig/lib/swig.js:113:15)
at parse (/var/lib/openshift/5453580c500446bfbc000d3c/app-root/runtime/repo/
node_modules/swig/lib/swig.js:339:5)
at Object.precompile (/var/lib/openshift/5453580c500446bfbc000d3c/app-root/r
untime/repo/node_modules/swig/lib/swig.js:486:23)
at Object.compile (/var/lib/openshift/5453580c500446bfbc000d3c/app-root/runt
ime/repo/node_modules/swig/lib/swig.js:606:16)
at Function.exports.swig.render (/var/lib/openshift/5453580c500446bfbc000d3c
/app-root/runtime/repo/node_modules/consolidate/lib/consolidate.js:246:56)
at /var/lib/openshift/5453580c500446bfbc000d3c/app-root/runtime/repo/node_mo
dules/consolidate/lib/consolidate.js:146:25
at read (/var/lib/openshift/5453580c500446bfbc000d3c/app-root/runtime/repo/n
ode_modules/consolidate/lib/consolidate.js:91:22)
at /var/lib/openshift/5453580c500446bfbc000d3c/app-root/runtime/repo/node_mo
dules/consolidate/lib/consolidate.js:144:9
at readPartials (/var/lib/openshift/5453580c500446bfbc000d3c/app-root/runtim
e/repo/node_modules/consolidate/lib/consolidate.js:114:33)
at View.engine (/var/lib/openshift/5453580c500446bfbc000d3c/app-root/runtime
/repo/node_modules/consolidate/lib/consolidate.js:139:5)
GET / 500 4.312 ms - -
This is consolidate.js bug, not OpenShift bug.
It has been already addressed upstream, see:
https://github.com/tj/consolidate.js/pull/134
Either you need to update your consolidate.js npm package once they release version greater than 0.10.0.
Or you can use the following workaround (as suggested by #truongminh):
app.locals.cache = "memory"

How to Report Results to Sauce Labs using Geb/Spock?

I want to use the Sauce Labs Java REST API to send Pass/Fail status back to the Sauce Labs dashboard. I am using Geb+Spock, and my Gradle build creates a test results directory where results are output in XML. My problem is that the results XML file doesn't seem to be generated until after the Spock specification's cleanupSpec() exits. This causes my code to report the results of the previous test run, rather than the current one. Clearly not what I want!
Is there some way to get to the results from within cleanupSpec() without relying on the XML? Or a way to get the results to file earlier? Or some alternative that will be much better than either of those?
Some code:
In build.gradle, I specify the testResultsDir. This is where the XML file is written after the Spock specifications exit:
drivers.each { driver ->
task "${driver}Test"(type: Test) {
cleanTest
systemProperty "geb.env", driver
testResultsDir = file("$buildDir/test-results/${driver}")
systemProperty "proj.test.resultsDir", testResultsDir
}
}
Here is the setupSpec() and cleanupSpec() in my LoginSpec class:
class LoginSpec extends GebSpec {
#Shared def SauceREST client = new SauceREST("redactedName", "redactedKey")
#Shared def sauceJobID
#Shared def allSpecsPass = true
def setupSpec() {
sauceJobID = driver.getSessionId().toString()
}
def cleanupSpec() {
def String specResultsDir = System.getProperty("proj.test.resultsDir") ?: "./build/test-results"
def String specResultsFile = this.getClass().getName()
def String specResultsXML = "${specResultsDir}/TEST-${specResultsFile}.xml"
def testsuiteResults = new XmlSlurper().parse( new File( specResultsXML ))
// read error and failure counts from the XML
def errors = testsuiteResults.#errors.text()?.toInteger()
def failures = testsuiteResults.#failures.text()?.toInteger()
if ( (errors + failures) > 0 ) { allSpecsPass = false }
if ( allSpecsPass ) {
client.jobPassed(sauceJobID)
} else {
client.jobFailed(sauceJobID)
}
}
}
The rest of this class contains login specifications that do not interact with SauceLabs. When I read the XML, it turns out that it was written at the end of the previous LoginSpec run. I need a way to get to the values of the current run.
Thanks!
Test reports are generated after a Specification has finished execution and the generation is performed by the build system, so in your case by Gradle. Spock has no knowledge of that so you are unable to get that information from within the test.
You can on the other hand quite easily get that information from Gradle. Test task has two methods that might be of interest to you here: addTestListener() and afterSuite(). It seems that the cleaner solution here would be to use the first method, implement a test listener and put your logic in afterSuite() of the listener (and not the task configuration). You would probably need to put that listener implementation in buildSrc as it looks like you have a dependency on SauceREST and you would need to build and compile your listener class before being able to use it as an argument to addTestListener() in build.gradle of your project.
Following on from erdi's suggestion, I've created a Sauce Gradle helper library, which provides a Test Listener that parses the test XML output and invokes the Sauce REST API to set the pass/fail status.
The library can be included by adding the following to your build.gradle file:
import com.saucelabs.gradle.SauceListener
buildscript {
repositories {
mavenCentral()
maven {
url "https://repository-saucelabs.forge.cloudbees.com/release"
}
}
dependencies {
classpath group: 'com.saucelabs', name: 'saucerest', version: '1.0.2'
classpath group: 'com.saucelabs', name: 'sauce_java_common', version: '1.0.14'
classpath group: 'com.saucelabs.gradle', name: 'sauce-gradle-plugin', version: '0.0.1'
}
}
gradle.addListener(new SauceListener("YOUR_SAUCE_USERNAME", "YOUR_SAUCE_ACCESS_KEY"))
You will also need to output the Selenium session id for each test, so that the SauceListener can associate the Sauce Job with the pass/fail status. To do this, include the following output in the stdout:
SauceOnDemandSessionID=SELENIUM_SESSION_ID

How do I print a Groovy stack trace?

How do I print a Groovy stack trace? The Java method, Thread.currentThread().getStackTrace() produces a huge stack trace, including a lot of the Groovy internals. I'm seeing a function called twice from a StreamingMarkupBuilder that looks like it should only be called once and I would like to see why Groovy thinks it should be calling it twice.
Solution:
org.codehaus.groovy.runtime.StackTraceUtils.sanitize(new Exception()).printStackTrace()
Original answer:
A Google search returns the following information:
Apparently, there is a method in org.codehaus.groovy.runtime.StackTraceUtils called printSanitizedStackTrace. There isn't much documentation for the method, though there is a method called sanitize which is described as
remove all apparently groovy-internal
trace entries from the exception
instance This modifies the original
instance and returns it, it does not
clone
So I would try org.codehaus.groovy.runtime.StackTraceUtils.printSanitizedStackTrace(Throwable t) (it is static)
and see if that works for you.
I found this questions when searching for "spock print full stack trace".
My unit tests are written in Groovy, using the Spock testing framework and they're run in the context of a Gradle build.
The fix for me was as simple as adding exceptionFormat = 'full' to my Gradle test task specification:
test {
testLogging {
exceptionFormat = 'full'
}
}
I have designed this simple code for stack trace printing, based on artificial simulation of a NullPointerException.
This code produces the same output in both modes: from a Jenkinsfile (Pipeline) and from a normal .groovy script in a command line.
def getStackTrace() {
try {
null.class.toString() // simulate NPE
} catch (NullPointerException e) {
return e.getStackTrace()
}
return null
}
def printStackTrace() {
def stackTraceStr = ""
def callingFuncFound = false
for (StackTraceElement ste : getStackTrace()) {
if (callingFuncFound) {
stackTraceStr += ste.toString() + '\n'
}
if (!callingFuncFound && ste.toString().startsWith(this.class.name + '.printStackTrace(')) {
callingFuncFound = true
}
}
println(stackTraceStr)
}
Some explanations:
The output is concatenated into a single string to avoid being mixed with "[Pipeline] echo" message prefix of Jenkins Pipeline's println()).
The number of "unnecessary" upper stack trace elements related to the NPE is different in Jenkinsfile and in a normal command line. This is why I calculate callingFuncFound and don't use just something like e.getStackTrace()[2..-1] to skip them.

Resources