factory girl - how can we access overrides passed to a method? - factory-bot

This question is related to when/how overrides work in FactoryGirl
For my specific problem, I have a organization with 'limits' attribute. The after(:create) section sets some other values and finally does a save. The save resets the 'limits' based on logic in organization.after_save method. So I had to do update_attributes so 'limits' is set to whatever is defined in the factory girl.
This all works OK except for cases when limits is overridden by a spec.
Here is the code:
factory :organization do
sequence(:name) {|n| "org#{n + $offset}" }
.....
limits_attributes :projectsLimit => 1, :svnEnabled => true, :deployEnabled => true
...
after(:create) do | org |
sub = FactoryGirl.create(:subscription, :organization => org)
sp = FactoryGirl.create(:subscription_plan, :subscription => sub)
sub.subscription_plans << sp
org.subscription = sub
org.status = :active
org.save
# Since entitlements are messed up after setting sub-plan set them here.
org.limits.update_attributes(:projectsLimit => 1, :svnEnabled => true, :deployEnabled => true)
end
end
This fails when 'limits' is overridden, clearly because I am not getting the overridden attributes:
FactoryGirl.create(:organization, :limits_attributes => {:gitEnabled => true, :projectsLimit => 3})
I tried getting attributes using attributes_for, I misinterpreted attributes_for to get the values passed to 'create the organization'
org_attrs = FactoryGirl.attributes_for(:organization)
puts "atts #{org_attrs}"
org.save
# Since entitlements are messed up after setting sub-plan set them here.
org.limits.update_attributes(org_attrs[:limits_attributes])
Given that I cannot change the logic in Organization's after_save, how can I update limits if user overrides them? Where in the flow of things are overrides applied to the models defined in FactoryGirl.
I think there might be a flaw in how I interpret what the code is doing OR the scenario I m looking to solve does not fit how FG is used.
Thanks.

I was incorrect about the overridden values. org has the values set before the save (overriden or default, whatever the case). So just saving a copy before and reusing it did it. Not sure if this is a good solution though
org_limits = org.limits.dup
org.save
# Since entitlements are messed up after setting sub-plan set them here.
org.limits.update_attributes(org_limits.attributes)

Related

NullReferenceException using Where() in AutoMapper.MapFrom

I'm modelling a 3rd party database using Automapper 8 and EF 6.
One of my DTO classes needs to use a Where clause on an association to locate the correct record.
// Community table is mapped and working.
// Mapping breaks when mapping dest.Subjects
cfg.CreateMap<Person, PersonDto>()
// snip many mappings
.ForMember(dest => dest.Id, act => act.MapFrom(src => src.ID))
.ForMember(dest => dest.UserName, act => act.MapFrom(src => src.Community.NetworkLogin))
.ForMember(
dest => dest.Subjects,
act => act.MapFrom(
src => src.Community.StudentClasses.Where(
subject => subject.Year == CurrentSemester.Year && subject.Semester == CurrentSemester.Semester)))
.ForMember(
dest => dest.Contacts,
act => act.MapFrom(
src => src.Community.Contacts.Where(
contact => Contact.UseThis).Select(contact => contact.ContactDetails)));
This code works in production, but I'd really like to Unit Test this model. Running a simple test (get all records in the Mock) I'm hit with a NullReferenceException when it tries to access the Community.StudentClasses object.
I found this answer relating to NullReferenceExceptionexceptions and AutoMapper, which helped me fix the rest of the references in this config, but I'm still having issues with this one. The test works when I remove the Community.StudentClasses mapping.
I'm mocking objects using code similar to:
public static Person Person19788 =>
new SchoolContact
{
ID = 19788,
NetworkLogin = "username",
// Tried various creation methods
// StudentClasses = new List<StudentClass> {new StudentClass()},
// StudentClasses = new List<StudentClass> {new StudentClass {Year = 0, Semester = 0}},
StudentClasses = null,
StudentContacts = null,
Address = Address19788
};
CurrentSemester has been checked, and returns valid non-zero values for Year and Semester.
The strange thing is that the Contacts mapping works fine, even with null values. So I assume that I've broken my Subjects mapping somewhere along the line, but I'm unsure where else to look.
It turns out that the problem was with my Subjects mapping after all.
The top-level associations were mapped correctly, however the lower-level associations were not. (I didn't include these mappings because a) I didn't think about them, and b) there's only so much code that anyone would be willing to wade through).
After fixing up the w > x > y > z mappings everything is working as expected. I thought I'd exhausted all options before posting this question. Lesson learned: don't post to SO until you've slept on it and taken a fresh look at the code the next day.

How to add an attribute to an object using the meta-object protocol?

I was trying to answer this question, and thought I could use the meta-object protocol to add attributes to a class. Here is a minimal example where I try to add an attribute test to the class Configuration after construction:
use v6;
class Configuration {
}
my $config = Configuration.new;
my $attr = Attribute.new(
:name('$.test'), # Trying to add a "test" attribute
:type(Str),
:has_accessor(1),
:package(Configuration)
);
$config.^add_attribute( $attr );
$config.^compose();
say "Current attributes: ", join ', ', $config.^attributes();
$attr.set_value( $config, "Hello" ); # <-- This fails with no such attribute '$.test'
say $config.test;
When I run this, I get:
Current attributes: $.test
P6opaque: no such attribute '$.test' on type Configuration in a Configuration when trying to bind a value
in block <unit> at ./p.p6 line 16
Attributes cannot be added after class composition time, which occurs at compile time when the closing } is reached when compiling the program. (This is the case for the P6opaque representation. It's not impossible that a representation could exist that allows this, but there's none specified at this time.)
Further to that, .^add_attribute is called on the meta-object, and for a class the attributes are per type, not per object; the code structure suggests that perhaps the expectation was per object. There's nothing that makes it impossible to have prototype object orientation (actually the MOP is designed so somebody could implement such an object system in Perl 6), but again there's nothing specified in Perl 6 itself that provides this.
Thus with the provided object system, such manipulation needs to be done at compile time, and before the closing }. That can be achieved as follows:
class Configuration {
BEGIN {
my $attr = Attribute.new(
:name('$!test'), # Trying to add a "test" attribute
:type(Str),
:has_accessor(1),
:package(Configuration)
);
Configuration.^add_attribute( $attr );
}
}
my $config = Configuration.new;
say "Current attributes: ", join ', ', $config.^attributes();
$config.^attributes[0].set_value( $config, "Hello" );
say $config.test;
This is one of the many places where Perl 6 is dynamic primarily by inviting the programmer to participate in compile time, rather than by making all things possible at runtime.
Finally, I'll note that there is a means to add attributes to an existing object, and on a per-object basis: by using does to mix a role in to it. That works by changing the type of the object along the way. There's some documentation on does here.

FluentAssertions graph comparison, ExcludingNestedObjects ignored?

I've got a unit/integration test as follows.
using (var repository = _factory.Get())
{
applicationBefore = repository.Applications
.Include(a => a.AcceptedAgreements)
.Single(a => a.AggregateId == applicationId);
}
// Perform an operation that deletes an Application and all
// related data and then rebuilds it from the event store.
Repo.Application applicationAfter = null;
using (var repository = _factory.Get())
{
applicationAfter = repository.Applications
.Include(a => a.AcceptedAgreements)
.Single(a => a.AggregateId == applicationId);
}
applicationAfter.AcceptedAgreements.ShouldAllBeEquivalentTo(applicationBefore.AcceptedAgreements, options => options
.ExcludingNestedObjects());
The repository reference is a DbContext and AcceptedAgreements is a navigation property.
This test fails with the following message.
Result Message:
FluentAssertions.Execution.AssertionFailedException :
Expected item[0].Application.Id to be 1, but found 2.
<more failures where stuff inside Application is different>
With configuration:
- Use declared types and members
- Compare enums by value
- Include all non-private properties
- Include all non-private fields
- Match member by name (or throw)
- Be strict about the order of items in byte arrays
- FluentAssertions.Equivalency.ShouldAllBeEquivalentToHelper+CollectionMemberOrderingRuleDecorator
If I modify the assertion as follows:
applicationAfter.AcceptedAgreements.ShouldAllBeEquivalentTo(applicationBefore.AcceptedAgreements, options => options
.Excluding(o => o.Application));
Now the test passes.
Please help me understand why ExcludingNestedObjects() doesn't exclude the Application property, which is in fact a nested object, and I have to resort to excluding each navigation property individually. The above code is slightly simplified as I actually have multiple navigation properties and have to exclude each of them individually.

Moops lexical_has and default values

I am trying to understand how lexical_has attributes work in Moops. This feature comes from Lexical::Accessor and, as I understand it, the lexical_has function is able to generate a CODE reference to any attribute a class might "lexically have" by using a scalar reference (which is kept in accessor =>). The CODE reference can then be used to access the class attribute in a way that "enforces" scope (because they are "inside out"??). But this is just my surmise and wild guesses so I would appreciate a better explanation. I also want to know why this approach doesn't seem to work in the following example:
Working from the example that is part of the Moops introduction I'm creating a class Car:
use Moops;
class Car {
lexical_has max_speed => (
is => 'rw',
isa => Int,
default => 90,
accessor => \(my $max_speed),
lazy => 1,
);
has fuel => (
is => 'rw',
isa => Int,
);
has speed => (
is => 'rw',
isa => Int,
trigger => method ($new, $old?) {
confess "Cannot travel at a speed of $new; too fast"
if $new > $self->$max_speed;
},
);
method get_top_speed() {
return $self->$max_speed;
}
}
Then I instantiate the object and try to use its methods to access its attributes:
my $solarcharged = Car->new ;
# This correctly won't compile due to $max_speed scoping:
# say $solarcharged->$max_speed;
# This shows expected error "too fast"
$solarcharged->speed(140);
# This prints nothing - wrong behavior?
say $solarcharged->get_top_speed();
The last line which uses the custom accessor baffles me: nothing happens. Am I missing an attribute or setting for the class (marking it eager or lazy => 0 doesn't work)? Do I need a BUILD function? Is there an initialization step I'm missing?
N.B. If I add a setter method to the class that looks like this:
method set_top_speed (Int $num) {
$self->$max_speed($num);
}
and then call it in my final series of statements:
# shows expected error "too fast"
$solarcharged->speed(140);
$solarcharged->set_top_speed(100);
# prints 100
say $solarcharged->get_top_speed();
the get_top_speed() method starts to return properly. Is this expected? If so, how does the default from the class settings work?
I've reported this as a bug here: https://rt.cpan.org/Public/Bug/Display.html?id=101024.
Since One can easily work around this by using "perl convention" (i.e. not using lexical_has and prefixing private attributes with "_") and this question arose from a bug, I don't expect a fix or a patch as an answer. For the bounty - I would appreciate an explanation of how Lexical::Accessor is supposed to work; how it "enforces" private internal scope on accessors; and maybe some CS theory on why that is a good thing.
According to the ticket filed by the OP, this bug was fixed in Lexical-Accessor 0.009.

What is the most efficient way to override an attribute in lots of my Moose based sub classes?

I am using HTML::FormHandler. To use it one is supposed to subclass from it and then you can override some attributes such as field_name_space or attribute_name_space.
However, I now have lots of forms all extending HTML::FormHandler or its DBIC based variant HTML::FormHandler::Model::DBIC and therefore have these overidden attributes repeated many times.
I tried to put them in a role but get an error that +attr notation is not supported in Roles. Fair enough.
What is the best way of eliminating this repetition? I thought perhaps subclassing but then I would have to do it twice for HTML::FormHandler and HTML::FormHandler::Model::DBIC, plus I believe general thought was that subclassing is generally better achieved with Roles instead.
Update: I thought it would be a good idea to give an example. This is what I am currently doing - and it involves code repetition. As you can see one form uses a different parent class so I cannot create one parent class to put the attribute overrides in. I would have to create two - and that also adds redundancy.
package MyApp::Form::Foo;
# this form does not interface with DBIC
extends 'HTML::Formhandler';
has '+html_prefix' => (default => 1);
has '+field_traits' => (default => sub { ['MyApp::Form::Trait::Field'] });
has '+field_name_space' => (default => 'MyApp::Form::Field');
has '+widget_name_space' => (default => sub { ['MyApp::Form::Widget'] });
has '+widget_wrapper' => (default => 'None');
...
package MyApp::Form::Bar;
# this form uses a DBIC object
extends 'HTML::Formhandler::Model::DBIC';
has '+html_prefix' => (default => 1);
has '+field_traits' => (default => sub { ['MyApp::Form::Trait::Field'] });
has '+field_name_space' => (default => 'MyApp::Form::Field');
has '+widget_name_space' => (default => sub { ['MyApp::Form::Widget'] });
has '+widget_wrapper' => (default => 'None');
...
package MyApp::Form::Baz;
# this form also uses a DBIC object
extends 'HTML::Formhandler::Model::DBIC';
has '+html_prefix' => (default => 1);
has '+field_traits' => (default => sub { ['MyApp::Form::Trait::Field'] });
has '+field_name_space' => (default => 'MyApp::Form::Field');
has '+widget_name_space' => (default => sub { ['MyApp::Form::Widget'] });
has '+widget_wrapper' => (default => 'None');
...
First of all, roles are composed into a class, they have nothing to do with subclassing. A subclass is a full class that extends a parent (or more than one, but in my experience multiple inheritance should be avoided if it can be). A role is a piece of behaviour, or a parial interface that can be applied to a class. The role then directly modifies the class. There's no new class created in general.
So inheritance and role composition are really two different things and two different kinds of design. Thus you can't simply exchange one for the other. Both have different design-implications.
My strategy with HTML::FormHandler has been to make a real subclass for each form that I require, and put the different behaviours of the form that I wanted to re-use into roles.
I'd think this question (how to implement the extensions you need in a clean and sane way) can't really be answered without knowing the actual design you're aiming for.
Update: I see what you mean and that's a tricky case. HTML::FormHandler is primarily targetted at extension by inheritance. So I think the best strategy would indeed be to have two subclasses, one for HTML::FormHandler and one for HTML::FormHandler::Model::DBIC. It seems teadious at first, but you might want to have different settings for them in the long run anyway. To avoid repeating the actual configuration (the default values) I'd try the following (this example is plain HFH, without DBIC):
package MyApp::Form;
use Moose;
use namespace::autoclean;
extends 'HTML::FormHandler';
with 'MyApp::Form::DefaultSettings';
# only using two fields as example
for my $field (qw( html_prefix field_traits )) {
has "+$field", default => sub {
my $self = shift;
my $init = "_get_default_$field";
my $method = $self->can($init)
or die sprintf q{Class %s does not implement %s method}, ref($self), $init;
return $self->$method;
};
}
1;
Note that you'd need to make an attribute lazy if it requires the values of another attribute for its computation. The above base class would look for hooks to find the initialized values. You'd have to do this in both classes, but you could put the default subroutine generation into a function you import from a library. Since the above doesn't require direct manipulation of the attribute anymore to change the default values, you can put that stuff in a role I called MyApp::Form::DefaultSettings above:
package MyApp::Form::DefaultSettings;
use Moose::Role;
use namespace::autoclean;
sub _build_html_prefix { 1 }
sub _build_field_traits { ['MyApp::Form::Trait::Field'] }
1;
This method will allow your roles to influence the default value construction. For example, you could have a role based on the one above that modifies the value with around.
There is also a very simple, but in my opinion kind-of ugly way: You could have a role provide a BUILD method that changes the values. This seems pretty straight-forward and easy at first, but it's trading extendability/flexibility with simplicity. It works simple, but also only works for very simple cases. Since the amount of forms in web applications is usually rather high, and the needs can be quite diverse, I'd recommend going with the more flexible solution.
The code for HTML::FormHandler::Model::DBIC is actually in a Moose trait in order to help with this situation. You can inherit from your base class, and in your forms that use the DBIC model, you can do
with 'HTML::FormHandler::TraitFor::Model::DBIC';
Would this method, using multiple inheritance (I know I know, ugh), where you put your common default overrides in one class, and then your customized code in others?
package MyApp::Form;
use Moose;
extends 'HTML::Formhandler';
has '+html_prefix' => (default => 1);
has '+field_traits' => (default => sub { ['MyApp::Form::Trait::Field'] });
has '+field_name_space' => (default => 'MyApp::Form::Field');
has '+widget_name_space' => (default => sub { ['MyApp::Form::Widget'] });
has '+widget_wrapper' => (default => 'None');
package MyApp::Form::Model::DBIC;
use Moose;
extends 'MyApp::Form', 'HTML::Formhandler::Model::DBIC';
# ... your DBIC-specific code
Now you can descend from MyApp::Form or MyApp::Form::Model::DBIC as needed.