TC3: Calling an FB method from the XAE Environment for testing purposes - twincat

I was wondering if it is possible to call a method directly from the XAE environment (online) for testing purposes. This would vastly reduce the amount of time to quickly test a function.
As an example; now I would write for each method:
IF bTestMethod THEN
fbFunctionBlock.method(parameters);
bTestMethod := FALSE;
END_IF
It would be nice to be able to call the function directly from the header within the online XAE interface by (for example) using a pragma like properties.
Maybe this functionality is already available that I'm not aware of? What would be the best / fastest way to test methods?
Thanks in advance,
Wouter

It would be nice to be able to call the function directly from the header within the online XAE interface by (for example) using a pragma like properties.
There is a pragma for calling methods remotely {attribute 'TcRpcEnable'}. But I don't know of any way to call it directly from XAE.
In the past I have used this pragma to test a method against an online 'calculator' with the help of node-red and this ADS node.
You can also add the method with the pragma to an opc-ua server. And use a client like UA-Expert to call the method manually.
Once you added the pragma, there are multiple ways to call it and test it over Ads. For many languages is a library available to make the ads calls. You can build a small test script, or a full test framework.
Like already mentioned in other answers, there is also a unit-testing library available to test code inside the controller without the need for extra software and pragma's: TcUnit

Maybe this functionality is already available that I'm not aware of?
Not that I'm aware of. There is no way to just call a function/method from XAE, because all the code is executed cyclically. So you need some way to 'activate' the function.
What would be the best / fastest way to test methods?
Make unit tests for individual functions and function blocks. Or you can make a digital twin to simulate machine behavior.

Related

How to use a single AWS Lambda for both Alexa Skills Kit and API.AI?

In the past, I have setup two separate AWS lambdas written in Java. One for use with Alexa and one for use with Api.ai. They simply return "Hello world" to each assitant api. So although they are simple they work. As I started writing more and more code for each one, I started to see how similar my java code was and I was just repeating myself by having two separate lambdas.
Fast forward to today.
What I'm working on now is having a single AWS lambda that can handle input from both Alexa and Api.ai but I'm having some trouble. Currently, my thought is that when the lambda is run, there would be a simple if statement like so:
The following is not real code, just what I think I can do in my head
if (figureOutIfInputType.equals("alexa")){
runAlexaCode();
} else if (figureOutIfInputType.equals("api.ai")){
runApiAiCode();
}
The thing is now I need to somehow tell if the function is being called by an alexa or api.ai.
This is my actual java right now:
public class App implements RequestHandler<Object, String> {
#Override
public String handleRequest(Object input, Context context) {
System.out.println("myLog: " + input.toString());
return "Hello from AWS";
}
I then ran the lambda from Alexa and Api.ai to see what Object input would get generated in java.
API.ai
{id=asdf-6801-4a9b-a7cd-asdffdsa, timestamp=2017-07-
28T02:21:15.337Z, lang=en, result={source=agent, resolvedQuery=hi how
are you, action=, actionIncomplete=false, parameters={}, contexts=[],
metadata={intentId=asdf-3a2a-49b6-8a45-97e97243b1d7,
webhookUsed=true, webhookForSlotFillingUsed=false,
webhookResponseTime=182, intentName=myIntent}, fulfillment=
{messages=[{type=0, speech=I have failed}]}, score=1}, status=
{code=200, errorType=success}, sessionId=asdf-a7ac-43c8-8ae8-
bc1bf5ecaad0}
Alexa
{version=1.0, session={new=true, sessionId=amzn1.echo-api.session.asdf-
7e03-4c35-9d98-d416eefc5b23, application=
{applicationId=amzn1.ask.skill.asdf-a02e-4938-a747-109ea09539aa}, user=
{userId=amzn1.ask.account.asdf}}, context={AudioPlayer=
{playerActivity=IDLE}, System={application=
{applicationId=amzn1.ask.skill.07c854eb-a02e-4938-a747-109ea09539aa},
user={userId=amzn1.ask.account.asdf}, device=
{deviceId=amzn1.ask.device.asdf, supportedInterfaces={AudioPlayer={}}},
apiEndpoint=https://api.amazonalexa.com}}, request={type=IntentRequest,
requestId=amzn1.echo-api.request.asdf-5de5-4930-8f04-9acf2130e6b8,
timestamp=2017-07-28T05:07:30Z, locale=en-US, intent=
{name=HelloWorldIntent, confirmationStatus=NONE}}}
So now I have both my Alexa and Api.ai output, and they're different. So that's good. I'll be able to tell which one is which. but I'm stuck. I'm not really sure if I should try to create an AlexaInput object and an ApiAIinput object.
Am I doing this all wrong? Am I wrong with trying to have one lambda fulfill my "assistant" requests from more than one service (Alexa and ApiAI)?
Any help would be appreciated. Surely, someone else must be writing their assistant functionality in AWS and wants to reuse their code for both "assistant" platforms.
I had the same question and same thought, but as I got further and further in implementing, I realized that it wasn't quite practical for one big reason:
While a lot of my logic needed to be the same - the format of the results was different. Sometimes, even the details or formatting of the results would be different.
What I did was go back to some concepts that were familiar in web programming by dividing it into two parts:
A back-end system that was responsible for taking parameters and applying the business logic to produce results. These results would be fairly low-level, not entire phrases, but more a set of keys/value pairs that indicated what kind of result to give and what values would be needed in that result.
A front-end system that was responsible for handling things that were Alexa/Assistant specific. So it would take the request, extract parameters and state, call the back-end system with this information, get a result back which included what kind of reply to send and the values needed, and then format the exact phrase (and any other supporting info, such as a card or whatever) and put it into a properly formatted response.
The front-end components would be a different lambda function for each agent type, mostly to make the logic a little cleaner. The back-end components can either be a library function or another lambda function, whatever makes the most sense for the task, but is independent of the front-end implementation.
I suppose one could also this by having an abstract parent class that implements the back-end logic, and having the front-end logic be subclasses of this. I wouldn't do it this way because it doesn't provide as clear an interface boundary between the two, but its not unreasonable.
You can achieve the result (code reuse) a different way.
Firstly, create a method for each type of event (Alexa, API Gateway, etc) using the aws-lambda-java-events library. Some information here:
http://docs.aws.amazon.com/lambda/latest/dg/java-programming-model-handler-types.html
Each entry point method should deal with the semantics of the event triggering it (API Gateway) and call into common code to give you code reuse.
Secondly, upload your JAR/ZIP to an S3 bucket.
Thirdly, for each event you want to handle - create a Lambda function, referencing the same ZIP/JAR in the S3 bucket and specifying the relevant entry point.
This way, you'll get code reuse without having to juggle multiple copies of the code on AWS, albeit at the cost of having multiple Lambdas defined.
There's a great tool that supports working this way called Serverless Framework which I'd highly recommend looking at:
https://serverless.com/framework/docs/providers/aws/
I've been using a single Lambda to handle Alexa ASK and Microsoft Luis.ai responses. I'm using Python instead of Java but the idea is the same and I believe that using an AlexaInput and ApiAIinput object, both extending the same interface should be the way to go.
I first use the context information to identify where the request is coming from and parse it into the appropriate object (I use a simple nested dictionary). Then pass this to my main processing function and finally, pass the output to a formatter again based on the context. The formatter will be aware of what you need to return. The only caveat is that handling session information; which in my case I serialize to my own DynamoDB table anyway.

Can I fake calling methods in Ruby tests?

I'm running some tests on my Ruby code, but the method I'm testing calls a function in an external library responsible for sending push notifications. I want the calls it makes to be 'faked', so they don't actually get called. It'd also be helpful if they could return a standard response, or yield with a standard response. Is there any way to do this?
Sure you can fake calling methods in Ruby tests. What you are looking for is creating so called mock code. It is entirely possible to return anything you want from such mock code.
You can create an identifier in Ruby which shadows another one - so for example you can create your own function shadowing one already existing in a library.
Google for the items written above in bold or ask more specific question, if needed.
The VCR gem makes it very easy to save your test suite's HTTP interactions and run them deterministically. That would be my suggested approach.
You can also, as others have pointed out, stub the method you are calling and manually specify its response. If you were using rspec, this would mean to add a line above the HTTP call in the test. Something along the lines of:
allow(Pusher).to receive(:message).and_return( "An object of your liking" )

Implementing Front Controller pattern

I've been trying to implement a Front Controller on a VBScript (ASP Classic) based system for a couple of days. I come from a ASP.NET MVC and Java background, where MVC implementations are kind common and mostly done by existing frameworks. On VBScript, however, there's almost nothing done in this area, so it is the reason why I'm trying to do it by myself. I used this and this article as a guide on how to implement it.
I believed at first that I'd need to define some constant parameters for each request, so I created 3:
class_command 'which command responsible to execute the correct class handler
action 'which method of the class handler to execute
action_params 'which parameters the action will need
Next, I defined a generic controller handler for treating the request:
Public Function Controller_Handler(action_params)
Its task is to extract the constant parameters (class_command, action, action_params) and treat any errors (I'll add later a filter to process it) that might come like absence of the constant parameters or authentication problems.
But soon I realized a problem: how will the handler know which command to call, since the request is a string? I can't simply converting it to class using reflection, because VBScript (I think) doesn't have a reflection library or built-in feature.
So I thought I could create a Switch Case like this:
Select action_Params.Item("action_params")
Case "command_A"
' Call Command A
Case "command_B"
' Call Command_B
.
.
.
Case "Command_X"
' And so on
End Select
But that would kinda procedural way to do it. Next I thought of creating a XML file which would map all the commands and other stuff.
So my question is: is this a good way of implementing a Front Controlller pattern, considering VBScript limitations? If not, could you provide a guidance (hopefully with some example, even a simple one) on how can I do it?
Moving from classic to .net/mvc I can share what I did in classic asp to try to emulate this behavior as closely as possible without making it too much of a maintenance issue.
Using URL Rewrite in IIS are my routes. I usually just make one route and direct/rewrite all inbound requests to one controller.asp page to simplify things and not have a bunch of rules and controller redirects directly in my URL Rewrite settings for maintaining it easier (for me).
Using Request.ServerVariables("HTTP_X-ORIGINAL-URL") in controllers.asp you can grab the actual URL that was entered, which return something like.. /real/url
In controllers.asp programatically call the view based on the entered url using Server.Execute("view1.asp")
I have one class file called routes.asp that is included in each model/class file, and helps me gather the URL properties oRoute.GetPath_FirstDirectory() and so on. The model/class file then uses this data to create its property values that can be consumed by the view. Using CLASS_INITIALIZE in each model/class to populate itself from the route/url, or it could also be done directly in the view.
In the respective view I include my class/model file (if even needed) using <!--#include file="class.asp"--> then simply open Set Model = new cModelClass to initialize and start using it in the view. I don't include the class in the controllers.asp because the view will not inherit any of the variables from controllers.asp when using Server.Execute() to the view. So I include it directly in the view.
Error handling can be at multiple levels here, but ideally its in the controllers.asp. Specific error handling is usually at the actual model/class CLASS_INITIALIZE to avoid redundant use of the class in the controller, since it's already going to be initialized in the view.
Now this is not exactly what goes in in .Net mvc, but it's the best way I've come up with, and easiest to maintain for me. Maybe others have other implementations, but this is mine and solely based on my experience. And so far, it's been working out pretty well.

CodeIgniter: Decision making for creating of library & helper in CodeIgniter

After developing in CodeIgniter for awhile, I find it difficult to make decisions when to create a custom library and when to create a custom helper.
I do understand that both allow having business logic in it and are reusable across the framework (calling from different controller etc.)
But I strongly believe that the fact that CI core developers are separating libraries from helpers, there has to be a reason behind it and I guess, this is the reason waiting for me to discover and get enlightened.
CI developers out there, pls advise.
i think it's better to include an example.
I could have a
class notification_lib {
function set_message() { /*...*/}
function get_message() {/*...*/}
function update_message() {/*...*/}
}
Alternatively, i could also include all the functions into a helper.
In a notification_helper.php file, i will include set_message(), get_message(), update_message()..
Where either way, it still can be reused. So this got me thinking about the decision making point about when exactly do we create a library and a helper particularly in CI.
In a normal (framework-less) php app, the choice is clear as there is no helper, you will just need to create a library in order to reuse codes. But here, in CI, I would like to understand the core developers seperation of libraries and helpers
Well the choice comes down to set of functions or class. The choice is almost the same as a instance class verses a static class.
If you have just a simply group of functions then you only need to make a group of functions. If these group of functions share a lot of data, then you need to make a class that has an instance to store this data in between the method (class function) calls.
Do you have many public or private properties to store relating to your notification messages?
If you use a class, you could set multiple messages through the system then get_messages() could return a private array of messages. That would make it perfect for being a library.
There is a question I ask myself when deciding this that I think will help you as well. The question is: Am I providing a feature to my framework or am I consolidating?
If you have a feature that you are adding to your framework, then you'll want to create a library for that. Form validation, for example, is a feature that you are adding to a framework. Even though you can do form validation without this library, you're creating a standard system for validation which is a feature.
However, there is also a form helper which helps you create the HTML of forms. The big difference from the form validation library is that the form helper isn't creating a new feature, its just a set of related functions that help you write the HTML of forms properly.
Hopefully this differentiation will help you as it has me.
First of all, you should be sure that you understand the difference between CI library and helper class. Helper class is anything that helps any pre-made thing such as array, string, uri, etc; they are there and PHP already provides functions for them but you still create a helper to add more functionality to them.
On the other hand, library can be anything like something you are creating for the first time, any solution which might not be necessarily already out there.
Once you understand this difference fully, taking decision must not be that difficult.
Helper contains a group of functions to help you do a particular task.
Available helpers in CI
Libraries usually contain non-CI specific functionality. Like an image library. Something which is portable between applications.
Available libraries in CI
Source link
If someone ask me what the way you follow when time comes to create Helpers or Libraries.
I think these differences:
Class : In a nutshell, a Class is a blueprint for an object. And an object encapsulates conceptually related State and Responsibility of something in your Application and usually offers an programming interface with which to interact with these. This fosters code reuse and improves maintainability.
Functions : A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value. You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.
So go for Class i.e. libraries if any one point matches
global variable need to use in two or more functions or even one, I hate using Global keyword
default initialization as per each time call or load
some tasks are private to entity not publicly open, think of functions never have public modifiers why?
function to function dependencies i.e. tasks are separated but two or more tasks needs it. Think of validate_email check only for email sending script for to,cc,bcc,etc. all of these needs validate_email.
And Lastly not least all related tasks i.e. functions should be placed in single object or file, it's easier for reference and remembrance.
For Helpers : any point which not matches with libraries
Personally I use libraries for big things, say an FTP-library I built that is a lot faster than CodeIgniters shipped library. This is a class with a lot of methods that share data with each other.
I use helpers for smaller tasks that are not related to a lot of other functionality. Small functions like decorating strings might be an example. Or copying a directory recursively to another location.

Creating mock data for unit testing

I consider myself still pretty new to the TDD scene. But find that no matter which method I use (mock framework or stubbing my own objects) I find that I have to write a lot of code to create mock data. I like the idea of loading up objects to create an in-memory database. But what I don't like is cluttering up my tests with a ton of code for the sole purpose of creating mock data. This is especially the case when the data needs to account for all the different cases.
I'd love some suggestions for a better way of doing this.
It would seem to me that I should be able to load the data once into a known state from some data store and then I could use a snapshot of that state which is loaded in the test setup/initialize before each test method is executed. This would satisfy proper testing practices while providing convenience and let me focus on writing tests instead of writing code to create test data "by hand".
May be you could try the NBuilder library. It provides a very fluent interface and is easy to use. You can use it for generating single instances of a class with defualt values or generate lists with default or overriden values. You can have a look at this one.
If your are using .Net Try NDBUnit
You populate your store and then it reverts your DB to a known state at test time, for each test. The Autumn of Agile screen cast series shows this in pretty good detail.
Or you can do this manually...build a stored procedure or whatever to truncate your tables and copy in the data in your teardown method.
You can have Builder class(es) that helps you building the instances you need / in this case ones you would use related to the repository.
Have the Builder use appropiate defaults, and on your tests you can overwride what you need. This helps you avoid needing to put have every single case of "data" mixed up for all the different tests (which introduces problems, because usually there are cases that aren't compatible for different tests).
**Update 1:**Take a look at www.markhneedham.com/blog/2009/01/21/c-builder-pattern-still-useful-for-test-data
I know exactly what you mean. I think a good approach to solving this problem is to actually have a separate MockFramework project that houses all your mock data, outside the test project. This way you can generate mock data separately, store it in memory if you want to, or not, and then reference the mock framework from the test project. If you use a third party framework to do this, all the better, but you can still wrap that third party framework in your own mock framework so you can get all that "glue" that creates the mock data the way you need it out of your tests so the tests can really be only what they need to be.
Thanks for all the suggestions, I think the solution requires a little bit of everything. I don't want these tests to end up being regression tests, but w/o some kind of existing data store everything still boils down to creating the data by "manually" building the objects.
What would really be nice would be a framework that allowed me to use my existing DAL to either script the data to code for me or get the data in memory and access it like an in memory database.
Untils.org covers this way better than I ever could.
Their whole guide is actually very good.
But basically, if your units require "a lot of data" they may not be unit tests anymore. I'd recommend attempting testing the smaller pieces individually.

Resources