Can you use ObjectHydrator to generate an object with constraints on the properties? - unit-testing

I'm currently writing tests for a .net6 project. I'm using AutoFixture with ObjectHydrator to generate objects with real-world looking data. Sometimes the objects are generated with data that violates their respective database table's column's constraints (i.e., a string that is too long). I'd like to setup ObjectHydrator to generate these objects with data that does not violate these constraints.
I've tried using data annotations on the object class properties (i.e., StringLength(n)) thinking that this would force the ObjectHydrator code to generate objects where the property values would equal a value that does not violate the defined constraint. This didn't work and the ObjectHydrator generated objects using default behavior. My attempts to find a solution have yielded results that are about ObjectHydrator that aren't relevant, model validation, or data annotations for EF.

Related

Ensuring that all fields of a class are serialized

I am writing serialize / de-serialize methods on an existing C++ class that contains several fields where most of these fields are complex, nested data structures themselves. What are some techniques I could use to ensure that I had serialized all the fields? I am using the Boost serialization library for this project.
One method I can think of is to write an 'equal' function for all the data types and write unit-tests that would assert that the original object was equal to the de-serialized object. However, this method seems error prone since amongst other things, the equals function would require an update whenever a field was added to the data type.

Programmatically specify implementation of derived attributes

I want to use derived attributes and references in an ecore model, but so far I have not found any documentation on how to set the code for the methods which compute the values of derived attributes/references.
As far as I understand it, the basic workflow is to mark an attribute/reference as derived, generate model code, and then manually add the implementation. However, I work with models dynamically generated through the Ecore API. Is there a way to take a String and specify this String as the implementation for the computation of the derived feature, without manually editing generated files?
EDIT>
To clarify: I'm looking for a way to directly change the generated Java files, by specifying method bodys (as strings) for the getters of derived EStructuralFeatures.
EMF provides a way of dealing with dedicated implementation for EOperation and derived EAttribute using "invocation delegate". This functionality allows you to put some implementation directly in your ecore metamodel in a string format (as soon as the used language can be "handled" by EMF, i.e, an invocation delegate exists).
As far as I know, OCL is well supported: https://wiki.eclipse.org/OCL/OCLinEcore#Invocation_Delegate
The registration of the invocation delegate is performed either by plugin registration or by hand (for standalone usage), and the mechanism works with the EMF reflection layer (dynamic EMF): https://wiki.eclipse.org/EMF/New_and_Noteworthy/Helios#Registering_an_Invocation_Delegate
(Please note that I never experienced this mechanism. I know it exists, but I never played with it.)
EDIT>
It seems that the question was not related to dynamic code execution for derived attribute, but to code injection (I misunderstood the "Is there a way to take a String and specify this String as the implementation for the computation of the derived feature?").
EMF provides a way of injecting code placed on the ecore metamodel directly into the generated code.
Here is the way for EAttribute with derived property. The EAttribute should have the following properties set to true: {derived volatile} (you can also add transient). If you only want a getter and no setter for your EAttribute, you can also set the property changeable to false.
Once your EAttribute is well "configured", you have to add a new EAnnotation with the source set to http://www.eclipse.org/emf/2002/GenModel and an entry with the key set to get and value set to your code that will be injected (see image below).
And voilĂ , your code will be generated with the value value injected in your getter.
You can add the same process for EOperation using body instead of get.

What is the best way to auto-generate values for features when an EObject is created?

I have some attributes in my EClasses I would like to initialize to a computed value when an instance is created. I'm wondering what the recommended way to do this using the framework is.
In one case I'd like to initialize the id attribute to a UUID. In this case I'd like the UUID value to be assigned when the object is first created and then remain the same for the life of the object.
In another case I'd like to generate a short id that only needs to be unique within the model instance.
I'm new to EMF and would greatly appreciate any guidance.
In both cases, I usually make the attributes suppress Setter and initialize the them in the default constructor.
the UUID is generated via EcoreUtils.generateUUID()
the class unique id is generated from a class static nextID
The attributes are not made unchangeable as we must (normally) be able to load a XML file and these must take precedence over the ones set in the constructors.
The class unique id, is slightly more difficult to handle as we must also initialize nextID to a good value when the application starts.
Consider the sequence where we create a number of objects first and then load an old file: how do we ensure there are no duplicates between the objects? One possible method is to divide the id into two parts: a timestamp and a sequence number. Assuming we cannot restart the application within the resolution of the timestamp (usually one second) this works quites all right.
This solution still assumes we never need to load two or more old files as these may conflict if created at the same time in different application instances....
All-in-all, I normally stick with UUIDs as this method avoids all of the above problems :-)

DRYing c++ structure

I have a simple c++ struct that is extensively used in a program. Now I wish to persist the structure in a sqlite database as individual fields (iow not as a blob).
What good ways are there to map the attributes of the struct to database columns?
Since C++ isn't not a very "dynamic" language, it is running short of the kinds of ORM's you might commonly find available in other languages that make this task light work.
Personally speaking, I've always ended up having to write very thin wrapper classes for each table manually. Basically, you need a structure that maps to each table and an accessor class to get data in and out of the table as needed.
The structures should have a field per column and you'll need methods for each database operation you want to perform (CRUD for example).
Some interpreted / scripting languages (PHP, etc) support "refection", where code can examine itself. That would allow a database framework to automatically serialize struct members to / from a database. Unfortunately, C/C++ do not natively support this. Therefore, unless you want to store it as a giant BLOB (which certainly has drawbacks), you will need to manually map each member of the struct to a db column.
The only tricky part (aside from time consuming), is to choose the db column type that best corresponds to the C data type. (char[] -> varchar, etc). As jkp suggested, it's nice to have a thin wrapper class to read / write each of your persistent structures.
Hard to answer in general. The easiest approach would be one column per attribute, that may or may not be appropriate for your application.
The other extreme would be to merge it all into one column, depending on how you are going to use the data stored.
Maybe use some other persistence framework? sqlite might not be the best solution here.
I like to use a one to one relationship between my data structure fields and data base fields. Where each record in the table represents a complete structure instance. The only exception is if it will cause excessive de-normalization in the table. Now to get the data to/from the database from the structure I implement a template class that takes the structure as template parameter. I then derive from the template and implement the get/set features of the structure to the database. I use the OTL library for all the real database IO. This makes the burden of a special class per structure type less intrusive.
I have created a system of Fields and Records, now based on the Composite Design Pattern. The Fields contain a method to return the field name and optionally the field type (for an SQL statement). I'm currently moving the SQL stuff out of the field and into a Visitor object.
The record contains a function to return the table name.
Using this scheme, I can create an SQL table without knowing the details of the fields or records. I just call polymorphic methods in the base class.
I've tried other techniques, but my code has evolved to this implementation.
Contrary to some of the other answers, I say it is possible for this task to be automated. E.g. take a look at quince (http://quince-lib.com). It lets you do stuff like this:
struct point {
float x;
float y;
};
QUINCE_MAP_CLASS(point, (x)(y))
extern database db;
table<point> points(db, "points");
(Full disclosure: I wrote quince.)

What is an ObjectMother?

What is an ObjectMother and what are common usage scenarios for this pattern?
ObjectMother starts with the factory pattern, by delivering prefabricated test-ready objects via a simple method call. It moves beyond the realm of the factory by
facilitating the customization of created objects,
providing methods to update the objects during the tests, and
if necessary, deleting the object from the database at the completion of the test.
Some reasons to use ObjectMother:
* Reduce code duplication in tests, increasing test maintainability
* Make test objects super-easily accessible, encouraging developers to write more tests.
* Every test runs with fresh data.
* Tests always clean up after themselves.
(http://c2.com/cgi/wiki?ObjectMother)
See "Test Data Builders: an alternative to the Object Mother pattern" for an argument of why to use a Test Data Builder instead of an Object Mother. It explains what both are.
As stated elsewhere, ObjectMother is a Factory for generating Objects typically (exclusively?) for use in Unit Tests.
Where they are of great use is for generating complex objects where the data is of no particular significance to the test.
Where you might have created an empty instance below such as
Order rubishOrder = new Order("NoPropertiesSet");
_orderProcessor.Process(rubishOrder);
you would use a sensible one from the ObjectMother
Order motherOrder = ObjectMother.SimpleOrder();
_orderProcessor.Process(motherOrder);
This tends to help with situations where the class being tested starts to rely on a sensible object being passed in.
For instance if you added some OrderNumber validation to the Order class above, you would simply need to instantiate the OrderNumber on the SimpleObject class in order for all the existing tests to pass, leaving you to concentrate on writing the validation tests.
If you had just instantiated the object in the test you would need to add it to every test (it is shocking how often I have seen people do this).
Of course, this could just be extracted out to a method, but putting it in a separate class allows it to be shared between multiple test classes.
Another recommended behavior is to use good descriptive names for your methods, to promote reuse. It is all too easy to end up with one object per test, which is definitely to be avoided. It is better to generate objects that represent general rather than specific attributes and then customize for your test. For instance ObjectMother.WealthyCustomer() rather than ObjectMother.CustomerWith1MdollarsSharesInBigPharmaAndDrivesAPorsche() and ObjectMother.CustomerWith1MdollarsSharesInBigPharmaAndDrivesAPorscheAndAFerrari()