Refreshing Vuetify V-Calendar with new events hide the events in the "Month" view - vue.js

Currently developing an appointment-making application using a C# API in Vue.js with Vuetify, I encounter a behaviour with the component V-Calendar I can't comprehend. When originally feeding events to the calendar (appointments retrieved from a database by contacting the API), those events are correctly displayed as followed :
Original calendar loading
The query originally ignores cancelled appointments. However, I give the option to include them with a checkbox in the calendar header. Checking the box automatically refreshes the list of events through a watcher. When doing so, the calendar has a strange behaviour and does no longer display the events. This only occurs in the "Month" view, the "Day" and "Week" ones correctly display the data.
Result of refreshing the calendar
Here is the definition of my calendar (programming in french, translated in english the variables/methods for your easier understanding)
<v-calendar ref="calendar"
v-model="focus"
:event-color="getEventColor"
:events="events"
:first-interval="13"
:interval-count="22"
:interval-format="intervalFormat"
:interval-minutes="30"
:type="type"
:weekdays="weekDays"
color="primary"
event-more-text="Show more"
event-overlap-mode="column"
locale="fr"
#change="updateRange"
#click:event="showEvent"
#click:more="viewDay"
#click:date="viewDay">
<template #event="event">
<div v-if="event.eventParsed.input.idEtat === etats.annule"><s><i>{{
event.eventParsed.input.name
}}</i></s></div>
<div>{{ event.eventParsed.input.name }}</div>
</template>
</v-calendar>
The definition of the updateRange method (called once when the page is loaded in the created() hook)
async updateRange({start, end}) {
this.currentDateDebut = start.date;
this.currentDateFin = end.date;
await this.refreshCalendarData();
}
The definition of the refreshCalendar method
async refreshCalendarData() {
this.loading = true;
const events = []
//Récupération des rendez-vous
await this.getRendezVous(this.currentDateDebut, this.currentDateFin);
this.rendezVous = await this.$store.getters["rendezVous/getRendezVousData"];
for (let i = 0; i < this.rendezVous.length; i++) {
const calculImcPossible = (this.rendezVous[i].taille != null && this.rendezVous[i].taille > 0) &&
(this.rendezVous[i].poids != null && this.rendezVous[i].poids > 0);
const calculImc = calculImcPossible
? (Math.round(this.rendezVous[i].poids / ((this.rendezVous[i].taille / 100) * (this.rendezVous[i].taille / 100)) * 100) / 100).toFixed(2)
: null;
const libelleImc = this.getLibelleImc(calculImc);
events.push({
id: this.rendezVous[i].id,
idInstitution: this.rendezVous[i].idInstitution,
name: this.heureCourte(this.rendezVous[i].date) + " | Appointment",
start: new Date(this.rendezVous[i].date),
end: new Date(new Date(this.rendezVous[i].date).getTime() + 15 * 60000),
color: this.rendezVous[i].institution.color,
timed: true,
taille: this.rendezVous[i].taille != null && this.rendezVous[i].taille > 0
? this.rendezVous[i].taille + "cm"
: "indéfinie",
poids: this.rendezVous[i].poids != null && this.rendezVous[i].poids > 0
? this.rendezVous[i].poids + "kg"
: "indéfini",
sexe: this.rendezVous[i].patient.sexe,
imc: calculImc != null ? (calculImc + " (" + libelleImc + ")") : "non-déterminé",
nom: this.rendezVous[i].patient.nom + " " + this.rendezVous[i].patient.prenom,
telephone: this.rendezVous[i].patient.telephone != null ? this.rendezVous[i].patient.telephone : "-",
email: this.rendezVous[i].patient.email != null ? this.rendezVous[i].patient.email : "-",
commentaire: this.rendezVous[i].commentaire,
regime: this.rendezVous[i].regime,
hospitalisation: this.rendezVous[i].hospitalisation,
contagieux: this.rendezVous[i].contagieux,
incontinent: this.rendezVous[i].incontinent,
naissance: this.dateCourte(this.rendezVous[i].patient.naissance),
diabete: this.rendezVous[i].diabete.type,
examen: this.rendezVous[i].examen.nom,
idEtat: this.rendezVous[i].idEtat,
idPatient: this.rendezVous[i].idPatient,
typeEvent: "rendez-vous",
editable: this.rendezVous[i].editable
});
}
}
And finally, the definition of the watcher showCancalledAppointments
async showCancelledAppointments() {
await this.refreshCalendarData();
}
Do you have any idea why this behaviour is displayed by the calendar ? Thank you for your time and help.

Updating the solution with the command 'npm update' fixed the problem. The latest version of Vuetify seems to solve the issue

Related

[Vue warn]: Invalid prop: custom validator check failed for prop "colspan" in bootstrapvue

I am using BootstrapVue in my Vuejs project, I face a weired issue "Invalid prop" with b-table-simple componentinb-thead table helper I bind colspan with array length which always gives a number, and it works fine but it generates console warning message:
[Vue warn]: Invalid prop: custom validator check failed for prop "colspan".
found in
---> <BTh>
<BTr>
<BThead>
<BTableSimple>
<NationalTrends> at resources/js/components/trends/NationalTrends.vue
<Trends> at resources/js/components/trends/Trends.vue
<Root>
When I put number (4 or any other number) it works fine without generating the warning in the console.
Below is my code:
<template>
<div>
<b-table-simple hover small caption-top responsive striped>
<caption>Commodity Trends</caption>
<b-thead head-variant="light">
<b-tr>
<b-th>Commodity</b-th>
<b-th>Current Month</b-th>
<b-th :colspan="selected_periods.length">Previous Period</b-th>
<b-th :colspan="selected_periods.length">% Change From the Previous Period</b-th>
<b-th :colspan="selected_periods.length" class="text-center">Direction of Change</b-th>
</b-tr>
</div>
</template>
Please help, I spent one hour trying to figure out whats the problem but no luck......
Try to use like this:
:colspan="selected_periods.length > 0 ? selected_periods.length : 1"
Please check selected_periods.length against that custom validator (see bootstrap-vue source)
const digitsRx = /^\d+$/
// Parse a rowspan or colspan into a digit (or null if < 1 or NaN)
const parseSpan = val => {
val = parseInt(val, 10)
return digitsRx.test(String(val)) && val > 0 ? val : null
}
/* istanbul ignore next */
const spanValidator = val => isUndefinedOrNull(val) || parseSpan(val) > 0
export const isUndefined = val => val === undefined
export const isNull = val => val === null
export const isUndefinedOrNull = val => isUndefined(val) || isNull(val)
I managed to remove the warning by adding a default value if null (which will not happen in my code) as below:
<b-th :colspan="selected_periods.length || 4">Previous Period</b-th>
<b-th :colspan="selected_periods.length || 4">% Change From the Previous Period</b-th>
<b-th :colspan="selected_periods.length || 4" class="text-center">Direction of Change</b-th>

Angular Animations - Dynamic and Responsive translations

I have a component that is usually dormant (by which I simply mean it is of little interest to the user), but in a certain state this component becomes 'activated' and I want to put it in the exact center of the screen and enlarge it to grab the user's attention.
There are several of these components in the dormant state, but only ever 1 activated. The dormant components could be anywhere on the screen, so I wanted a solution that would translate the component from wherever it was originally to the middle of the screen while activated, and then return it back to its original dormant position when done.
Attempting to do this:
template:
<div #myElement [#isActivated]="activated">
Hello Stack Overflow
<button (click)="activated = activated === 'activated' ? 'dormant' : 'activated">
Toggle
</button>
</div>
typescript:
#Component({
// ...
animations: [
trigger('isActivated', [
state('dormant', style($transitionToActivated)),
state('activated', style({
transform: 'translateX(0%) translateY(0%) scale(1)'
})),
transition('dormant => activated', animate('1000ms ease')),
transition('activated => dormant', animate('1000ms ease'))
])
]
})
export class MyComponent implements OnInit {
#ViewChild('myElement') myElement: ElementRef;
activated = 'dormant';
transitionToActivated: any;
ngOnInit() {
let rect = this.myElement.nativeElement.getBoundingClinetRect();
this.transitionToActivated = {
transform: ''translateX(' + ((window.screen.width / 2) - (rect.right + rect.left) / 2) + ') translateY(' +
((window.screen.height / 2) - (rect.top + rect.bottom) / 2) + ') scale(1.5)'
}
}
}
My syntax here is off: the $transitionToActivated inside of the Component decorator is invalid. Is it possible to this kind of responsive animations with Angular Animations? Or will I need to look into a pure CSS solution?
[here's a plunker of what I'm trying... currently my attempt to put it in the exact center is commented out, and just some static animation instructions]
I figured out a couple things.
First, above I'm using window.screen for width and height of the 'screen.' This is actually giving me the resolution of the monitor (resizing the window doesn't affect it). I wanted document.documentElement to get the size of the viewport.
Second, I solved the issue of dynamic animations by using the AnimationPlayer to define the animations programmatically [rather than defining them in the Component decorator as I was trying to above].
I'm still curious as to whether the animations can be dynamically changed via the animation property inside the component decorator... I expect there must be a way, but I've been rather frustrated by the hand-wavy-ness of the Angular animations API and still can't figure it out.
Also, my solution acts funky when the viewport size is changed while in the 'activated state' (doesn't respond to resizing [as would be expected] and jumps at the start of its 'return' animation to the new middle of the viewport [again as expected].
Here's code and plunker to my solution:
export class App implements OnInit {
#ViewChild('myElement') myElement: ElementRef;
activated: BehaviorSubject<string> = new BehaviorSubject<string>('dormant');
transitionToActivated: any;
player: AnimationPlayer;
factory: any;
constructor(private builder: AnimationBuilder) {}
ngOnInit() {
console.log('viewport width: ' + document.documentElement.clientWidth);
console.log('viewport height: ' + document.documentElement.clientHeight);
let rect = this.myElement.nativeElement.getBoundingClientRect();
console.log('rect right: ' + rect.right);
console.log('rect left: ' + rect.left);
this.transitionToActivated = 'translateX(' + ((document.documentElement.clientWidth / 2) -
(rect.right + rect.left) / 2) + 'px) translateY(' +
((document.documentElement.clientHeight / 2) - (rect.top + rect.bottom) / 2) +
'px) scale(1)';
this.activated.subscribe(newValue => {
this.transitionToActivated = 'translateX(' + ((document.documentElement.clientWidth / 2) -
(rect.right + rect.left) / 2) + 'px) translateY(' +
((document.documentElement.clientHeight / 2) - (rect.top + rect.bottom) / 2) +
'px) scale(1)';
console.log(this.transitionToActivated);
if(newValue === 'activated'){
this.factory = this.builder.build([
style({ transform: 'translateX(0) translateY(0) scale(1)' }),
animate(
'1000ms',
style({ transform: this.transitionToActivated })
)
]);
this.player = this.factory.create(this.myElement.nativeElement, {});
this.player.play()
} else if(newValue === 'dormant'){
this.factory = this.builder.build([
style({ transform: this.transitionToActivated })
animate(
'1000ms',
style({ transform: 'translateX(0) translateY(0) scale(1)' }),
)
]);
this.player = this.factory.create(this.myElement.nativeElement, {});
this.player.play()
}
})
}
}

Using document.getElementsByClassName in Testcafe

I have a menu that always has the same structure, but the IDs can change from one installation to another. the only thing that stays the same is the heading (in my case "Plugins"). I call the document.getElementsByClassName function with a Selector inside my test:
var slides = Selector(() =>{
return document.getElementsByClassName("c-p-header-text");
});
Every heading of an menu element has the c-p-header-text class. Here is what a menu heading element looks like:
<div id="ext-comp-1002" class="c-p c-tree c-p-collapsed" style="width: auto;">
<div class="c-p-header c-unselectable c-accordion-hd" id="ext-gen135" style="cursor: pointer;">
<div class="c-tool c-tool-toggle" id="ext-gen140"> </div>
<img src="/backEnd/images/s.gif" class="c-p-inline-icon order"><span class="c-p-header-text" id="ext-gen150">Plugins</span>
</div>
It would be easy to use await t.click("#ext-gen150") but it is not safe that it is always this id.
here is what i tried:
await t
.click('#sites__db');
var slides = Selector(() =>{
return document.getElementsByClassName("c-p-header-text");
});
console.log("[DEBUG]" + slides);
console.log("[DEBUG] found " + slides.length + " elements");
for(var i = 0; i < slides.length; i++)
{
var txtOfCurrElem = slides.item(i).innerText;
console.log("[DEBUG "+ i +"] Text: " + txtOfCurrElem);
}
Running this test give me the following output:
[DEBUG]function __$$clientFunction$$() {
var testRun = builder.getBoundTestRun() || _testRunTracker2.default.resolveContextTestRun();
var callsite = (0, _getCallsite.getCallsiteForMethod)(builder.callsiteNames.execution);
var args = [];
// OPTIMIZATION: don't leak `arguments` object.
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}return builder._executeCommand(args, testRun, callsite);
}
[DEBUG] found 0 elements
The plan is to find the element (with the heading "Plugins") and then click on it when the test continuous.
You don't have to use document.getElementsByClassName in this case. You can just use CSS class selector instead:
var slides = Selector('.c-p-header-text');
You should use the count property when dealing with an array of Selectors. docs. Also, element properties, like exists, count, and DOM node state properties are Promisified, so when you use them not in t.expect, you should use the await keyword:
var count = await slides.length;
console.log("[DEBUG] found " + count + " elements");
for(var i = 0; i < count; i++)
{
var txtOfCurrElem = await slides.nth(i).innerText;
console.log("[DEBUG "+ i +"] Text: " + txtOfCurrElem);
}
I found a simple answer to my question. I use the .withText option to click on the Plugins element:
.click(Selector('span').withText("Plugins"))
Since this name is also unique, it is always the correct element that gets clicked. I do not know if it would have worked with the solution from #AndreyBelym if my site is not an extJS web application.

Foundation 6 slider: range stating from negative values

I wander if in foundation 6 sliders, it is possible to allow negative values e.g. swinging from -50 to 50.
Currently I have a slider in [0 100]:
<div class="row">
<div class="small-4 large-4 columns">
<label>Audio Volume</label>
</div>
<div class="small-6 large-6 columns">
<div class="slider" id="slidervol" data-slider data-end="100" display_selector: "#slidervol">
<span class="slider-handle" data-slider-handle role="slider" tabindex="1" aria-controls="sliderVolOutput"></span>
<span class="slider-fill" data-slider-fill></span>
</div>
</div>
<div class="small-2 large-2 columns">
<input name="AudioVolTxtbox" type="number" style="width: 4em;" tabindex="2" id="sliderVolOutput">
</div>
</div>
You can set a negative start value, but the behaviour is unpredictable when you do so. If you want to make use of negative values, you'll need logic to update the value in #sliderVolOutput after the handle has been moved.
The moved.zf.slider event is triggered every time the handle is moved and you can use that fact to update the textbox value. This event is fired quite a few times, so you'll need to add additional code to get rid of the flickering (if it's bothersome).
I've provided some basic code that should get you started. If you have any questions, please let me know.
var target = document.getElementById("slidervol");
var options = {
"start": 0,
"end": 100,
"decimal": 0
};
var elem = new Foundation.Slider($(target), options);
var offset = 50;
$(target).on('moved.zf.slider', function() {
$('#sliderVolOutput').val(Number($('.slider-handle').attr('aria-valuenow')) - offset);
});
Another approach would be to use the mousemove.zf.slider event. This gets rid of the flicker, but the textbox value is only updated once you've stopped manipulating the slider:
$(target).on('mousemove.zf.slider', function() {
$('#sliderVolOutput').val(Number($('.slider-handle').attr('aria-valuenow')) - offset);
});
UPDATE:
In response to your additional query, I've had time to implement the required functionality (editing the value in the text box causing the slider to update) using a hidden control.
The slider-handle now targets the hidden control (aria-controls), which will always contain a positive value. The text box will contain the negative (computed) value. This is what the updated html looks like for the slider-handle:
<span class="slider-handle" data-slider-handle role="slider" tabindex="1" aria-controls="sliderVolOutputHidden"></span>
And this is the additional hidden input I've used:
<input type="hidden" id="sliderVolOutputHidden" value="0">
I've also added an input event for #sliderVolOutput that updates the value of the hidden input and triggers the change event. The change event is important, as without it, the handle will not update:
$('#sliderVolOutput').on('input', function() {
$('#sliderVolOutputHidden').val(Number($('#sliderVolOutput').val()) + offset);
$('#sliderVolOutputHidden').trigger('change');
});
Fiddle Demo
I get quite a result patching as follows foundation.js.
I can change values smoothly with the slider (with no flickering) but I can not decrement the textbox (aria-controls) below 0 since he event handler does not fire.
## -6953,13 +6953,14 ##
'id': id,
'max': this.options.end,
'min': this.options.start,
+ 'offset': this.options.offset,
'step': this.options.step
});
this.handles.eq(idx).attr({
'role': 'slider',
'aria-controls': id,
- 'aria-valuemax': this.options.end,
- 'aria-valuemin': this.options.start,
+ 'aria-valuemax': this.options.end + this.options.offset,
+ 'aria-valuemin': this.options.start + this.options.offset,
'aria-valuenow': idx === 0 ? this.options.initialStart : this.options.initialEnd,
'aria-orientation': this.options.vertical ? 'vertical' : 'horizontal',
'tabindex': 0
## -6978,8 +6979,8 ##
key: '_setValues',
value: function _setValues($handle, val) {
var idx = this.options.doubleSided ? this.handles.index($handle) : 0;
- this.inputs.eq(idx).val(val);
- $handle.attr('aria-valuenow', val);
+ this.inputs.eq(idx).val(val+this.options.offset);
+ $handle.attr('aria-valuenow', val+this.options.offset);
}
/**
## -7033,7 +7034,8 ##
} else {
//change event on input
value = this._adjustValue(null, val);
- hasVal = true;
+ value = value - this.options.offset;
+ hasVal = true;
}
this._setHandlePos($handle, value, hasVal);
## -7286,7 +7288,13 ##
* #option
* #example false
*/
- invertVertical: false
+ invertVertical: false,
+ /**
+ *
+ * #option
+ * #example 0
+ */
+ offset: 0
};
function percent(frac, num) {
Then, for instance I want to change my parameter "Audio Volume" from -24 to 24 so in js:
// Audio Volume
vartxt = GetParameter("AudioVolume") // get the value in some way
tval = parseFloat(vartxt);
document.DeviceConfig.AudioVolTxtbox.value = tval - 24; //change the textbox
var target = document.getElementById("slidervol");
var options = {
"start": 0,
"end": 48,
"decimal": 0,
"step": 1,
"offset": -24,
"initialStart": tval
};
var elem = new Foundation.Slider($(target), options);
At the moment the only problem I get is that I have to configure the input box as 'text', since if I set it as 'number' the spinner does not allow to go below the 0.

How can I read Variables from data pool with Selenium IDE?

I am using Selenium IDE to test a web based HR/SW system.
There is a screen that used to enter vacation for employees.
I am having nearly 3000 employee.
I built a test case that enter vacations for one employee using variables.
How can I repeat the test case for all 3000 employees without creating the test case 3000 times. It will take an impossible effort to do that. Note: Each employee is having different vacation data (Type, start date, End date)
Is there any way that I can use a file (Excel,....) that variable can use to read its data from?
Is there any solution for my case???
I will be very very grateful I any one could help me.
Thank you.
You could use an XML file as an input.
1) At first you have to add following user extensions:
sideflow.js - (http://51elliot.blogspot.com/2008/02/selenium-ide-goto.html - additionally this article explains how to add user extension files)
datadriven.js
include.js
At the moment I can't find links where I took the last two, therefore I will give their code in the end of my post. Code is taken from my working directory. You just put the code to correspondent files, then add files to SelemiunIDE user extension and use them.
2) Create an XML file test_data.xml:
<testdata>
<test employee="1" type="1" startDate="01.01.2013" endDate="01.02.2013" />
<test employee="2" type="1" startDate="01.02.2013" endDate="01.03.2013" />
<test employee="3" type="1" startDate="01.03.2013" endDate="01.04.2013" />
...
</testdata>
3) In your test case use code like this:
${DataPath} - full path to a directory with XML-files
<!--BEGIN LOOP-->
<tr>
<td>loadTestData</td>
<td>file://${DataDir}/test_data.xml</td>
<td></td>
</tr>
<tr>
<td>while</td>
<td>!testdata.EOF()</td>
<td></td>
</tr>
<tr>
<td>nextTestData</td>
<td></td>
<td></td>
</tr>
<tr>
<td>echo</td>
<td>employee=${employee} type=${type} ...</td>
<td></td>
</tr>
...
<!--END LOOP-->
<tr>
<td>endWhile</td>
<td></td>
<td></td>
</tr>
Used user extensions:
include.js
/**
* Original Developer: Jerry Qian(qqqiansjtucs#hotmail.com)
* Modified By: John Witchel (jwitchel#colevalleygroup.com)
* include extension for Selenium-IDE edition
* refer to includeCommand_2.1.3 for Selenium-Core edition
* #version 1.3
*
*/
function IDEIncludeCommand() {}
IDEIncludeCommand.LOG_PREFIX = "IDEIncludeCommand: ";
IDEIncludeCommand.BEGIN_TEMPLATE = "begin$Template$";
IDEIncludeCommand.END_TEMPLATE = "end$Template$";
IDEIncludeCommand.VERSION = "1.1";
IDEIncludeCommand.prototype.prepareTestCaseAsText = function(responseAsText, paramsArray) {
/**
* Prepare the HTML to be included in as text into the current testcase-HTML
* Strip all but the testrows (tr)
* Stripped will be:
* - whitespace (also new lines and tabs, so be careful wirt parameters relying on this),
* - comments (xml comments)
* Replace variable according to include-parameters
* note: the include-variables are replaced literally. selenium does it at execution time
* also note: all selenium-variables are available to the included commands, so mostly no include-parameters are necessary
*
* #param responseAsText table to be included as text (string)
* #return testRows array of tr elements (as string!) containing the commands to be included
*
* TODO:
* - selenium already can handle testcase-html. use selenium methods or functions instead
* - find better name for requester
*/
// removing new lines, carret return and tabs from response in order to work with regexp
var pageText = responseAsText.replace(/\r|\n|\t/g,"");
// remove comments
// begin comment, not a dash or if it's a dash it may not be followed by -> repeated, end comment
pageText = pageText.replace(/<!--(?:[^-]|-(?!->))*-->/g,"");
// find the content of the test table = <[spaces]table[char but not >]>....< /[spaces]table[chars but not >]>
var testText = pageText.match(/<\s*table[^>]*>(.*)<\/\s*table[^>]*>/i)[1];
// Replace <td></td> with <td> </td> for iE - credits Chris Astall
// rz: somehow in my IE 7 this is not needed but is not bad as well
testText = testText.replace(/<\s*td[^>]*>\s*<\s*\/td[^>]*>/ig,"<td></td>");// jq: no space
// replace vars with their values in testText
for ( var k = 0 ; k < paramsArray.length ; k++ ) {
var pair = paramsArray[k];
testText = testText.replace(pair[0],pair[1]);
}
// removes all < /tr>
// in order to split on < tr>
testText = testText.replace(/<\/\s*tr[^>]*>/ig,"");
// split on <tr>
var testRows = testText.split(/<\s*tr[^>]*>/i);
return testRows;
};
IDEIncludeCommand.prototype.getIncludeDocumentBySynchronRequest = function(includeUrl) {
/**
* Prepare and do the XMLHttp Request synchronous as selenium should not continue execution meanwhile
*
* note: the XMLHttp requester is returned (instead of e.g. its text) to let the caller decide to use xml or text
*
* selenium-dependency: uses extended String from htmlutils
*
* TODO use Ajax from prototype like this:
* var sjaxRequest = new Ajax.Request(url, {asynchronous:false});
* there is discussion about getting rid of prototype.js in developer forum.
* the ajax impl in xmlutils.js is not active by default in 0.8.2
*
* #param includeUrl URI to the include-document (document has to be from the same domain)
* #return XMLHttp requester after receiving the response
*/
var url = this.prepareUrl(includeUrl);
// the xml http requester to fetch the page to include
var requester = this.newXMLHttpRequest();
if (!requester) {
throw new Error("XMLHttp requester object not initialized");
}
requester.open("GET", url, false); // synchron mode ! (we don't want selenium to go ahead)
try {
requester.send(null);
} catch(e) {
throw new Error("Error while fetching url '" + url + "' details: " + e);
}
if ( requester.status != 200 && requester.status !== 0 ) {
throw new Error("Error while fetching " + url + " server response has status = " + requester.status + ", " + requester.statusText );
}
return requester;
};
IDEIncludeCommand.prototype.prepareUrl = function(includeUrl) {
/** Construct absolute URL to get include document
* using selenium-core handling of urls (see absolutify in htmlutils.js)
*/
var prepareUrl;
// htmlSuite mode of SRC? TODO is there a better way to decide whether in SRC mode?
if (window.location.href.indexOf("selenium-server") >= 0) {
LOG.debug(IDEIncludeCommand.LOG_PREFIX + "we seem to run in SRC, do we?");
preparedUrl = absolutify(includeUrl, htmlTestRunner.controlPanel.getTestSuiteName());
} else {
preparedUrl = absolutify(includeUrl, selenium.browserbot.baseUrl);
}
LOG.debug(IDEIncludeCommand.LOG_PREFIX + "using url to get include '" + preparedUrl + "'");
return preparedUrl;
};
IDEIncludeCommand.prototype.newXMLHttpRequest = function() {
// TODO should be replaced by impl. in prototype.js or xmlextras.js
// but: there is discussion of getting rid of prototype.js
// and: currently xmlextras.js is not activated in testrunner of 0.8.2 release
var requester = 0;
var exception = '';
// see http://developer.apple.com/internet/webcontent/xmlhttpreq.html
// changed order of native and activeX to get it working with native
// xmlhttp in IE 7. credits dhwang
try {
// for IE/ActiveX
if(window.ActiveXObject) {
try {
requester = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
requester = new ActiveXObject("Microsoft.XMLHTTP");
}
}
// Native XMLHttp
else if(window.XMLHttpRequest) {
requester = new XMLHttpRequest();
}
}
catch(e) {
throw new Error("Your browser has to support XMLHttpRequest in order to use include \n" + e);
}
return requester;
};
IDEIncludeCommand.prototype.splitParamStrIntoVariables = function(paramString) {
/**
* Split include Parameters-String into an 2-dim array containing Variable-Name and -Value
*
* selenium-dependency: uses extended String from htmlutils
*
* TODO: write jsunit tests - this could be easy (if there were not the new RegExp)
*
* #param includeParameters string the parameters from include call
* #return new 2-dim Array containing regExpName (to find a matching variablename) and value to be substituted for
*/
var newParamsArray = new Array();
// paramString shall contains a list of var_name=value
var paramListPattern = /([^=,]+=[^=,]*,)*([^=,]+=[^=,]*)/;
if (! paramString || paramString === "") {
return newParamsArray;
} else if (paramString.match( paramListPattern )) {
// parse parameters to fill newParamsArray
var pairs = paramString.split(",");
for ( var i = 0 ; i < pairs.length ; i++ ) {
var pair = pairs[i];
var nameValue = pair.split("=");
//rz: use String.trim from htmlutils.js of selenium to get rid of whitespace in variable-name(s)
var trimmedNameValue = new String(nameValue[0]).trim();
// the pattern to substitute is ${var_name}
var regExpName = new RegExp("\\$\\{" + trimmedNameValue + "\\}", "g");
if (nameValue.length < 3) {
newParamsArray.push(new Array(regExpName,nameValue[1]));
} else {
var varValue = new String(nameValue[1]);
for (var j = 2; j < nameValue.length; j++) {
varValue=varValue.concat("="+nameValue[j]);
}
newParamsArray.push(new Array(regExpName,varValue));
}
}
} else {
throw new Error("Bad format for parameters list : '" + paramString + "'");
}
return newParamsArray;
};
IDEIncludeCommand.prototype.doInclude = function(locator, paramString) {
// Rewrite logic for Selenium IDE by Jerry Qian
var currentSelHtmlTestcase = testCase;
var includeCmdRow = testCase.debugContext.currentCommand();
if (!includeCmdRow) {
throw new Error("IDEIncludeCommand: failed to find include-row in source testtable");
}
var paramsArray = this.splitParamStrIntoVariables(paramString);
var inclDoc = this.getIncludeDocumentBySynchronRequest(locator);
// Get an array of commands from the include text with all whitespace stripped
var includedTestCaseHtml = this.prepareTestCaseAsText(inclDoc.responseText, paramsArray);
this.injectIncludeTestCommands(locator,includeCmdRow,includedTestCaseHtml);
};
IDEIncludeCommand.prototype.injectIncludeTestCommands = function(locator,includeCmdRow, testRows) {
// Rewrite logic for Selenium IDE by Jerry Qian
var newCommands = new Array();
// skip first element as it is empty or <tbody>
for (var i = 1 ; i < testRows.length; i++) {
if(i == 1){// add BEGIN-END block
var beginCommand = new Command(IDEIncludeCommand.BEGIN_TEMPLATE,locator,"");
newCommands.push(beginCommand);
}
var newText = testRows[i];
if(newText.match(/<\s*td.*colspan=.*>(.*)<\/\s*td[^>]*>/i)){//delete comment step
continue;
}
// removes all < /td>
// in order to split on <td>
newText = newText.replace(/<\/\s*td[^>]*>\s*<\/\s*tbody[^>]*>/ig,""); //remove </tbody>first
newText = newText.replace(/<\/\s*td[^>]*>/ig,"");
var newCols = newText.split(/<\s*td[^>]*>/i);
var new_cmd,new_target,new_value;
for (var j = 1 ; j < newCols.length; j++) {//skip 0
if(j == 1) {
new_cmd = newCols[j].replace(/\s/g,"");//trim \s
}else if(j == 2) {
new_target = newCols[j].replace(/\s+$/g,"");//trim end \s
}else if(j == 3) {
new_value = newCols[j].replace(/\s+$/g,"");//trim end \s
}
}
var newCommand = new Command(new_cmd,new_target,new_value);
newCommands.push(newCommand); //correct all steps
}
var endCommand = new Command(IDEIncludeCommand.END_TEMPLATE,locator,"");
newCommands.push(endCommand);//add BEGIN-END block
var cmsBefore = testCase.commands.slice(0,testCase.debugContext.debugIndex + 1);
var cmdsBehind = testCase.commands.slice(testCase.debugContext.debugIndex + 1, testCase.commands.length);
testCase.commands = cmsBefore.concat(newCommands).concat(cmdsBehind);//Injection
// Don't inject if it appears the injection has already been done
// (i.e., if the next command is the BEGIN).
if (testCase.commands.length <= testCase.debugContext.debugIndex+1
|| beginCommand.toString() != testCase.commands[testCase.debugContext.debugIndex+1].toString())
{
// The include command cannot be the last command in the TestCase, or else
// the de-injection code in doEnd$Template$ will cause an error. So we'll
// add a simple echo if it is the last.
if (testCase.commands.length == testCase.debugContext.debugIndex+1)
{
// Using concat instead of push so that we don't trigger the TestCase's set-modified flag.
testCase.commands = testCase.commands.concat(new Command("echo", "The include command cannot be the last line in a TestCase, so this command was added. It can be left in place or removed, as desired.", "The include command cannot be the last line in a TestCase, so this command was added. It can be left in place or removed, as desired."));
}
// This is original code.
var cmsBefore = testCase.commands.slice(0,testCase.debugContext.debugIndex + 1);
var cmdsBehind = testCase.commands.slice(testCase.debugContext.debugIndex + 1, testCase.commands.length);
testCase.commands = cmsBefore.concat(newCommands).concat(cmdsBehind);//Injection
}
};
Selenium.prototype.doInclude = function(locator, paramString) {
LOG.debug(IDEIncludeCommand.LOG_PREFIX + "Version " + IDEIncludeCommand.VERSION);
var ideIncludeCommand = new IDEIncludeCommand();
ideIncludeCommand.doInclude(locator, paramString);
// If goto scripts exist then reindex the labels. goto_sel_ide.js creates an array of labels when the
// script is initialized but an included file's labels are not part of that initial read, so this function
// re-initializes that array with the included files labels (if any). If goto_sel.ide.js is not included
// it's ignored.
try {
this.initialiseLabels();
}
catch (e) {
LOG.debug("Goto Script not used.");
}
};
// Array to hold the starting position of the Begin$Template$ marker. Pushing and popping the position onto an array
// allows us to correctly handle nested includes during clean up.
var beginTemplateIndex = new Array();
// Mark the beginning of the include
Selenium.prototype.doBegin$Template$ = function(locator){
LOG.info("Begin Template " + locator + " at position " + testCase.debugContext.debugIndex);
// Add the current position to the tail of the beginTemplateIndex
beginTemplateIndex.push(testCase.debugContext.debugIndex);
};
// Clean up everything between the closest Begin$Template$ and this $End$Template$, and pop the position off the array.
Selenium.prototype.doEnd$Template$ = function(locator){
// Remove the last Begin$Template$ from the tail of the beginTemplateIndex
var currentBeginTemplateIndex = beginTemplateIndex.pop();
LOG.info("End Template " + locator + " at position " + currentBeginTemplateIndex);
// Delete the commands that we injected in injectIncludeTestCommands.
testCase.commands =
testCase.commands.slice(0,currentBeginTemplateIndex).concat(
testCase.commands.slice(testCase.debugContext.debugIndex+1, testCase.commands.length));
// Set the current command to the next one after the injected block.
testCase.debugContext.debugIndex = currentBeginTemplateIndex-1;
//Must refresh to syncup UI
editor.view.refresh();
};
datadriven.js
/************************************ DATADRIVEN EXTENSION START ********************************************/
/*
NAME:
datadriven
Licensed under Apache License v2
http://www.apache.org/licenses/LICENSE-2.0
PURPOSE:
Basic data driven testing.
Full documentation at http://wiki.openqa.org/display/SEL/datadriven
EXAMPLE USE:
The structure of your data driven test case will be;
-------------------------------------------
COMMAND |TARGET |VALUE
-------------------------------------------
loadTestData |<file path> |
while |!testdata.EOF() |
testcommand1 | |
testcommand...| |
testcommandn | |
endWhile | |
-------------------------------------------
AUTHOR:
Jonathan McBrien
jonathan#mcbrien.org
2008-10-22: v0.1: Initial version.
2009-01-16: v0.2: Updated for Firefox 3.
xmlTestData.prototype.load now uses the include extension's getIncludeDocumentBySynchronRequest method for better portability.
(Why reinvent the wheel? :) - with appreciation to the include extension's authors.)
*/
XML.serialize = function(node) {
if (typeof XMLSerializer != "undefined")
return (new XMLSerializer()).serializeToString(node) ;
else if (node.xml) return node.xml;
else throw "XML.serialize is not supported or can't serialize " + node;
}
function xmlTestData() {
this.xmlDoc = null;
this.testdata = null;
this.index = null;
}
xmlTestData.prototype.load = function(xmlloc) {
loader = new IDEIncludeCommand();
var xmlHttpReq = loader.getIncludeDocumentBySynchronRequest(xmlloc);
this.xmlDoc = xmlHttpReq.responseXML;
this.index = 0;
this.testdata = this.xmlDoc.getElementsByTagName("test");
if (this.testdata == null || this.testdata.length == 0) {
throw new Error("Test data couldn't be loaded or test data was empty.");
}
}
xmlTestData.prototype.EOF = function() {
if (this.index != null && this.index < this.testdata.length) return false;
return true;
}
xmlTestData.prototype.more = function() {
return !this.EOF();
}
xmlTestData.prototype.next = function() {
if (this.EOF()) {
LOG.error("No test data.");
return;
}
LOG.info(XML.serialize(this.testdata[this.index])); // Log should anything go wrong while testing with this data.
if (this.testdata[this.index].attributes.length != this.testdata[0].attributes.length) {
LOG.error("Inconsistent attribute length in test data.");
return;
}
for (i=0; i<this.testdata[this.index].attributes.length; i++){
if (null == this.testdata[0].getAttribute(this.testdata[this.index].attributes[i].nodeName)) {
LOG.error("Inconsistent attribute names in test data.");
return;
}
selenium.doStore(this.testdata[this.index].attributes[i].nodeValue, this.testdata[this.index].attributes[i].nodeName);
}
this.index++;
}
Selenium.prototype.testdata = null;
Selenium.prototype.doLoadTestData = function(xmlloc) {
testdata = new xmlTestData();
testdata.load(xmlloc);
};
Selenium.prototype.doNextTestData = function() {
testdata.next();
};
/************************************ DATADRIVEN EXTENSION END **********************************************/
Current solution is a SelBlocks component which allows you to do cycles according to the dataset in XML
ForXML | XMLFileName.XML
... test case steps
EndForXML
The XML should have specific structure
<testdata>
<vars storedVariable1="xxxxx" storedVariable2="yyyyy" .. storedVariableN="zzzzz" />
.. other record(s)
</testdata>
Each stored variable vill be available in test case as ${storedVariableN}.
You can produce XML by MS Excel or LibreOffice using Formulas like this one and copy it to whole table:
="<vars "&
" "&$A$1&"="""&A2&""" "&
" "&$B$1&"="""&B2&""" "&
..
" "&$X$1&"="""&X2&""" "&
"/>")
XML can be easily copypasted after each change of the dataset.
Selblocks contains the while, datadriven, goto, loop and other extensions mentioned in previous answers. You can use other functionalities of the Selblocks as conditional jumps, conditions, catch-try blocks, functions, etc. See full reference here: http://refactoror.wikia.com/wiki/Selblocks_Reference
Beware with new Selenium 3 release and Sel Core absence it is not guaranteed, that tests with Selblock addon will work in the future versions of the firefox.
You can also check this very nice blog article:
http://seleniumworks.blogspot.com/2014/01/selenium-ide-data-driven.html
This gives an explanation on how to use the needed plugins and where to download them from. It worked perfectly for me.
This answer pretty much has the same approach as the one provided by #Yevgen Ulyanenkov as I used his answer in order to find the above article. But has some more googling to it that hopefully will be helpful to someone.
I think you need to use loop I don't see your code so just check this one for selenium-ide loop If you have any more problem if so comment my answer. I can't comment into your question because reputation is not enough so. If possible please add your code into your question.