Zend_Test_PHPUnit how to print exception/output? - zend-framework

How can I echo a html/xml output from a controller action in my test case?
Here is my testcase:
public function testCreateAccountIsASuccessfulRequest()
{
$this->dispatch('/v2/user/create-account');
$this->assertFalse($this->response->isException());
$this->assertNotRedirect();
}
Which prints this in commandline:
test# /usr/local/bin/phpunit --verbose Controllers_UserControllerTest.php
PHPUnit 3.6.10 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 12.50Mb
There was 1 failure:
1) Controllers_UserControllerTest::testCreateAccountIsASuccessfulRequest
Failed asserting that true is false.
/path/to/tests/Controllers/UserControllerTest.php:17
/usr/local/bin/phpunit:46
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
test#
I am not sure what is the actual exception. How to see it? Also, how can I see the actual output of the controller action? So HTML/XML it sends to browser?

God I am slow today:
public function testCreateAccountIsASuccessfulRequest()
{
$this->dispatch('/v2/user/create-account');
echo $this->getResponse()->getBody();
$this->assertFalse($this->response->isException());
$this->assertNotRedirect();
}

Related

Apache Beam TextIO.read().from() does not interpret escaped special character in filepattern

Environment
Java SDK 2.33.0
Setup
$ mkdir -p /tmp/beam
$ echo "test" >> "/tmp/beam/test*.txt"
Test pipeline
public class PipelineTest {
#Test
public void test() {
Pipeline p = TestPipeline.create().enableAbandonedNodeEnforcement(false);
String filename = "/tmp/beam/test\\*.txt";
PCollection<String> input = p.apply(TextIO.read().from(filename));
PAssert.that(input).containsInAnyOrder("test");
p.run();
}
}
This test fails with below messages.
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 10.66 s <<< FAILURE! - in PipelineTest
[ERROR] test Time elapsed: 10.645 s <<< ERROR!
org.apache.beam.sdk.Pipeline$PipelineExecutionException: java.io.FileNotFoundException: No files matched spec: /tmp/beam/test\*.txt
at PipelineTest.test(PipelineTest.java:28)
Caused by: java.io.FileNotFoundException: No files matched spec: /tmp/beam/test\*.txt
How can I read files that contain asterisks or other special characters?
For now you'll simply have to rename such files. I've filed https://issues.apache.org/jira/browse/BEAM-13231

How can I mark some ScalaTests so that they only execute when invoked explicitly

I'm new to SBT and scalatest but am wondering how I get some of my org.scalatest._ tests to only execute "on demand".
In SBT I can invoke all of the Unit Tests like sbt:Sprout> test, or all of the IntegrationTests like sbt:Sprout> it:test. I need a way to annotate the tests that allows an sbt:Sprout test invocation to skip them but with some other invocation executes ONLY these tests. Scalatest docs speak of some sbt:Sprout> test-only *RedSuite invocation to allow me to "Categorize" my tests, but its not clear how to leverage that so they DON'T run as Unit Tests. org.scalatest.Tags alone do not get it off the "default" of getting executed when sbt:Sprout> test. I need these to be ignored unless invoked explicitly.
Is this use case possible in ScalaTest through SBT?
You can specify tag names of tests to include or exclude from a run. To specify tags to include, use -n followed by a list of tag names to include. Similarly, to specify tags to exclude, use -l followed by a list of tag names to exclude
(please look here for more info in the official documents).
For example:
package com.test
import org.scalatest.FlatSpec
import org.scalatest.Tag
object IncludeTest extends Tag("com.tags.Include")
object ExcludeTest extends Tag("com.tags.Exclude")
class TestSuite extends FlatSpec {
"Test1" taggedAs(IncludeTest) in {
val sum = 1 + 1
assert(sum === 2)
}
"Test2" taggedAs(ExcludeTest) in {
val minus = 2 - 1
assert(minus === 1)
}
}
To include IncludeTest and exclude ExcludeTest tag, you should do:
test-only org.* -- -n com.tags.Include -l com.tags.Exclude
assume assertion specified inside a fixture-context object could be used to implement conditional-ignore semantics dependant on environmental flag. For example, consider the following IfIgnored fixture
trait IfIgnored extends Assertions {
assume(System.getenv("runIgnoredTest").toBoolean, "!!! TEST IGNORED !!!")
}
which can be instantiated like so
it should "not say goodbye" in new IfIgnored {
Hello.greeting shouldNot be ("goodbye")
}
Now if we define the following settings in build.sbt
Test / fork := true,
Test / envVars := Map("runIgnoredTest" -> "false")
and the following tests
class HelloSpec extends FlatSpec with Matchers {
"The Hello object" should "say hello" in {
Hello.greeting shouldEqual "hello"
}
it should "not say goodbye" in new IfIgnored {
Hello.greeting shouldNot be ("goodbye")
}
it should "not say live long and prosper" in new IfIgnored {
Hello.greeting shouldNot be ("live long and prosper")
}
}
then executing sbt test should output
[info] HelloSpec:
[info] The Hello object
[info] - should say hello
[info] - should not say goodbye !!! CANCELED !!!
[info] scala.Predef.augmentString(java.lang.System.getenv("runIgnoredTest")).toBoolean was false !!! TEST IGNORED !!! (HelloSpec.scala:6)
[info] - should not say live long and prosper !!! CANCELED !!!
[info] scala.Predef.augmentString(java.lang.System.getenv("runIgnoredTest")).toBoolean was false !!! TEST IGNORED !!! (HelloSpec.scala:6)
[info] Run completed in 2 seconds, 389 milliseconds.
[info] Total number of tests run: 1
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 1, failed 0, canceled 2, ignored 0, pending 0
[info] All tests passed.
where we see only should say hello ran whilst the rest were ignored.
To execute only ignored tests we could define the following custom command testOnlyIgnored:
commands += Command.command("testOnlyIgnored") { state =>
val ignoredTests = List(
""""should not say goodbye"""",
""""should not say live long and prosper""""
).mkString("-z ", " -z ", "")
"""set Test / envVars := Map("runIgnoredTest" -> "true")""" ::
s"""testOnly -- $ignoredTests""" :: state
}
Note how we are making use of -z runner argument to run particular tests, for example,
testOnly -- -z "should not say goodbye" -z "should not say live long and prosper"
Also note how we are manually adding test names to ignoredTests. Now executing sbt testOnlyIgnored should output
[info] HelloSpec:
[info] The Hello object
[info] - should not say goodbye
[info] - should not say live long and prosper
[info] Run completed in 2 seconds, 298 milliseconds.
[info] Total number of tests run: 2
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 2, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.
where we see should say hello was not run whilst all the ignored tests ran.
If we drop the requirement of having to run ignored tests separately, then we can use provided ignore annotation like so
ignore should "not say goodbye" in {
Hello.greeting shouldNot be ("goodbye")
}
which on sbt test outputs
[info] HelloSpec:
[info] The Hello object
[info] - should say hello
[info] - should not say goodbye !!! IGNORED !!!
[info] - should not say live long and prosper !!! IGNORED !!!
[info] Run completed in 2 seconds, 750 milliseconds.
[info] Total number of tests run: 1
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 1, failed 0, canceled 0, ignored 2, pending 0

Publish Nunit Test Results in Post Always Section

I'm trying to run a pipeline that does some Pester Testing and publish the NUnit results.
New tests were introduced and for whatever the reason, Jenkins no longer publishes the test results and errors out immediately after the powershell script. Hence, it doesn't get to the nunit publish piece. I receive this:
ERROR: script returned exit code 128
Finished: FAILURE
I've been trying to include the publish in the always section of the post section of the Jenkinsfile, however, I'm running into problems on how to make that NUnit test file available.
I've tried establishing an agent and unstash the file (even though it probably won't stash if the powershell script cancels the whole pipeline). When I use agent I get the following exception:
java.lang.NoSuchMethodError: No such DSL method 'agent' found among steps
Here is the Jenkinsfile:
pipeline {
agent none
environment {
svcpath = 'D:\\svc\\'
unitTestFile = 'UnitTests.xml'
}
stages {
stage ('Checkout and Stash') {
agent {label 'Agent1'}
steps {
stash name: 'Modules', includes: 'Modules/*/**'
stash name: 'Tests', includes: 'Tests/*/**'
}
}
stage ('Unit Tests') {
agent {label 'Agent1'}
steps {
dir(svcpath + 'Modules\\'){deleteDir()}
dir(svcpath + 'Tests\\'){deleteDir()}
dir(svcpath){
unstash name: 'Modules'
unstash name: 'Tests'
}
dir(svcpath + 'Tests\\'){
powershell """
\$requiredCoverageThreshold = 0.90
\$modules = Get-ChildItem ../Modules/ -File -Recurse -Include *.psm1
\$result = Invoke-Pester -CodeCoverage \$modules -PassThru -OutputFile ${unitTestFile} -OutputFormat NUnitXml
\$codeCoverage = \$result.CodeCoverage.NumberOfCommandsExecuted / \$result.CodeCoverage.NumberOfCommandsAnalyzed
Write-Output \$codeCoverage
if (\$codeCoverage -lt \$requiredCoverageThreshold) {
Write-Output "Build failed: required code coverage threshold of \$(\$requiredCoverageThreshold * 100)% not met. Current coverage: \$(\$codeCoverage * 100)%."
exit 1
} else {
write-output "Required code coverage threshold of \$(\$requiredCoverageThreshold * 100)% met. Current coverage: \$(\$codeCoverage * 100)%."
}
"""
stash name: 'TestResults', includes: unitTestFile
nunit testResultsPattern: unitTestFile
}
}
post {
always {
echo 'This will always run'
agent {label 'Agent1'}
unstash name: 'TestResults'
nunit testResultsPattern: unitTestFile
}
success {
echo 'This will run only if successful'
}
failure {
echo 'This will run only if failed'
}
unstable {
echo 'This will run only if the run was marked as unstable'
}
changed {
echo 'This will run only if the state of the Pipeline has changed'
echo 'For example, if the Pipeline was previously failing but is now successful'
}
}
}
Any and all input is welcome! Thanks!
The exception you are getting is due to Jenkins' strict pipeline DSL. Documentation of allowable uses of agent are here.
Currently agent {...} is not allowed to be used in the post section. Maybe this will change in the future. If you require the whole job to run on the node that services label 'Agent1' the only way to currently do that is to
Put agent {label 'Agent1'} immediately under pipeline { to make it global
Remove all instances of agent {label 'Agent1'} in each stage
Remove the agent {label 'Agent1'} from the post section.
The post section acts more like traditional scripted DSL than the pipeline declarative DSL. So you have to use node() instead of agent.
I believe I've had this same question myself, and this SO post has the answer and some good context.
This Jenkins issue isn't exactly the same thing but shows the node syntax in the post stage.

Protractor jasmine2-protractor-util TypeError: Cannot read property 'forEach' of undefined

I've got a problem with separated protractor specs. I've trying to divide 1 test 1 spec. And got a error message like
E/launcher - Cannot read property 'forEach' of undefined
E/launcher - TypeError: Cannot read property 'forEach' of undefined
at C:\Users\mako\AppData\Roaming\npm\node_modules\jasmine2-protractor-utils\reporter\jasmine2_reporter.js:112:24
at Array.forEach (native)
at self.jasmineDone (C:\Users\mako\AppData\Roaming\npm\node_modules\jasmine2-protractor-utils\reporter\jasmine2_reporter.js:108:16)
at dispatch (C:\Users\mako\AppData\Roaming\npm\node_modules\protractor\node_modules\jasmine-core\lib\jasmine-core\jasmine.js:1966:28)
at ReportDispatcher.jasmineDone (C:\Users\mako\AppData\Roaming\npm\node_modules\protractor\node_modules\jasmine-core\lib\jasmine-core\jasmine.js:1
949:11)
at C:\Users\mako\AppData\Roaming\npm\node_modules\protractor\node_modules\jasmine-core\lib\jasmine-core\jasmine.js:758:18
at QueueRunner.clearStack (C:\Users\mako\AppData\Roaming\npm\node_modules\protractor\node_modules\jasmine-core\lib\jasmine-core\jasmine.js:660:9)
at QueueRunner.run (C:\Users\mako\AppData\Roaming\npm\node_modules\protractor\node_modules\jasmine-core\lib\jasmine-core\jasmine.js:1881:12)
at C:\Users\mako\AppData\Roaming\npm\node_modules\protractor\node_modules\jasmine-core\lib\jasmine-core\jasmine.js:1898:16
at C:\Users\mako\AppData\Roaming\npm\node_modules\protractor\node_modules\jasmine-core\lib\jasmine-core\jasmine.js:1842:9
E/launcher - Process exited with error code 199
Test cases are running properly, error happens after all suites are done.
Problem disappear if spec have more than on "it" even empty. Have you got any ideas what can be a problem?
I would suggest to add a piece of code which returns a promise , to your onPrepare block of Protractor configuration file.
For Example:
onPrepare: function () {
// returning the promise makes protractor wait for the reporter config before executing tests
return global.browser.getProcessedConfig().then(function (config) {
});
}
I "solve" problem.
/*plugins: [{
package: 'jasmine2-protractor-utils',
disableHTMLReport: false,
disableScreenshot: false,
screenshotPath:'./test_results/E2E/screenshots',
screenshotOnExpectFailure:true,
screenshotOnSpecFailure:true,
clearFoldersBeforeTest: true,
htmlReportDir: './test_results/E2E/htmlReports',
/*failTestOnErrorLog: {
failTestOnErrorLogLevel: 900,
excludeKeywords: ['keyword1', 'keyword2']
}*/
// }],
And the problem is with plugin 'jasmine2-protractor-utils'. If I've got two specs and one test each error happens. Without this plugin or if I add empty test to one of them it works fine.

How to create a task that prints command line arguments?

I'm finding the documentation at http://www.scala-sbt.org/0.13/docs/Input-Tasks.html utterly baffling. Can someone provide me with a complete example of a task/input task that takes a command line argument and does something with it e.g.:
sbt "greeting hello world"
and prints "hello world"
Following the document Input Tasks (with the main change to the name of the input task so it's greeting):
import sbt.complete.Parsers.spaceDelimited
val greeting = inputKey[Unit]("A demo input task.")
greeting := {
val args: Seq[String] = spaceDelimited("<arg>").parsed
args foreach println
}
With the above in build.sbt, you can call the input task from the console:
> greeting "hello world"
hello world
or from the command line:
➜ so-25596401 xsbt 'greeting "hello world"'
[info] Loading global plugins from /Users/jacek/.sbt/0.13/plugins
[info] Set current project to so-25596401 (in build file:/Users/jacek/sandbox/so-25596401/)
hello world
[success] Total time: 0 s, completed Sep 1, 2014 1:34:31 AM
Note the quotes that designate what is the single task/command with arguments.