How to use value of a property in referenced object inside alice fixture? - fixtures

I'm trying to create a fixture where two classes contain dates which values have a dependency.
A simple example, however ridiculous this is. Customers have animals, but sometimes animals change their owners. So I want to keep the date range of the relation. Sometimes animals are without an owner (shelter or whatever. this is just an example).
Obviously, the relationship cannot start before the animal is born, so I would like to keep it like that when creating a fixture.
My idea was:
App\Entity\Animals\Animal:
animal_{1..100}:
name: <firstName()>
birthDate: <dateTimeBetween("-10 years", "now")>
App\Entity\Animals\AnimalCustomer:
animalCustomer_{1..200}:
animal: '#animal_*'
relationStart: <dateTimeBetween($animal->birthDate(), "-2 months")>
relationEnd: 20%? <dateTimeBetween($relationStart, "now")>
Unfortunately, when using the fixture the $animal cannot be evaluated.
How to properly to handle this?

Related

How to define a function to get an field element of a Marshmallow Schema while still serialising through a nested Schema

So I have a Nested Many Schema (eg Users) inside another Schema (eg Computer). My input object to be deserialised by the Schema is complex and does not allow for assignment, and to modify it to allow for assignment is impractical.
The input object (eg ComputerObject) itself does not contain an a value called "Users", but nested in a few other objects is a function that can get the users (eg ComputerObject.OS.Accounts.getUsers()), and I want the output of that function to be used as the value for that field in the schema.
Two possible solutions exist that I know of, I could either define the field as field.Method(#call the function here) or I could do a #post_dump function to call the function and add it to the final output JSON as it can provide both the initial object and the output JSON.
The issue with both of these is that it then doesn't serialise it through the nested Schema Users, which contains more nested Schemas and so on, it would just set that field to be equal to the return value of getUsers, which I don't want.
I have tried to define it in a pre-dump so that it can then be serialised in the dump (note: this schema is used only for dumping and not for loading), but as that takes in the initial object I cannot assign to it.
Basically, I have a thing I am trying to do, and a bunch of hacky workarounds that could make it work but not without breaking other things or missing out on the validation altogether, but no actual solution it seems, anybody know how to do this properly?
For further info, the object that is being input is a complex Django Model, which might give me some avenues Im not aware of, my Django experience is somewhat lacking.
So figured this out myself eventually:
Instead of managing the data-getting in the main schema, you can define the method used in the sub-schema using post_dump with many=True, thus the following code would work correctly:
class User(Schema):
id = fields.UUID
#pre_dump(pass_many=True)
def get_data(self, data, **kwargs):
data = data.Accounts.getUsers()
return data
class Computer(Schema):
#The field will need to be called "OS" in order to correctly look in the "OS" attribute for further data
OS = fields.Nested(User, many=True, data_key="users")

Multiple properties with the same type in a structure concept

So it appears a structure concept cannot have properties with the same type.
For example if I have the following
structure (A) {
description (blah blah)
property (prop1) {
type (Type1)
}
property (prop2) {
type (Type1)
}
}
I get "ERROR: property #prop1 duplicates the type of property #prop2". Am I doing something wrong or is that how it is supposed to work? I don't understand why a structure can't have two properties of the same type. Anyway I have gotten around this by making an additional concept that extends the original, so the types technically have a different name but are functionally the same. However this is kind of a PITA because now I have to make all these extra concepts whenever I need a structure that needs more than one property of the same type.
Depending upon your use case, using role-of may be appropriate. What role-of is for is different contexts with the same underlying data.
For instance in a train schedule capsule, I may have an identical list of departure and arrival stations (as an enum). However these are contextually different. Using role-of lets me create a common train station concept but two contextually different roles e.g. both a departure station and an arrival station concept
With role-of I can use both in a structured concept.
Some example code (From my open source Bixby sample code - https://github.com/rogerkibbe/bixby_bart_commuter)
Excerpt from Station.model.bxb - base for station
enum (Station) {
description (BART Station Names)
symbol(12th St. Oakland City Center)
symbol(16th St. Mission)
symbol(19th St. Oakland)
symbol(24th St. Mission)
symbol(Antioch)
From this, I create two role-of concepts:
enum (SearchDepartureStation) {
description (Train Departure Station)
features {
transient
}
role-of (Station)
}
enum (SearchArrivalStation) {
description (Train Arrival Station)
features {
transient
}
role-of (Station)
}
And finally I can use both of the above in a structured concept (excerpt below):
structure (TrainSchedule) {
description (Train Schedule)
property (searchDepartureStation) {
type (SearchDepartureStation)
min (Required)
max (One)
}
property (searchArrivalStation) {
type (SearchArrivalStation)
min (Required)
max (One)
}
Yes, you would need to have a different type for each property since Bixby uses the type of each property for context when parsing user utterances.
If your Structure would make sense with all the properties of the same type lumped into one, you can use max(Many)(documentation) to indicate that prop is of type Type1 and may contain multiple values. An example use case for this option is a capsule that needs to handle recipe ingredients. All ingredients can be aggregated into one ingredients property without needing to have a separate property for each one.
If your Structure requires each property to be separate, you would need to create a different type for each property to allow Bixby to differentiate between each property. An example use case for this option is a capsule that tracks sports statistics. It is not enough to label each player on a basketball team as type(Player). You would need to define the type of player as well. This would be done by creating a Player type and extending it to each type of player (This is what you have done currently).

How to mock an array of interfaces using powermock or mockito

I am mocking an interface array which throws java.lang.IllegalArgumentException: Cannot subclass final class class.
Following are the changes I did.
Added the following annotations at class level in this exact order:
#Runwith(PowerMockRunner.class)
#PrepareForTest({ Array1[].class, Array2[].class })
Inside the class I am doing like this:
Array1[] test1= PowerMockito.mock(Array1[].class);
Array2[] test2= PowerMockito.mock(Array2[].class);
and inside test method:
Mockito.when(staticclass.somemethod()).thenReturn(test1);
Mockito.when(staticclass.somediffmethod()).thenReturn(test2);
Basically I need to mock an array of interfaces.
Any help would be appreciated.
Opening up another perspective on your problem: I think you are getting unit tests wrong.
You only use mocking frameworks in order to control the behavior of individual objects that you provide to your code under test. But there is no sense in mocking an array of something.
When your "class under test" needs to deal with some array, list, map, whatever, then you provide an array, a list, or a map to it - you just make sure that the elements within that array/collection ... are as you need them. Maybe the array is empty for one test, maybe it contains a null for another test, and maybe it contains a mocked object for a third test.
Meaning - you don't do:
SomeInterface[] test1 = PowerMock.mock() ...
Instead you do:
SomeInterface[] test1 = new SomeInterface[] { PowerMock.mock(SomeInterface.class) };
And allow for some notes:
At least in your code, it looks like you called your interface "Array1" and "Array2". That is highly misleading. Give interfaces names that say what their behavior is about. The fact that you later create arrays containing objects of that interface ... doesn't matter at all!
Unless you have good reasons - consider not using PowerMock. PowerMock relies on byte-code manipulation; and can simply cause a lot of problems. In most situations, people wrote untestable code; and then they turn to PowerMock to somehow test that. But the correct answer is to rework that broken design, and to use a mocking framework that comes without "power" in its name. You can watch those videos giving you lengthy explanations how to write testable code!

Referencing an instance of a given class in sequence diagrams

I have to model a system where an object of the class Person will invoke the static method getBook(...) : Book on the class Book which will return an instance of a particular book.
How do you reference the book instance obtained by the operation?
As of now, I can think of two approaches, neither of which I have ever seen/used, which is why I am looking for the correct approach.
The first approach is to invoke methods directly on the book instance obtained, e.g. if the reference returned by getBook(...) : Book is named matchingBook, I would use matchingBook.doSomething(...), much like having a local variable.
The second way, which I find more in the line of sequence diagrams is to let the book instance returned by the operation appear with its own lifeline, e.g. next to the Book class, and referencing it with an arrow labeled doSomething(...).
However, with the second approach, it is not that obvious that this object is in fact the one returned by the operation.
The second approach is the correct. To show that you are pointing to the returned object (matchingBook), you can add the variable name to the title of the lifeline, like this:
The second approach is the correct one. Anytime you call operations on an object returned by a first operation, you can't do better than a name match between the result of the first call and the lifeline.
Anyway I don't really understand what you expect of the first way: where would you put matchingBook.doSomething(...)? on a arrow pointing which lifeline?

optional parameters for immutable classes

I am not sure whether this is the right forum to ask this question, but it refers to code, so I am asking here.
In the book "Groovy in action", section 7.1.4 (named parameters), the author says that usage of named params "crops up frequently in creating immutable classes that have some parameters that are optional".
What has immutability of the class got to do with optional parameters? I thought these 2 topics were completely orthogonal.
crops up frequently in creating immutable classes that have some parameters that are optional
the sentence above is a bit blurry as there is no such thing as "class parameters", i can only assume it relates to method/constructor parameters.
when we're talking about constructors, Groovy's named parameters make sense when its about optional parameters:
#groovy.transform.Immutable
class Person {
String firstName
String lastName
Integer age
}
def p = new Person(age: 42, lastName: 'Doe')
The above example shows how to create an immutable Person instance. The firstName is not provided as named parameter, it's optional. In fact, with named parameters it's possible to specify any parameter combo when making the constructor call without actually having to implement constructors for all combinations.
There is also the possibility of using named parameters in instance/static method calls, as shown in this blog post by Mr. Haki.
The key to that statement is that if you're dealing with an immutable class, the implication is that you have only one chance to set state - in a constructor. Normally you'd be able to manipulate an (mutable) object via setters, one-at-a-time, to build up the desired state. For an immutable, you'd have to create a ctor for every possible set of instantiation states instead, if a facility like optional params were not available. For a class with many fields, this could get messy.

Resources