Prevent Doctrine from removing a foreign key constraint - doctrine-orm

I manually added a foreign key to a table. How can I prevent SchemaTool from removing it and ideally not even reporting that it exists? I hoped that I could use a listener to prevent it, but there doesn't appear to be a SchemaForeignKeyDefinitionEventArgs event. How can this be accomplished?
class DoctrineSchemaListener implements EventSubscriber
{
public function onSchemaAlterTable(SchemaAlterTableEventArgs $args)
{
if($this->checkIfThisIsRemovingTheFk()) {
$args->preventDefault();
}
}
public function onSchemaAlterTableChangeColumn(SchemaAlterTableChangeColumnEventArgs $args)
{
if($this->checkIfThisIsRemovingTheFk()) {
$args->preventDefault();
}
}
public function onSchemaColumnDefinition(SchemaColumnDefinitionEventArgs $args)
{
if($this->checkIfThisIsRemovingTheFk()) {
$args->preventDefault();
}
}
public function onSchemaIndexDefinition(SchemaIndexDefinitionEventArgs $args)
{
if($this->checkIfThisIsRemovingTheFk()) {
$args->preventDefault();
}
}
}

Related

Resolution status in DryIoc container

Is it possible in DryIoc container to figure out whether some singleton has been instantiated?
For instance
var container = new Container();
container.Register<IApplicationContext, ApplicationContext>( Reuse.Singleton );
// var context = container.Resolve<IApplicationContext>();
if ( container.IsInstantiated<IApplicationContext>() ) // Apparently this does not compile
{
// ...
}
// OR
if ( container.IsInstantiated<ApplicationContext>() )
{
// ...
}
There is no way at the moment and no such feature planned. You may create an issue to request this.
But I am wandering why it is needed. Cause singleton provides a guarantee to be created only once, so you may not worry or check for double creation.
Is it for something else?
Update
OK, in DryIoc you may register a "decorator" to control and provide information about decoratee creation, here is more on decorators:
[TestFixture]
public class SO_IsInstantiatedViaDecorator
{
[Test]
public void Test()
{
var c = new Container();
c.Register<IService, X>(Reuse.Singleton);
c.Register<XProvider>(Reuse.Singleton);
c.Register<IService>(
Made.Of(_ => ServiceInfo.Of<XProvider>(), p => p.Create(Arg.Of<Func<IService>>())),
Reuse.Singleton,
Setup.Decorator);
c.Register<A>();
var x = c.Resolve<XProvider>();
Assert.IsFalse(x.IsCreated);
c.Resolve<A>();
Assert.IsTrue(x.IsCreated);
}
public interface IService { }
public class X : IService { }
public class A
{
public A(IService service) { }
}
public class XProvider
{
public bool IsCreated { get; private set; }
public IService Create(Func<IService> factory)
{
IsCreated = true;
return factory();
}
}
}
This example also illustrates how powerful is composition of DryIoc decorators and factory methods.

Create aggregators dynamically for exceptions

We are using aggregators to keep a count for exceptions during processing
public class BigTableWriter extends DoFn<String, Void> {
private Aggregator<Integer, Integer> errorAggregator;
public BigTableWriter(CloudBigtableOptions options) {
errorAggregator = createAggregator("errors",new Sum.SumIntegerFn());
}
#Override
public void processElement(DoFn<String, Void>.ProcessContext c){
try {
....do work here
}
catch(Exception ex){
errorAggregator.addValue(1);
}
}
}
We'd like to make this more granular rather than keeping a single aggregator to collect the errors. The documentation says that aggregator is typically created in the constructor. Is it possible to create an aggregator for each exception type inside of our catch block? For instance, we want to do something like.
public class BigTableWriter extends DoFn<String, Void> {
private Map<String, Aggregator<Integer, Integer> aggregatorMap;
public BigTableWriter(CloudBigtableOptions options) {
aggregatorMap = new HashMap<>();
}
#Override
public void processElement(DoFn<String, Void>.ProcessContext c){
try {
....do work here
}
catch(Exception ex){
aggregateException(ex.getCause().getMessage());
}
}
public void aggregateException(String exceptionMessage) {
Aggregator<Integer, Integer> aggregator = null;
if(!aggregatorMap.containsKey(exceptionMessage){
aggregator = createAggregator(exceptionMessage,new Sum.SumIntegerFn());
}
else {
aggregator = aggregatorMap.get(exceptionMessage);
}
aggregator.put(exceptionMessage, aggregator);
}
}
Unfortunately, no. The current logic for initializing aggregators requires that they are known at graph construction time (aka. created during the DoFn construction). It's a good feature request though. Created an issue to track it here: https://github.com/GoogleCloudPlatform/DataflowJavaSDK/issues/55

Best practices of implementing unit of work and repository pattern using ServiceStack.ORMLite

Supposing that there are two repository interface :
interface IFooRepository
{
void Delete(int id);
}
interface IBarRepository
{
void Delete(int id);
}
And an IUnitOfWork interface like :
interface IUnitOfWork : IDisposable
{
void Commit();
void Rollback();
}
what is the best practices of implementing those interface using ServiceStack.ORMLite so that user can use them like
MyFooRepository.Delete(4);
// if an Exception throws here, Bar won't be deleted
MyBarRepository.Delete(7);
Or
using (var uow = CreateUnitOfWork())
{
MyFooRepository.Delete(4);
MyBarRepository.Delete(7);
uow.Commit(); //now they are in an transaction
}
Not sure of your need for Repository + UnitOfWork patterns but I think there are some alternative solutions in ServiceStack + OrmLite that keep your code 'DRY' before you need to introduce any patterns (especially if you're mainly seeking Transaction/Rollback support). Something like below is where I would start.
public class Foo //POCO for data access
{
//Add Attributes for Ormlite
public int Id { get; set; }
}
public class Bar //POCO for data access
{
//Add Attributes for Ormlite
public int Id { get; set; }
}
//your request class which is passed to your service
public class DeleteById
{
public int Id { get; set; }
}
public class FooBarService : MyServiceBase //MyServiceBase has resusable method for handling transactions.
{
public object Post(DeleteById request)
{
DbExec(dbConn =>
{
dbConn.DeleteById<Foo>(request.Id);
dbConn.DeleteById<Bar>(request.Id);
});
return null;
}
}
public class MyServiceBase : Service
{
public IDbConnectionFactory DbFactory { get; set; }
protected void DbExec(Action<IDbConnection> actions)
{
using (var dbConn = DbFactory.OpenDbConnection())
{
using (var trans = dbConn.OpenTransaction())
{
try
{
actions(dbConn);
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
throw ex;
}
}
}
}
}
Some references...
https://github.com/ServiceStack/ServiceStack.RedisWebServices - The above code is modified from this example
https://groups.google.com/forum/#!msg/servicestack/1pA41E33QII/R-trWwzYgjEJ - discussion about layers in ServiceStack
http://ayende.com/blog/3955/repository-is-the-new-singleton - Ayende Rahien (NHibernate core contributor) on Repository pattern

how to create a mock in a model test case

Maybe I am doing this wrong.
I'd like to test the beforeSave method of a model (Antibody). A part of this method calls a method on an associated model (Species). I'd like to mock the Species model but don't find how.
Is it possible or am I doing something that goes against the MVC pattern and thus trying to do something that I shouldn't?
class Antibody extends AppModel {
public function beforeSave() {
// some processing ...
// retreive species_id based on the input
$this->data['Antibody']['species_id']
= isset($this->data['Species']['name'])
? $this->Species->getIdByName($this->data['Species']['name'])
: null;
return true;
}
}
Assuming your Species model in created by cake due to relations, you can simply do something like this:
public function setUp()
{
parent::setUp();
$this->Antibody = ClassRegistry::init('Antibody');
$this->Antibody->Species = $this->getMock('Species');
// now you can set your expectations here
$this->Antibody->Species->expects($this->any())
->method('getIdByName')
->will($this->returnValue(/*your value here*/));
}
public function testBeforeFilter()
{
// or here
$this->Antibody->Species->expects($this->once())
->method('getIdByName')
->will($this->returnValue(/*your value here*/));
}
Well, it depends on the way your 'Species' object is injected.
Is it injected via the constructor ? Via a setter ? Is it inherited ?
Here is an example with a constructor injected object :
class Foo
{
/** #var Bar */
protected $bar;
public function __construct($bar)
{
$this->bar = $bar;
}
public function foo() {
if ($this->bar->isOk()) {
return true;
} else {
return false;
}
}
}
Then your test would be something like this:
public function test_foo()
{
$barStub = $this->getMock('Overblog\CommonBundle\TestUtils\Bar');
$barStub->expects($this->once())
->method('isOk')
->will($this->returnValue(false));
$foo = new Foo($barStub);
$this->assertFalse($foo->foo());
}
The process is quite the same with setter injected objects :
public function test_foo()
{
$barStub = $this->getMock('Overblog\CommonBundle\TestUtils\Bar');
$barStub->expects($this->once())
->method('isOk')
->will($this->returnValue(false));
$foo = new Foo();
$foo->setBar($barStub);
$this->assertFalse($foo->foo());
}

NUnit Conditional Teardown?

Is there a way to do a conditional TearDown in NUnit?
I have a TestFixture which has a need to run cleanup code for just a few tests, and I don't really want to:
Run the TearDown method on every test
Create a private helper method and call it from the tests requiring cleanup if I can avoid it
There isn't unfortunately.
Can you not do the cleanup in the [TestFixtureTearDown] instead, so once all the tests have finished? I guess that depends on whether the cleanup has to be done before the next test runs.
Alternatively, put those tests that require a cleanup in another class/TextFixture together, away from the other tests. Then you can use a TearDown in there which doesn't need to be conditional.
Edit:
One thing I've just thought of, which could be done to achieve the aim though probably isn't actually worth it for this particular need, is that you can extend NUnit - create your own custom attributes which you could handle however you wanted. This is mentioned here. Like I say, I don't think really you should go down that route for this, but is useful to know none-the-less
You can have the main TearDown in a base class:
[TearDown]
public virtual void TearDown()
{
// Tear down things here
}
and then override it in the class where you have the tests that should not run the tear down code:
[TearDown]
public override void TearDown()
{
// By not calling base.TearDown() here you avoid tearing down
}
Extend all you classes with test from BaseTest
public class BaseTest
{
[SetUp]
public void BeforeTest()
{
GetService<NUnitHooksController>().ExecuteBeforeTestHooks(this);
}
[TearDown]
public void AfterTest()
{
GetService<NUnitHooksController>().ExecuteAfterTestHooks(this);
}
}
Use AfterTest and BeforeTest hooks. Works both with and without category.
public class ExampleTest : BaseTest
{
[Test, Category("asdasd")]
public void Test01()
{
...
}
[AfterTest("asdasd")]
public void ExampleHook()
{
...
}
}
public class NUnitHooksController
{
private readonly ILogger _log;
public NUnitHooksController(ILogger log)
{
_log = log;
}
public void ExecuteBeforeTestHooks(object testClass)
{
ExecuteHooks(testClass, typeof(BeforeTestAttribute));
}
public void ExecuteAfterTestHooks(object testClass)
{
ExecuteHooks(testClass, typeof(AfterTestAttribute));
}
private MethodInfo[] GetHookMethods(object currentTestClass, Type attributeType)
{
return currentTestClass
.GetType()
.GetMethods()
.Where(m => m.GetCustomAttributes(attributeType, false).Length > 0)
.ToArray();
}
private void ExecuteHooks(object testClass, Type requiredAttributeType)
{
var hooks = GetHookMethods(testClass, requiredAttributeType);
var testCategories = GetTestCategories();
foreach (var hook in hooks)
{
var allAttributes = hook.GetCustomAttributes(requiredAttributeType, true);
foreach (var attribute in allAttributes)
{
if (!attribute.GetType().IsEquivalentTo(requiredAttributeType))
{
continue;
}
var hookCategories = GetCategoriesFromAttribute(attribute);
// if we do not have specific category on hook
// or we have at least one same category on hook and test
if (!hookCategories.Any() || hookCategories.Intersect(testCategories).Any())
{
ExecuteHookMethod(testClass, hook);
}
}
}
}
private object[] GetTestCategories()
{
return TestContext.CurrentContext.Test.Properties["Category"].ToArray();
}
private void ExecuteHookMethod(object testClass, MethodInfo method)
{
var hookName = method.Name;
_log.Information($"Executing - '{hookName}' hook");
try
{
method.Invoke(testClass, Array.Empty<object>());
}
catch (Exception e)
{
_log.Error($"Executing of - '{hookName}' hook failed - {e}");
}
}
private string[] GetCategoriesFromAttribute(object attribute)
{
if (attribute is BeforeTestAttribute beforeTestAttribute)
{
return beforeTestAttribute.Categories;
}
if (attribute is AfterTestAttribute afterTestAttribute)
{
return afterTestAttribute.Categories;
}
throw new ArgumentException($"{attribute.GetType().FullName} - does not have categories");
}
}
I have solved this using the name of the test:
namespace TestProject
{
public class TestClass
{
// Test without TearDown
[Test]
public void Test1()
{
Assert.Pass("Test1 passed");
}
// Test with TearDown
[Test]
public void Test2()
{
Assert.Pass("Test2 passed");
}
[TearDown]
public void TearDown()
{
// Execute only after Test2
if (TestContext.CurrentContext.Test.Name.Equals(nameof(this.Test2)))
{
// Execute Test2 TearDown...
}
}
}
}
Or if you want to use the full name of Test2 (TestProject.TestClass.Test2) you can replace the line
if (TestContext.CurrentContext.Test.Name.Equals(nameof(this.Test2)))
by
if (TestContext.CurrentContext.Test.FullName.Equals(typeof(TestClass).FullName + "." nameof(this.Test2)))