How to use mock in support of UI development? - multithreading

I m working on a user interface in JavaFX. It is the front-end of an infrastructure service that I have already developed and is operational. I read here and there that mock can be used to avoid running all the system when it is to heavy to run, but also for isolation purpose.
At present I want to run some basic test as I am also learning how to use JavaFX and I would not want to run all my infrastructure for the matter.
Basically I have a TreeView that I would like to update based on what is coming from the service. Normally the service that runs in background would update the model and call a Platform.runlater() method to ask the UI to refresh.
I was wondering how can I achieve that using mocking. How can I have a mock object update a simplified shared structure such as a list(model) and then call Platform.runlater()? Actually I would first ask: is it a possible and appropriate usage of mock and if yes how can it be done, with which framework?
Personally what is a bit not clear to me is the involvement of multi-threading. Indeed my object under test which is the interface would not be calling any method of my mock, expect indirectly, the Run() method, given that my service is a runnable.
Hence I would appreciate if anyone could enlighten me a bit further on the matter. I'm confused....
Best,
Maatari

First prepare applications (or change your current app to support test mode) which can populate your TreeView with specific data. The entity which will provide fake data for TreeView will be your mock object for specific data. It should look like a service from TreeView point of view, which means you need to extract common methods from your services class into interface and make TreeView use this interface instead of concrete class.
To handle UI testing you can you use JemmyFX library. You can create simple test which will verify any UI properties of your TestView or imitate user actions like mouse clicks or text input. You may not worry about threading issues, jemmy will handle it for you.
It can look next way (I use junit as test harness here):
public class TreeTest {
#BeforeClass
public static void setUpClass() throws Exception {
// running your specially crafted FX application with mock service data
// you can do it any way, e.g. by calling main() method with some parameters
AppExecutor.executeNoBlock(TreeApp.class);
}
#Test // this is junit annotation for test
public void fooTest() {
// here we are receiving special jemmyfx entity which knows how to handle
// tree views and is attached to your TreeView
// (if you app has only one TreeView, you may need additional logic for several ones)
TreeViewDock tree = new TreeViewDock(new SceneDock().asParent());
// this way we can find some item which you expected to see in you TreeView
// because you've created you mock data this way.
// Note that underlying code will respect UI threading,
// will understand that UI can have delay and will give it certain time without blocking
// and will throw descriptive exception in case expected item wasn't found
tree.asTree().selector().select(new ByToStringLookup("item1"));
// you can find subitems
tree.asTree().selector().select(new ByToStringLookup("item1"), new ByToStringLookup("subitem1");
// and perform operations on them, e.g. expand:
new TreeItemDock(tree.asItemParent(), new EqualsLookup("item2")).asTreeItem().expand();
//etc
}
You can find more info on site on just by code completion hints

Related

Transition to route's action from Ember object

I am fairly new to ember. I have an existing Ember App and i need to implement a functionality in it. I have a Ember Object as below
`import Ember from 'ember'`
CallService = Ember.Object.extend
... other code here
_updateConnectedLeadId: (->
console.log "Do i get here??"
**pass the route action here**
).observes('some_other_here')
`export default CallService`
Unfortunately, i couldn't put the whole code here.
My route looks like
ApplicationRoute = Ember.Route.extend
actions:
showLead: ->
console.log data
console.log "did i get here?"
#transitionTo('dashboard')
`export default ApplicationRoute`
I tried using #send('showLead'), #sendAction('showLead') in my method but no luck.
My main intention is to make a transition once the console.log "Do i get here??" is displayed. I am not sure if i am on the right way here.
I also tried using #transitionTo('dashboard') and #transitionToRote('dashboard') directly but it throws me errors.
I have been stuck for a day on this now and i am clueless.
I'll be grateful for any guidance and help. Thanks
You have the problem that you are trying to trigger a route action or trigger a transition from within an Ember.Object, named call service. The code you create is unclear about where your custom object is being created; where the observer is triggered due to a change to object's property update, and so on.
Nevertheless, I tried to provide a working example for you. If you open the twiddle, you will see that I created a my-object instance within index.js route and pass it as model to my-component. When you click the button within my-component.hbs. The my-object instances dummyVariable is toggled and the observer within my-object executes. The tricky part here is that I passed index route itself as ownerRoute property to my-object instance; so that I can trigger the index route's dummyAction from within my-object.js with
ownerRoute.send('dummyAction');
so that related action executes and transition to my-route is performed. Although, I believe this might solve your question; I am not quite happy about the design. I do not think, it is a good way for Ember.Objects to know about routes, actions, controllers, etc. I believe the proper way is observing object's relevant properties from within this constructs and perform necessary actions by their own. Moreover, you might consider creating a service instead of an object and inject the service directly to your route instead of creating an instance of your class extending Ember.Object. If you have to extend from Ember.Object you can just inject relevant route, controller, etc to the instances of that particular object class by using an instance-initializer if you need.
Anyway, please take a look at the twiddle and ask more if you need to. I will be happy to help if I can.

User roles and workflow status xpages and managed bean

To not have to keep repeating some validations, for example, who can see a button in a certain status of a document in the worlflow, I'm using session, scope, and session variables to store the user roles and application variable to store the Status related to each area.
I was evaluating whether it would be better from a performance and build point of view to implement a managed bean, to return the user roles and the possible statuses of each participating workflow area. Would it be the best structure in fact? What do you think? I do not have much experience in java. How could I construct the structure in java, several methods, one for roles and the other for set of status associated with the area that would name the related method? You could return the results of this method in arrays, or there is a better return structure.
Thanks a lot!
My best suggestion is to adopt the pageController Methodology. Then it's more like true MVC. This has been talked about on NotesIn9 screencast many times but basically you have a java object that's bound to your XPage. In effect it's a viewScoped bean that holds all your page logic. Then you can have methods like isGroupMember(), hasRole() etc and calculate that on the pageInit. There's little need to hold onto that in sessionScope in my opinion. So for example I have this in my pageController :
public boolean isGroupMember(String groupName) {
return JSFUtil.getXSPContext().getUser().getGroups().contains(groupName);
}
So that's available to each page. BUT I don't need to copy that snippet onto every page controller. In Java you can have your page controllers extend a more generic class. so I have a "base.pageController" class. All the specific page controllers extend that. So this isGroupMember() code goes into the base and then it's available to be used on every XPage. Doing it this way gives you the ability to have generic functions like this and then hold more specific function that are only for the individual page.
You can also have a hasRole() function etc...
Recommend you check out this video : http://www.notesin9.com/2016/08/25/notesin9-196-no-dependency-page-controllers/
Also for a question like this, I recommend you just use the xpages tag. Adding others like javabeans can bring people in who know nothing about XPages and XPages is unique enough of a beast that outsiders can cause some confusion on occasion.

Kohana 3.3 - how to correctly move controller function to model

again I've got a question about Kohana and how I am supposed to use model functions.
I want to move parts of a controller function into a more appropriate model to be able to access this function from additional controllers. (From what I have read so far I conclude that calling the controller function from a different controller is considered bad architecture).
My problem is that depending on several circumstances (i.e. model parameters) this controller function creates a log entry in a different database table and sends an email to some users.
How am I supposed to create this log entry and send the mails if main functionality resides inside the model? Should I instantiate the second model from within the first, call the log function and afterwards send the mails exactly how I did from my controller?
Thanks in advance.
This is a question that doesn't have 1 correct answer, unfortunately. A lot of it comes down to how you prefer to implement the MVC pattern.
At its base MVC uses: Models, Views and Controllers
Models
These classes should represent entities in your database
Example:
Model_User maps to an entity in your Users table
$user = new Model_User;
$user->first_name = 'Joe';
$user->last_name = 'Smith';
$user->save();
Views
These files store presentation data/templates (html usually/mostly)
Example:
index.tpl
<h1>HELLO, WORLD!</h1>
<h2><?=$some_variable_from_controller?></h2>
Controllers
These files handle incoming requests and process data to be injected into views
Example:
Controller_Home handles request to the home page
class Controller_Home extends Controller {
public function action_index(){
$view = View::factory('index');
$view->render();
}
}
Now that you get the basics it's time to understand a specific problem this limited structure promotes. Controllers get kind of fat and messy. This leads us to libraries or a service oriented architecture.
These libraries allow us to move large groups of logic into a portable service layer that can easily be used across all controllers, models and other libraries. They also break our code up into smaller more concise chunks that actually made sense.
Example:
In my controller instead of using a bunch of logic that logs a user in via facebook I can simply create a Social_Login_Service and use it as follows.
Social_Login_Service::facebook($user_email);
Now you would simply see that 1 clean line in your login controller instead of a whole messy slew of logic that will pile up in your controller until it melts your brain to looks at.
This is a very basic overview of a possible direction (and one that I prefer).
It is very useful to break up your sites into smaller components and if you're using Kohana, I recommend doing this with Modules (http://kohanaframework.org/3.1/guide/kohana/modules) they're great.
I hope this little snippet helped.

Custom Control Custom Methods?

I have been making good use of custom properties withing custom controls. Is there such thing as custom methods? Say I want something to happen in a CC. A good example is the show method of the dialog box extension. If I have a cc with a extension dialog inside, I want my custom control to have a Show method which insulates the end user programmer from the extension pages Shoe method.
Is there anyway to do this?
At runtime, all Custom Control elements become instances of the UIIncludeComposite class; as such, there are many built in methods that you can call against any given control instance, but there is no way to specify custom methods, as opposed to custom properties.
There are, however, at least two ways you could achieve the result you're after:
Convert your Custom Control to a component (this NotesIn9 episode describes the simplest approach to this process). Once you've migrated the class that Designer generated to one that won't get overridden every time you build your NSF, you can add custom methods without fear that the next build will just wipe them out again. Since Custom Controls are essentially just IBM's implementation of the JSF 2.0 notion of "composite components", you could also create a component from scratch that has the same behavior as your existing Custom Control but also supports custom behavior. Note that either approach does not necessarily require that you create an OSGi library... you can define these components directly in an NSF; you only need to push them to a library if you want to reuse them across multiple NSFs without having to copy the various files to each.
In the custom properties for your control, include one property that accepts an API object. In other words, you could create any object (say, a Java class or SSJS object) that supports the custom methods you wish to define, and pass that object to the control. You could then call those methods by getting a handle on the object via the CC's property map.
For example:
<myCC id="myCustomControl" API="#{someObject}" />
Assuming whatever #{someObject} resolves to includes a show() method, you can call that method by getting a handle on the instance that has been passed to the control:
var cc = getComponent("myCustomControl");
var ccProperties = cc.getPropertyMap();
var ccAPI = ccProperties.get("API");
ccAPI.show(cc);
In the above example, I'm passing the actual Custom Control to the show() method, because the object itself isn't aware of the Custom Control it was passed to. So if that method needs to get a handle on its children to toggle their rendered property, for example, then it needs some other way of determining its context.
Tim's solution with passing in the object is a great solution to that.
Just something that popped into my head, would be easy to make a property similar to the rendered property on a control. Pass in a value and inside the custom control do something based on its value ie. if true display dialog, else hide, in the XPage during run time modify this value and partial refresh the control, the logic will be re run by this and the control will display etc.
Another solution could be to include a JavaScript library in your custom control providing functions (your custom control methods) where you'd have to pass in the id of the custom control instance.

Preventing StackOverflowException while serializing Entity Framework object graph into Json

I want to serialize an Entity Framework Self-Tracking Entities full object graph (parent + children in one to many relationships) into Json.
For serializing I use ServiceStack.JsonSerializer.
This is how my database looks like (for simplicity, I dropped all irrelevant fields):
I fetch a full profile graph in this way:
public Profile GetUserProfile(Guid userID)
{
using (var db = new AcmeEntities())
{
return db.Profiles.Include("ProfileImages").Single(p => p.UserId == userId);
}
}
The problem is that attempting to serialize it:
Profile profile = GetUserProfile(userId);
ServiceStack.JsonSerializer.SerializeToString(profile);
produces a StackOverflowException.
I believe that this is because EF provides an infinite model that screws the serializer up. That is, I can techincally call: profile.ProfileImages[0].Profile.ProfileImages[0].Profile ... and so on.
How can I "flatten" my EF object graph or otherwise prevent ServiceStack.JsonSerializer from running into stack overflow situation?
Note: I don't want to project my object into an anonymous type (like these suggestions) because that would introduce a very long and hard-to-maintain fragment of code).
You have conflicting concerns, the EF model is optimized for storing your data model in an RDBMS, and not for serialization - which is what role having separate DTOs would play. Otherwise your clients will be binded to your Database where every change on your data model has the potential to break your existing service clients.
With that said, the right thing to do would be to maintain separate DTOs that you map to which defines the desired shape (aka wireformat) that you want the models to look like from the outside world.
ServiceStack.Common includes built-in mapping functions (i.e. TranslateTo/PopulateFrom) that simplifies mapping entities to DTOs and vice-versa. Here's an example showing this:
https://groups.google.com/d/msg/servicestack/BF-egdVm3M8/0DXLIeDoVJEJ
The alternative is to decorate the fields you want to serialize on your Data Model with [DataContract] / [DataMember] fields. Any properties not attributed with [DataMember] wont be serialized - so you would use this to hide the cyclical references which are causing the StackOverflowException.
For the sake of my fellow StackOverflowers that get into this question, I'll explain what I eventually did:
In the case I described, you have to use the standard .NET serializer (rather than ServiceStack's): System.Web.Script.Serialization.JavaScriptSerializer. The reason is that you can decorate navigation properties you don't want the serializer to handle in a [ScriptIgnore] attribute.
By the way, you can still use ServiceStack.JsonSerializer for deserializing - it's faster than .NET's and you don't have the StackOverflowException issues I asked this question about.
The other problem is how to get the Self-Tracking Entities to decorate relevant navigation properties with [ScriptIgnore].
Explanation: Without [ScriptIgnore], serializing (using .NET Javascript serializer) will also raise an exception, about circular
references (similar to the issue that raises StackOverflowException in
ServiceStack). We need to eliminate the circularity, and this is done
using [ScriptIgnore].
So I edited the .TT file that came with ADO.NET Self-Tracking Entity Generator Template and set it to contain [ScriptIgnore] in relevant places (if someone will want the code diff, write me a comment). Some say that it's a bad practice to edit these "external", not-meant-to-be-edited files, but heck - it solves the problem, and it's the only way that doesn't force me to re-architect my whole application (use POCOs instead of STEs, use DTOs for everything etc.)
#mythz: I don't absolutely agree with your argue about using DTOs - see me comments to your answer. I really appreciate your enormous efforts building ServiceStack (all of the modules!) and making it free to use and open-source. I just encourage you to either respect [ScriptIgnore] attribute in your text serializers or come up with an attribute of yours. Else, even if one actually can use DTOs, they can't add navigation properties from a child object back to a parent one because they'll get a StackOverflowException.
I do mark your answer as "accepted" because after all, it helped me finding my way in this issue.
Be sure to Detach entity from ObjectContext before Serializing it.
I also used Newton JsonSerializer.
JsonConvert.SerializeObject(EntityObject, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });

Resources