phpunit not marking test as completed and successful - zend-framework2

I'm having issues getting phpunit to positively test a method i created. im using a zend application and the ApplicationTest works fine. Here's my current command line output:
ApplicationTest\Controller\IndexController
[x] Sample not active
[x] Index action can be accessed
[x] Index action view model template rendered within layout
[x] Invalid route does not crash
PlutoTest\Stdlib\ArrayUtils
[ ] Sample not active
As you can see, there is no X inside my ArrayUtils test. I even put the method inside the ApplicationTest and you can see it executed correctly.
Here's the phpunit class:
namespace PlutoTest\Stdlib;
use Pluto\Stdlib\ArrayUtils;
use Pluto\pluto;
use PHPUnit\Framework\TestCase;
class ArrayUtilsTest extends TestCase
{
public function setUp()
{
$configOverrides = [];
$phpunitConfigFile=$this->getNormalizedPhpunitConfigFile();
$this->setApplicationConfig(ArrayUtils::merge(
include $phpunitConfigFile,
$configOverrides
));
parent::setUp();
}
private function getNormalizedPhpunitConfigFile()
{
$file = sprintf('%s/application.phpunit.php',pluto::path('zfconfig'));
return $file;
}
public function testSampleNotActive()
{
$stack = [];
$this->assertEquals(0, count($stack));
array_push($stack, 'foo');
$this->assertEquals('foo', $stack[count($stack)-1]);
$this->assertEquals(1, count($stack));
$this->assertEquals('foo', array_pop($stack));
$this->assertEquals(0, count($stack));
}
}
Here's my phpunit.xml:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
colors="true"
bootstrap="bootstrap.phpunit.php"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/6.3/phpunit.xsd"
backupGlobals="true"
backupStaticAttributes="false"
cacheTokens="false"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
forceCoversAnnotation="true"
processIsolation="false"
stopOnError="false"
stopOnFailure="false"
stopOnIncomplete="false"
stopOnSkipped="false"
timeoutForSmallTests="1"
timeoutForMediumTests="10"
timeoutForLargeTests="60"
beStrictAboutTestsThatDoNotTestAnything="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTestSize="true"
verbose="true">
<testsuites>
<testsuite name="Application Module Test Suite">
<directory phpVersion="7.0.0" phpVersionOperator=">=">./module/Application/test</directory>
<directory phpVersion="7.0.0" phpVersionOperator=">=">./test/pluto/src</directory>
</testsuite>
</testsuites>
<php>
<env name="APPLICATION_ENV" value="development"/>
<ini name="display_errors" value="1"/>
<ini name="display_startup_errors" value="1"/>
<ini name="error_reporting" value="32767"/>
<ini name="report_memleaks" value="1"/>
</php>
</phpunit>
And here's my composer:
"autoload-dev" : {
"psr-4" : {
"ApplicationTest\\" : "module/Application/test/",
"PlutoTest\\" : "test/pluto/src"
}
},

Try changing as the following:
"autoload-dev": {
"psr-4": {
...
"YourModuleNameTest\\": "module/YourModuleName/test/"
}
},
If done, do not forget to run dump-autoload through composer in your terminal.
What if you modify your phpunit.xml this way:
<testsuites>
<testsuite name="Application Module Test Suite">
<directory phpVersion="7.0.0" phpVersionOperator=">=">./module/Application/test</directory>
</testsuite>
<testsuite name="YourModuleName">
<directory phpVersion="7.0.0" phpVersionOperator=">=">./module/YourModuleName/test</directory>
</testsuite>
</testsuites>
Next up, run the following command:
./vendor/bin/phpunit --testsuite YourModuleName
To list all available suites, run the following command:
./vendor/bin/phpunit --list-suites
To list all available tests, run the following command:
./vendor/bin/phpunit --list-tests

Related

KahaDb properties in Grails

Using ActiveMQ in Grails through JMS plugin I cannot figure how to set KahaDb persistence properties.
Tried something like:
amq.broker(useJmx: true, persistent: true) {
amq.transportConnectors() {
amq.transportConnector(uri: "tcp://0.0.0.0:61616")
}
amq.persistenceAdapter() {
amq.kahaDB(directory:${application.config.grails.moviesxd.activemq.kahadb},
checksumJournalFiles:true,
checkForCorruptJournalFiles:true,
ignoreMissingJournalfiles:true)
}
}
But i get
groovy.lang.GroovyRuntimeException: Namespace prefix: kahadb is not bound to a URI
Seems like kahadb prefix is not recognized but i cannot find documentation anywhere on how to do this.
You're just missing the equivalent of
xmlns:amq='http://activemq.apache.org/schema/core'
which would be
xmlns amq:'http://activemq.apache.org/schema/core'
(see the reference docs for more info - search for "Using Spring Namespaces")
so the whole conversion would be
import org.springframework.jms.connection.SingleConnectionFactory
xmlns amq:'http://activemq.apache.org/schema/core'
amq.broker(useJmx: true, persistent: true) {
amq.transportConnectors {
amq.transportConnector(uri: 'tcp://0.0.0.0:61616')
}
amq.persistenceAdapter {
amq.kahaDB(directory: application.config.grails.moviesxd.activemq.kahadb,
checksumJournalFiles: true,
checkForCorruptJournalFiles: true,
ignoreMissingJournalfiles: true)
}
}
amq.connectionFactory(id: 'amqConnectionFactory', brokerURL: 'vm://localhost')
jmsConnectionFactory(SingleConnectionFactory, ref('amqConnectionFactory'))
As a workaround what i've done is to include an additional resources.xml and use standard and well documented XML properties as:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:amq="http://activemq.apache.org/schema/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">
<amq:broker useJmx="true" persistent="true">
<amq:transportConnectors>
<amq:transportConnector uri="tcp://0.0.0.0:61616" />
</amq:transportConnectors>
<amq:persistenceAdapter>
<amq:kahaDB directory="${grails.moviesxd.activemq.kahadb.path}" />
</amq:persistenceAdapter>
</amq:broker>
<amq:connectionFactory id="amqConnectionFactory"
brokerURL="vm://localhost" />
<bean id="jmsConnectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
<constructor-arg ref="amqConnectionFactory" />
</bean>
</beans>
... but it's a piti i have to do this ... still will be great if i get an answer.

Specifying filenames for ant junit batchtest

I have a working ant-task that runs me a batch of junit-tests, in the following fashion:
<junit printsummary="yes" showoutput="yes" haltonfailure="no">
<formatter type="plain" />
<classpath>
<path refid="app.compile.classpath" />
<path id="classes" location="${app.classes.home}" />
<path id="test-classes" location="${app.build.home}/test-classes" />
</classpath>
<batchtest fork="no" todir="${app.tests.reports}">
<fileset dir="${app.tests.home}">
<include name="**/*Test*.java" />
</fileset>
</batchtest>
</junit>
Now this works fine right now, except for the names of the Test-reports that are generated. These names are overly long and follow the pattern:
TEST-com.company.package.Class.txt
Is there a way for specify a file-naming pattern for the report files for batchtest, preferrably for ant 1.6.5?
I know that for a single test, you can specify a filename by using the outfile attribute. In the junit-task reference, it's just stated that:
It then generates a test class name for each resource that ends in .java or .class.
No, it's not possible.
According to the source code
protected void execute(JUnitTest arg, int thread) throws BuildException {
validateTestName(arg.getName());
JUnitTest test = (JUnitTest) arg.clone();
test.setThread(thread);
// set the default values if not specified
//#todo should be moved to the test class instead.
if (test.getTodir() == null) {
test.setTodir(getProject().resolveFile("."));
}
if (test.getOutfile() == null) {
test.setOutfile("TEST-" + test.getName());
}
// execute the test and get the return code
TestResultHolder result = null;
if (!test.getFork()) {
result = executeInVM(test);
} else {
ExecuteWatchdog watchdog = createWatchdog();
result = executeAsForked(test, watchdog, null);
// null watchdog means no timeout, you'd better not check with null
}
actOnTestResult(result, test, "Test " + test.getName());
}
it will create the out file as "TEST-" + test.getName() if you don't specify it explicitly in the test element. It's not possible to specify it in batchtest element.

Get an entry of a Manifest file with ant

I am trying to develope an Ant macrodef which gets the values separated by commas of the Require-Bundle property in a Manifest file passed as parameter. What I want to obtain is something like this:
Require-Bundle=org.eclipse.ui,org.eclipse.ui.ide,org.eclipse.ui.views...
The problem I am facing in my code is that it doesn't take into account if the property has multiple values in multiple lines, here is my code:
<macrodef name="getDependencies">
<attribute name="file" />
<attribute name="prefix" default="ant-mf." />
<sequential>
<loadproperties>
<file file="#{file}" />
<filterchain>
<linecontains>
<contains value="Require-Bundle" />
</linecontains>
<prefixlines prefix="#{prefix}" />
</filterchain>
</loadproperties>
</sequential>
</macrodef>
But this is what I get:
[echoproperties] ant-mf.Require-Bundle=org.eclipse.ui,
Any help will be appreciated.
Most likely, your Manifest file looks like this:
Require-Bundle: org.eclipse.ui,
org.eclipse.ui.ide,
org.eclipse.ui.views,
...
Unfortunately, Java Manifest files aren't quite Java Properties files. Manifest files can have attributes that span multiple lines whereas Property files can't have multi-line values. The <loadproperties> task can't handle multi-line attributes.
Instead, you'll need an Ant task that knows about Manifest files. In another question, Richard Steele provides Ant script that loads a Manifest file from a Jar file. You can adapt the example to get just the Require-Bundle attribute.
Thanks to Chad Nouis I have changed the macrodef approach to scriptdef. I have debugged and adapted the Richard Steele script to fit my needs:
<!--
Loads entries from a manifest file.
#manifest A manifest file to read
#entry The name of the manifest entry to load (optional)
#prefix A prefix to prepend (optional)
-->
<scriptdef name="getDependencies" language="javascript" description="Gets all entries or a specified one of a manifest file">
<attribute name="manifest" />
<attribute name="entry" />
<attribute name="prefix" />
<![CDATA[
var filename = attributes.get("manifest");
var entry = attributes.get("entry");
if (entry == null) {
entry = "";
}
var prefix = attributes.get("prefix");
if (prefix == null) {
prefix = "";
}
var manifest;
if (filename != null) {
manifest = new java.util.jar.Manifest(new java.io.FileInputStream(new java.io.File(filename)));
} else {
self.fail("File is required");
}
if (manifest == null) {
self.log("Problem loading the Manifest");
} else {
var attributes = manifest.getMainAttributes();
if (attributes != null) {
if (entry != "") {
project.setProperty(prefix + entry, attributes.getValue(entry));
} else {
var it = attributes.keySet().iterator();
while (it.hasNext()) {
var key = it.next();
project.setProperty(prefix + key, attributes.getValue(key));
}
}
}
}
]]>
</scriptdef>

log4j2 runtime reconfiguration not working - empty file created

I am trying to manually reconfigure log4j2 at runtime but getting partial success.
Here is the relevant code:
package examples.test;
public class ABCImpl implements XYX{
static Logger logger;
public void initialize(){
LoggerContext ctx = null;
Configuration config = null;
Map mp = null;
ctx = (LoggerContext) LogManager.getContext(false);
config = (Configuration)ctx.getConfiguration();
mp = config.getAppenders();
System.out.println("***<Provider o/p follows> Before logger re-configuration:");
System.out.println("\tAppenders:" + mp.keySet());
//reconfiguration attempt - starts
try{
URI configuration = this.getClass().getResource("/log4j2.xml").toURI();
ctx = Configurator.initialize(this.getClass().getName(), null, configuration);
}catch(Exception e){
System.out.println("\t-------Exception encountered-------");
e.printStackTrace();
}
config = (Configuration) ctx.getConfiguration();
mp = config.getAppenders();
System.out.println("***<Provider o/p follows> After logger re-configuration:");
System.out.println("\tAppenders:" + mp.keySet());
//reconfiguration attempt - ends
logger = LogManager.getLogger(this.getClass().getName());
}
public void myBusinessMethod(){
logger.info("Entry..............");
logger.info("Exit..............");
}
}
This class is actually part of a jar file and am running it inside an application server which guarantees that my initialize method would be called as soon as my class is instantiated.
Here is my log4j2.xml, which I have packed into jar's root:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Don't forget to set system property
-DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
to make all loggers asynchronous. -->
<Configuration status="info">
<Appenders>
<!-- Async Loggers will auto-flush in batches, so switch off immediateFlush. -->
<RollingRandomAccessFile name="Appender1" fileName="servers/${sys:weblogic.Name}/logs/Auditing_${sys:weblogic.Name}.log" immediateFlush="true" append="false" filePattern="servers/${sys:weblogic.Name}/logs/archive/Auditing_${sys:weblogic.Name}-%d{yyyy-MM-dd-HH}-%i.log.gz">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m %ex%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
<SizeBasedTriggeringPolicy size="250 MB"/>
</Policies>
<DefaultRolloverStrategy max="20"/>
</RollingRandomAccessFile>
<Async name="Async1">
<AppenderRef ref="Appender1"/>
</Async>
</Appenders>
<Loggers>
<Logger name="examples.test.ABCImpl" level="info" includeLocation="false" additivity="false">
<AppenderRef ref="Appender1"/>
</Logger>
<Root level="info" includeLocation="false">
<AppenderRef ref="Appender1"/>
</Root>
</Loggers>
</Configuration>
The problem is even though the log file gets created, but nothing gets logged in it. The output in std out that I get is :
ABCImpl.initialize
activeHandlerEntries.length=1
***<Provider o/p follows> Before logger re-configuration:
Appenders:[Console]
***<Provider o/p follows> After logger re-configuration:
Appenders:[Async1, Appender1]
Just to make sure that my log4j2.xml and the piece of code is okay without runtime reconfiguration stuff, if I use -Dlog4j.configurationFile=file:SOME_PATH_OUTSIDE_JAR/log4j2.xml log gets populated as expected.
Please help.
I wondered, if deriving the context for initialization by
ctx = (LoggerContext) LogManager.getContext(false);
may be the problem, since you have to access the "current" context with
ctx = (LoggerContext) LogManager.getContext(true);
according to the Log4j2 API. I would really appreciate a clarification, since i'm trying to programmatically configuring Log4J2, too.
Hours of helpless staring at the code and trying my hands here and there, I found that if I get the Logger from newly initialized context (which is obtained from Configurator.initialize) instead of LogManager, log gets populated with data.
Without this trick, not sure if I needed to call any additional API methods (just after Configurator.initialize) to hook the new context into LogManager so that I could have continued traditional approach of getting Logger from LogManager.
...
config = (Configuration) ctx.getConfiguration();
mp = config.getAppenders();
System.out.println("***<Provider o/p follows> After logger re-configuration:");
System.out.println("\tAppenders:" + mp.keySet());
//reconfiguration attempt - ends
//Following line screwed me up for over three weeks
//logger = LogManager.getLogger(this.getClass().getName());
//workaround:
logger = ctx.getLogger(this.getClass().getName());
}
public void myBusinessMethod(){
logger.info("Entry..............");
logger.info("Exit..............");
}
....
}

PersistenceManager issue

I have written a code to save my screen data and retrieve it for second time. Code is:
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
title="HomeView"
add="addHandler(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import spark.managers.PersistenceManager;
protected function saveButton_clickHandler(event:MouseEvent):void
{
var saveManager:PersistenceManager = new PersistenceManager();
saveManager.setProperty("myText", myInput.text);
}
protected function addHandler(event:FlexEvent):void
{
var loadManager:PersistenceManager = new PersistenceManager();
if(loadManager.load())
{
var savedData:Object = loadManager.getProperty("myText");
if(savedData)
myInput.text = savedData.toString();
}
}
protected function clearButton_clickHandler(event:MouseEvent):void
{
var persistenceManager:PersistenceManager = new PersistenceManager();
persistenceManager.clear();
myInput.text = "";
}
]]>
</fx:Script>
<s:TextInput width="100%" id="myInput"/>
<s:Group width="100%">
<s:layout>
<s:HorizontalLayout/>
</s:layout>
</s:Group>
<s:Button id="saveButton" x="-1" y="65" width="100%" label="Save"
click="saveButton_clickHandler(event)"/>
<s:Button id="clearButton" x="0" y="116" width="100%" label="Clear"
click="clearButton_clickHandler(event)"/>
But, when I packaging it for deploying on iPad, it gives me a error like:
Error occurred while packaging the application:
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.
Compilation failed while executing : ADT
I am using Flash builder 4.5 to create iOS application.
Thanx in advance
You need to modify your FlashBuilder.ini file
It's located in your FlashBuilder installation directory.
You need to modify the Xms size - this will allocate more memory while compiling and building project. Remember it should be in strongs of 2.
My file looks like this:
launcher.defaultAction
openFile
-nl
en_US
-vmargs
-Xms256m
-Xmx512m
-XX:MaxPermSize=256m
-XX:PermSize=64m

Resources