Doctrine2: testing repository classes with YAML config - testing

I have YAML config for my symfony2 project using Doctrine2. I'm not understanding how exactly to adapt the cookbook entry to a YAML setup.
My doctrine mapping is at /path/to/my/bundle/Resources/config/doctrine/IpRange.orm.yml
When running PHPUnit, I get the error:
Doctrine\ORM\Mapping\MappingException: No mapping file found named 'Yitznewton.FreermsBundle.Entity.IpRange.orm.yml' for class 'Yitznewton\FreermsBundle\Entity\IpRange'.
Sounds like I need to configure the test rig to use the symfony file naming conventions, but I don't know how to do that.
Using symfony-standard.git checked out to v2.0.7
Here's my test:
<?php
namespace Yitznewton\FreermsBundle\Tests\Utility;
use Doctrine\Tests\OrmTestCase;
use Doctrine\ORM\Mapping\Driver\DriverChain;
use Doctrine\ORM\Mapping\Driver\YamlDriver;
use Yitznewton\FreermsBundle\Entity\IpRange;
use Yitznewton\FreermsBundle\Entity\IpRangeRepository;
class IpRangeRepositoryTest extends OrmTestCase
{
private $_em;
protected function setup()
{
// FIXME: make this path relative
$metadataDriver = new YamlDriver('/var/www/symfony_2/src/Yitznewton/FreermsBundle/Resources/config/doctrine');
$metadataDriver->setFileExtension('.orm.yml');
$this->_em = $this->_getTestEntityManager();
$this->_em->getConfiguration()
->setMetadataDriverImpl($metadataDriver);
$this->_em->getConfiguration()->setEntityNamespaces(array(
'FreermsBundle' => 'Yitznewton\\FreermsBundle\\Entity'));
}
protected function getRepository()
{
return $this->_em->getRepository('FreermsBundle:IpRange');
}
public function testFindIntersecting_RangeWithin_ReturnsIpRange()
{
$ipRange = new IpRange();
$ipRange->setStartIp('192.150.1.1');
$ipRange->setEndIp('192.160.1.1');
$this->assertEquals(1, count($this->getRepository()
->findIntersecting($ipRange)),
'some message');
}

Looking again at the symfony docs, it seems that integration testing with a live test database is preferred to unit testing for repository classes. That is, there is no support for stubbing EntityManagers.

Related

How to restart the Quarkus Lambda between integration test?

I have a project with Quarkus and Lambda extension. I have multiple integration test and I need to restart the lambda between each test.
Apparently the lambda is created by MockEventServer but I didn't succeed to access to the object created.
By analyzing the code I find that you can inject a MockEventServer to the following method:
DevServicesLambdaProcessor.startEventServer(LaunchModeBuildItem launchMode,
LambdaConfig config,
Optional<EventServerOverrideBuildItem> override,
BuildProducer<DevServicesResultBuildItem> devServicePropertiesProducer,
BuildProducer<RuntimeApplicationShutdownBuildItem> runtimeApplicationShutdownBuildItemBuildProducer)
So I try to create a build step:
public class AwsMockServ {
public static MockEventServer mockEventServer = new MockEventServer();
#BuildStep
public EventServerOverrideBuildItem overrideEventServer() {
return new EventServerOverrideBuildItem(
() -> mockEventServer);
}
}
But the buildStep is ignored...
Someone succeed to restart the mockEventServer between integration test ?
Thanks for your help.

How can I use environment specific variables in micronaut?

I'm new to micronaut and server side programming in general. The micronaut documentation, unfortunately, does not make a lot of sense to me, as I do not have a Java background. A lot of the terms like "ApplicationContext" make sense in english, but I have no idea how to use them in practice.
Trying to start with a very basic app that prints different configurations ("localhost", "dev", "prod") depending on the environment it is in.
Here's my controller
#Controller("/")
class EnvironmentController {
// this should return "localhost", "DEV", "PROD" depending on the environment
#Get("/env")
#Produces(MediaType.TEXT_PLAIN)
fun env() = "???" // what should I put here ?
// this should return the correct mongodb connection string for the environment
#Get("/mongo")
#Produces(MediaType.TEXT_PLAIN)
fun mongo() = "???" // what should I put here ?
}
Here's the application.yml. Ideally I'd have 1 yml file for each environment
micronaut:
application:
name: myApp
server:
port: 8090
environment: localhost
mongodb:
uri: 'mongodb://localhost:27017'
Application.kt is untouched with the rest of the files generated by the mn cli tool. How can I set per environment parameters, or pass the yml file as a parameter when starting micronaut?
Are there any conventions around this?
You can specify an environment with -Dmicronaut.environments, or by specifying them in the context builder Micronaut.run in your Application class.
https://docs.micronaut.io/latest/guide/index.html#environments
Then for example application-env.yml will be loaded.
https://docs.micronaut.io/latest/guide/index.html#propertySource
The docs are pretty clear on this
By default Micronaut only looks for application.yml. Then, for tests,dev and prod, it loads application.yml and overrides any values there with the ones defined in application-test.yml, application-dev.yml and application-prod.yml
If you want to enable any other environment, you need to do it manually
public static void main(String[] args) {
Micronaut.build(args)
.mainClass(Application.class)
.defaultEnvironments("dev")
.start();
}
https://docs.micronaut.io/latest/guide/index.html#_default_environment

Swagger api listing is empty

Recently I have configure swagger with one of my project. Its using jersey2 and JAX-WS on tomcat for restful API. I have used following manual to configure
https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-2.X-Project-Setup-1.5
${basepath}/swagger.json response with following
{"swagger":"2.0","info":{"version":"1.0.0","title":""},"host":"localhost:8080","basePath":"/myapi","schemes":["http"]}
Unfortounately it does not contain any api which is under my resource package.
I have tried with the answer of following question
swagger - empty listing with no API
But it didn't help either.
The above answer using com.wordnik.swagger.* package(s)
But with the manual I got io.swagger.* package(s), which doesn't have
JaxrsApiReader class
My assumption is swagger couldn't scan my api list from Resource package.
But could not figure out which configuration or which code snippet I have missed.
Any help?....
It looks like you forgot to mark the rest endpoints with #Api
I had the same issue, I used a different approach that worked for me, by adding information only in my Application class. In case you have one, that might help you:
public class MyApi extends Application {
public MyApi() {
super();
BeanConfig beanConfig = new BeanConfig();
beanConfig.setTitle("MyApi");
beanConfig.setVersion("0.0.1");
beanConfig.setSchemes(new String[]{"http", "https"});
beanConfig.setHost("localhost:8080");
beanConfig.setBasePath("/mypath");
//putting only the path to my api unblocked me, I removed "io.swagger.resources"
beanConfig.setResourcePackage("system.organization.api");
beanConfig.setScan(true);
beanConfig.setPrettyPrint(true);
}
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> s = new HashSet<>();
s.add(MyApis);
//for swagger
s.add(ApiListingResource.class);
s.add(SwaggerSerializers.class);
return s;
}
}
Then, the links of classes with #API annotation appeared in swagger.json
Mostly done with the same manual you used: https://github.com/swagger-api/swagger-core/wiki/Swagger-Core-Jersey-1.X-Project-Setup-1.5

How do I specify my resourcesXml for Glassfish as a resource itself, and not a local file?

I want to put all my configuration files (arquillian.xml, glassfish-resources.xml,test-persistence.xml) in a library and just reference that when i want to run a test in a project. But it seems the resourceXml only allows for a file-path and not a classpath: variable.
Is there a way to do that?
My configuration is currently based upon the arquillian-persistence-tutorial example project. I actually have no special configuration which is need. Just a in-memory db etc. etc.
I fixed it by extending the Arquillian class, and writing the resource to a local file (in the target folder) before any test.
Now in a domain project i only need to do this in a unit test:
public class MyEntityRepositoryImplTest extends BaseArquillianTest {
#Deployment
public static Archive<?> createDeployment() {
return create().//
addClass(MyEntityRepositoryImpl.class).//
addClass(MyEntityDaoImpl.class).//
addClass(MockSomeRepositoryImpl.class).//
addClass(MyEntityJpa.class);
}
#EJB
private MyEntityRepository myEntityRepository;
#Test
public void mMytest () {
}

Testing Castle windsor Component with PerWebRequest lifestyle

I'm trying to do some testing with castle windsor involved, in one of my tests I want to check the windsor installers, so I check that the container can resolve my components given its interface.
So far, so good, the problem starts when the component has PerWebRequest lifestyle in its installer, at first it complained about HttpContext.Current is null, having that one solved creating a fake Context in test setup I'm now having this exception in nunit test
System.Exception : Looks like you forgot to register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule
Add '' to the section on your web.config. If you're running IIS7 in Integrated Mode you will need to add it to section under
As I'm running this from NUnit, how I can register the module or class in windsor so it works, or how can be mocked, as in this test is not really a web request, just checking that the container resolve the type.
And also this same thing will happen if I make any integration tests with this component outside a real webrequest, is there any way to make this work or really mock a web request so this tests can be run?
Tranks in advance
Fer
In your test you could subscribe to the ComponentModelCreated event and change the lifestyle of your per-web-request components to something else. (example).
If you're writing an integration test with the scope of a single request, singleton should do.
If you're writing an integration test that spans multiple requests, you could use a contextual lifestyle to simulate the scope of requests.
Edit: including code from example (which is no longer available):
container.Kernel.ComponentModelCreated += Kernel_ComponentModelCreated;
…
void Kernel_ComponentModelCreated(Castle.Core.ComponentModel model)
{
if (model.LifestyleType == LifestyleType.Undefined)
model.LifestyleType = LifestyleType.Transient;
}
From version 5 of Windsor the accepted answer doesn't work if you are using Castle.Facilities.AspNet.SystemWeb.WebRequestScopeAccessor because the PerWebRequest lifestyle is already a scoped lifestyle.
I got it to work by changing the the ComponentModelCreated delegate to the following:
void Kernel_ComponentModelCreated(Castle.Core.ComponentModel model)
{
const string CastleScopeAccessorType = "castle.scope-accessor-type";
if (model.ExtendedProperties.Contains(CastleScopeAccessorType))
{
model.ExtendedProperties.Remove(CastleScopeAccessorType);
}
}
I ended up implementing this extension. ATTN: Must call before loading components with the PerWebRequest lifestyle:
public static class WindsorContainerExtensions
{
public static IWindsorContainer OverridePerWebRequestLifestyle(this IWindsorContainer container)
{
container.Kernel.ComponentModelCreated += model =>
{
if (model.IsPerWebRequestLifestyle())
{
model.LifestyleType = LifestyleType.Transient;
}
};
return container;
}
private static bool IsPerWebRequestLifestyle(this ComponentModel model)
{
return model.LifestyleType == LifestyleType.Scoped
&& model.HasAccessorType(typeof(WebRequestScopeAccessor));
}
private static bool HasAccessorType(this ComponentModel model, Type type)
=> model.HasExtendedProperty("castle.scope-accessor-type", type);
private static bool HasExtendedProperty<T>(this ComponentModel model, object key, T expected)
{
return model.ExtendedProperties[key] is T actual
&& EqualityComparer<T>.Default.Equals(actual, expected);
}
}
Requires these imports:
using System;
using System.Collections.Generic;
using Castle.Core;
using Castle.Facilities.AspNet.SystemWeb;
using Castle.Windsor;
If you also want to check if the type of scope is per web request you could also do this
var isPerWebRequestScope = JsonConvert.SerializeObject(model.ExtendedProperties).Contains("Castle.Facilities.AspNet.SystemWeb.WebRequestScopeAccessor")