concordion assertEquals limitation - concordion

Concordion version of assertEquals allows to compare a method return value with the HTML element inner value, like
p concordion:assertEquals="getGreeting()">Hello World!
However in many cases, the expected value is generated dynamically during the test execution and is not known in advance. How to use Concordion assertEquals in that case? How to pass the expected value into the assertEquals?

A similar question was answered in the Concordion group:
https://groups.google.com/forum/#!topic/concordion/9hkcXCgwqWU
Did the answers help you?
If not, what do you need additionally?

Final solution from the thread referenced in the previous answer:
html:
<span concordion:execute="#result = getResults()"></span>
<p><span concordion:assertTrue="#result.matches">They match!</span>
Primary email is: <span concordion:echo="#result.primaryEmail"></span>
Secondary email is: <span concordion:echo="#result.secondaryEmail">
</span></p>
fixture:
import static org.concordion.api.MultiValueResult.multiValueResult;
public MultiValueResult getResults() {
return multiValueResult()
.with("primaryEmail", "t...#tfwright.co.nz")
.with("secondaryEmail", "t...#tfwright.co.nz")
.with("matches", true);
}

Related

Access filter result Angular 6

How can I access filteredArray in my .ts component? Because right now it is accessible only inside ng-container.
<ng-container *ngIf="(userList | filter: 'name' : value) as filteredArray">
<tr *ngFor="let user of filteredArray">
<td>{{user.name}}</td>
<td>{{user.group}}</td>
</tr>
<div>Count: {{ filteredArray.length }}</div>
</ng-container>
How can I modify the code in order to obtain what I want? Thank you for your time!
To answer your question directly: it's not possible the way you describe it. But read on.
Pipes (sometimes still called "filters") should be used only to format data, i.e. prepare it in a human-readable form. For example, the build-in date pipe can be used to transform an ISO string to a string such as "March 21st, 1995", which is how a human from the USA might expect to read the date.
The way you're using pipes is not recommended, precisely because of the question you have. You've essentially put application logic inside a template, which is an anti-pattern and beats the purpose of having easy-to-read declarative templates, which Angular uses in order to figure out how to update DOM.
You should move the filtering logic back to the class. For example, instead of setting this.userList = xxx, you could have a function which you call every time, such as this.changeUserList(xxx).
changeUserList (list) {
this.userList = list
this.filteredArray = list.filter(...)
}
You can put this logic in a setter as well, which allows you to run custom code when you write the usual this.userList = list, but you'll need a separate (usually prefixed private) property on the class where you'd actually store the value. It's not really a limitation since you can also have a trivial getter, so you can still us this.userList normally as a getter without having to remember to use this._userList, essentially tucking this away as the get/set pair's implementation detail.
private _userList
public set userList (list) {
this._userList = list
this.filteredArray = list.filter(...)
}
public get userList (list) { return this._userList }
Observables could really come in handy here as well, since you could just rx.map the userList$ to filteredArray$ with an Array#filter.
public userList$
public filteredArray$ = this.userList$.pipe(map(arr => arr.filter(...))
Then in the template, you can use the async pipe.
*ngIf="filteredArray$ | async as filteredArray"
Avoid doing the following.... but it works for demo purposes 😃
Create a component (e.g. demo-element.component.ts) that takes a single #Input() value:any
Add this new component as the first child of the <ng-container>, and give it a template reference #containerRef e.g.:
<ng-container *ngIf="(userList | filter: 'name' : value) as filteredArray">
<demo-element #containerRef [value]="filteredArray"></demo-element>
In your main component, add
#ViewChild('containerRef') ref;
ngAfterViewInit() {
this.filteredArray = this.ref.value; // Terrible pattern, but answers the question:-)
}
I hope this below code will help you.
<div class="rsrvtn_blk" *ngIf="(items | fSearch:firstname) as filteredItems">
<div class="col-md-3 pl-0" *ngFor="let item of filteredItems">
// you can display the filtered content here
</div>
</div>

Check for "Not in" a list condition Angular 2 template

I have a template as below:
<span *ngIf="item.status !=='E1' && item.status !=='B' && item.status !=='R'">{{item.status_desc}}</span>
As above, i have a ngIf condition there, making no sense but somehow it working. What am trying to do there is check "status in [E1, B, R]" something like that. How can i do that in the html without going to the ts file. Any idea guys?
In your HTML, you could use includes(), which returns true if the element is found:
<span *ngIf="!['E1', 'B', 'R'].includes(item.status)">{{item.status_desc}}</span>
as JB Nizet suggested.
Or you could use a function, like this:
statusList = [E1, B, R];
checkStatus(item)
{
return (statusList.indexOf(item) != -1);
}
where your HTML now should llol like this:
<span *ngif="checkStatus(item.status)">{{item.status_desc}}</span>
If you really don't want to go to your TypeScript source, you can do something like this for increased readability.
<span *ngIf="!['E1', 'B', 'R'].includes(item.status)">{{item.status_desc}}</span>
But perhaps it's wiser to make a variable on your class with the 'undesired' statuses like:
public ignoreStatus: string[] = ['E1', 'B', 'R'];
and then
<span *ngIf="!ignoreStatus.includes(item.status)">{{item.status_desc}}</span>
but then it would be even better to make a reusable method out of this in your class:
public isIgnoreStatus(item: any): boolean {
return this.ignoreStatus.includes(item.status);
}
with
<span *ngIf="!isIgnoreStatus(item.status)">{{item.status_desc}}</span>
No you cannot do that with template, what you can do is create a function that does the job for you
statuses = [E1, B, R];
checkValid(item){
return (statuses.indexOf(item) != -1);
}
then in HTML
<span *ngIf="checkValid(item.status)">{{item.status_desc}}</span>
You can create a pipe to do all this filters.
In that pipe you can write any logic to remove all unwanted elements.
It will make your code look better and understandable.

Grails losing image if not select new one on edit page

I'm making a website using spring security and grails 3.1.10. In this site I'm listing all image from database and show them at index. The problem is when I tried to edit one of those image. For example I want to just edit name but if I do not select an image this field become null.But I want to protect the image. How can i through this.
edit gsp
<div class="col-xs-2 col-sm-2 col-md-2">
<input type="file" class="form-control" name="productImage" id="productImage">
</div>
I tried to write a controller to protect old one but this one not work.
def id=params.id
Product old=Product.findById(params.id)
def f = request.getFile('productImage')
if(f.empty){
print("file is empty")
if(old.productImage){
println("there is a file in database")
product.productImage=old.productImage
}}
I think I kind of understand there are a few issues here:
//These two are the same
Long id=params.id ? params.id as Long : null
Long id=params.id ? params.long('id') : null
It says
Long id= (is there a params.id )
{ yes ? } -> params.id as Long {otherwise :} -> null
findById should be used in rare cases:
//You should never use findById unless an example would be findByIdAndSomethingElse(id,somethingElse)
// Product old=Product.findById(params.id)
Instead you should use (look int get read and load) get is the best since it ensures the record actually exists and where as read could return a cached copy (that may since be removed) (read load are less resource intensive) worth reading up about - so sticking with get : and you may not have id so it should be wrapped around a further
if (id) {
// Product old=Product.get(id)
// Product old=Product.read(id)
// Product old=Product.load(id)
// You could have just done this which should convert params.id as long itself as the method
Product old=Product.get params.id
def f = request.getFile('productImage')
if(f.empty){
print("file is empty")
if(old.productImage){
println("there is a file in database")
//I think this may be the issue:
product.productImage=old.productImage
//should this not be ?
product=old
}}
you have now outlined what old or product do after your statement which is the reason for my comment.
Does product or old then get sent as variables to the gsp page how are they represented ?
Also if this is your edit form;
<div class="col-xs-2 col-sm-2 col-md-2">
<input type="file" class="form-control" name="productImage" id="productImage">
</div>
This is missing value
<input type="file" class="form-control" name="productImage"
value="${someParams?.value}" id="productImage">
You state it returns null so it must be some other form field that you have not provided since this field actually has no value defined and therefore can never be a null.
Also notice
value="${someParams?.value}"
vs
value="${someParams.value}"
The ? is protecting the field from returning a null value. So upon start of a form where there may not be a value that would then save it showing null on the user's screen.
With all that said there appears to a be a conflict in what you say something going null vs what you are trying to set etc.. maybe a clash in what you want or maybe an easier way of putting it all
def f = request.getFile('productImage')
if (f.empty) {
if (params.id) {
Product old=Product.get(params.id as Long)
print("file is empty")
if (old.productImage) {
println("there is a file in database")
product.productImage=old.productImage
} else {
//what should produce.productImage be now if no file and nothing on db ?
}
} else {
//what should happen if there is no product.id ?
}
} else {
//what happens when there is a file provided - should that Product check be outside of this loop entirely should that file being returned be merged with the existing record ?
}
There is lots there that will hopefully help you understand what is going wrong. With that all said this sort of stuff should really be done with the aid of a validation class this saves on you having to code out lots of logic in your controllers that in the end looks all too long winded and messy and hard to follow.
I will update an example project: https://github.com/vahidhedayati/grails-bean-validation-examples a bit later today with an image example. Hopefully with a video to explain what I have added. Will leave a comment on here when done.

Concordion - how can i set a value into a table?

At some stage in a concordion test I have, I set a value to some random number.
This value is passed along, and later on , I have some output. The output is "checked" using the concordion "table" setup, where i compare an output value to what I expect it to be.
The problem I have is that I would like to check against the random number mentioned above. When I get the random number, I can set it to something Concordion can store -
<span c:set="#prefixValue">Bob</span>
Well, you get the idea - I replace "Bob" with a getter for my value.
But when I try to use it:
<table c:execute="#actual = getValue(#report, #xpath)">
<tr>
<th>Field name</th>
<th c:assertEquals="#actual">Value</th>
<th c:set="#xpath">Xpath</th>
</tr>
<tr>
<td>UnrelatedValue</td>
<td>SomeDeterminateValue</td>
<td>theXpathForThisToCompareTo</td>
</tr>
<tr>
<td>prefix</td>
<td><span c:echo="#prefixValue" /></td>
<td>differentXpathForThisToCompareTo</td>
</tr>
The whole shebang grinds to a halt, complaining that
"
Commands must be placed on elements when using 'execute' or 'verifyRows' commands on a <table>.
"
How can I use a pre-determined value in a table in Concordion?
The specs aren't supposed to have random elements in them. They're supposed to contain a specific example or set of examples. Rather than using a random number, hardcode a particular value and then you can use it later on.
To tell the fixture about the hardcoded value you can do this:
<span c:execute="setPrefixValue(#TEXT)">Bob</span>
Then in the fixture:
public void setPrefixValue(String prefixValue) {
// TODO: Whatever system configuration you need to do
}
If it isn't actually possible to set the value in your system under test, then use your fixture code to map between the hardcoded value and the actual random value.
public String getValue(String report, String xpath) {
String value = report(report).get(xpath);
if (value.equals(knownRandomValue)) {
return hardcodedValue;
}
return value;
}
Oh Lord! I didn't realise Concordion was going to get all rigid on me.
To fix, I had to alter the Concordion method I was using to be less stupidly rigid.
Following the general ideas here:
http://automatingsoftwaretesting.wordpress.com/2011/05/27/write-your-own-concordion-command-an-example-for-asserting/
I wrote this:
#Override
public void verify(CommandCall commandCall, Evaluator evaluator, ResultRecorder resultRecorder) {
Object expected = evaluator.evaluate(commandCall.getChildren().get(0).getExpression());
Object actual = evaluator.evaluate(commandCall.getExpression());
Element element = setupTheGoshDarnElement(commandCall, expected);
if (actual.equals(expected)) {
resultRecorder.record(Result.SUCCESS);
announceSuccess(element);
} else {
resultRecorder.record(Result.FAILURE);
announceFailure(element, expected.toString(), actual);
}
}
private Element setupTheGoshDarnElement(CommandCall commandCall, Object expected) {
Element e = commandCall.getElement();
e.appendText(expected.toString());
return e;
}
private void announceFailure(Element element, String expected, Object actual) {
listeners.announce().failureReported(new AssertFailureEvent(element, expected, actual));
}
private void announceSuccess(Element element) {
listeners.announce().successReported(new AssertSuccessEvent(element));
}
And so made a new "evaluator" ~ the rest of the evaluator is identical to the AssertEqualsCommand, if you're wondering.
This neatly checks the element and evaluates. Why concordion didn't do this ~ it isn't rocket science at all ~ is beyond me!
NOTE that I still need to use the "expanded table" in my question to get this to work, the short-form table has it's own issues with evaluating inner expressions.

Mvc Web Api Knouck and Json Tree Issue

I have 2 problems. Before I explain my problems I want to share my json result, a little part.
I wanna take all Category Properties(CategoryId,CategorySeoName...) and I write this.
public IEnumerable<Category> FindAllCategoryName()
{
return CategoryRepository.GetAll().Select(x => new Category
{
CategoryName = x.CategoryName
}).ToList();
}
But it gives an error like this "An exception of type 'System.NotSupportedException' occurred in System.Data.Entity.dll but was not handled in user code" and additional information "Category class have a complex type, you don't create Linq to Entities query". I think this problem about ICollection Tales propeties
My second problem is, list of this tales in category. I use knockout.js.
talesCrud.js
function TalesViewModel() {
var self = this;
self.tales = ko.observableArray();
$.getJSON("/api/tales/kids/", self.tales);}
$(document).ready(function () {
ko.applyBindings(new TalesViewModel());})
Html
<ul data-bind="foreach: tales">
<li>
<div>
<div>Masal Adı</div>
<span data-bind="text: $data.TaleName"></span>
</div>
<div>
<div>İçerik</div>
<span data-bind="text: $data.Content"></span>
</div>
<div>
<div>Ses Dosyası</div>
<span data-bind="text: $data.VoicePath"></span>
</div>
</li>
</ul>
I didn't take this properties in json result. Because it's have different tree.
Firstly, you should post two questions, will get you answers more easily. The first issue seems fairly generic, and googling for the error message has lots of leads, but we'd really have to see more code, know more variables (whats your db/driver?) to tell more.
As for your second issue, it looks like you're using $.getJSON incorrectly. I assume you want to load the JSON into the tales array, if so, you should try this instead
$.getJSON("/api/tales/kids/", function(data) {
self.tales(data.Tales);
});
It looks correct otherwise.