Unable to branch my tests using a variable in Postman - testing

I have a collection with two folders, one for POSTs and one for GETs
At the collection level, I have set variables
And the following collection-level scripts to be run after every request:
requestLast = pm.variables.get("requestLast");
requestCurrent = pm.variables.get("requestCurrent");
statusGet = pm.variables.get("statusGet");
requestLast = requestCurrent;
requestCurrent = pm.request.name;
I want to always be keeping track of the previously run request, so I can return to it when necessary.
In the 'positivePosts' folder I have the following test script:
if(statusGet === 0) {
postman.setNextRequest("resultsPositive");
}
else {
statusGet = 0;
}
pm.variables.set("requestLast", requestLast);
pm.variables.set("requestCurrent", requestCurrent);
pm.variables.set("statusGet", statusGet);
The individual POST requests have no test scripts.
The results folder does not have any tests, but the resultsPositive GET has this test script:
var jsonData = JSON.parse(responseBody);
schema = pm.variables.get("schemaPositive");
tests["Valid Schema"] = tv4.validate(jsonData, schema);
tests["Status code is 200"] = responseCode.code === 200;
statusGet = 1;
postman.setNextRequest(requestLast);
pm.variables.set("requestLast", requestLast);
pm.variables.set("requestCurrent", requestCurrent);
pm.variables.set("statusGet", statusGet);
There are no pre-request scripts anywhere in the collection.
When running the collection, I would expect this order:
postRich
resultsPositive
postAllProperties
resultsPositive
postMinimum
resultsPositive
However, what I actually see is:
postRich
postAllProperties
postPositive
I also don't understand why postPositive is not run after postRich.

Related

How can I create reliable flask-SQLAlchemy interactions with server-side-events?

I have a flask app that is functioning to expectations, and I am now trying to add a message notification section to my page. The difficulty I am having is that the database changes I am trying to rely upon do not seem to be updating in a timely fashion.
The html code is elementary:
<ul id="out" cols="85" rows="14">
</ul><br><br>
<script type="text/javascript">
var ul = document.getElementById("out");
var eventSource = new EventSource("/stream_game_channel");
eventSource.onmessage = function(e) {
ul.innerHTML += e.data + '<br>';
}
</script>
Here is the msg write code that the second user is executing. I know the code block is run because the redis trigger is properly invoked:
msg_join = Messages(game_id=game_id[0],
type="gameStart",
msg_from=current_user.username,
msg_to="Everyone",
message=f'{current_user.username} has requested to join.')
db.session.add(msg_join)
db.session.commit()
channel = str(game_id[0]).zfill(5) + 'startGame'
session['channel'] = channel
date_time = datetime.utcnow().strftime("%Y/%m/%d %H:%M:%S")
redisChannel.set(channel, date_time)
Here is the flask stream code, which is correctly triggered by a new redis time, but when I pull the list of messages, the new message the the second user has added is not yet accessible:
#games.route('/stream_game_channel')
def stream_game_channel():
#stream_with_context
def eventStream():
channel = session.get('channel')
game_id = int(left(channel, 5))
cnt = 0
while cnt < 1000:
print(f'cnt = 0 process running from: {current_user.username}')
time.sleep(1)
ntime = redisChannel.get(channel)
if cnt == 0:
msgs = db.session.query(Messages).filter(Messages.game_id == game_id)
msg_list = [i.message for i in msgs]
cnt += 1
ltime = ntime
lmsg_list = msg_list
for i in msg_list:
yield "data: {}\n\n".format(i)
elif ntime != ltime:
print(f'cnt > 0 process running from: {current_user.username}')
time.sleep(3)
msgs = db.session.query(Messages).filter(Messages.game_id == game_id)
msg_list = [i.message for i in msgs]
new_messages = # need to write this code still
ltime = ntime
cnt += 1
yield "data: {}\n\n".format(msg_list[len(msg_list)-len(lmsg_list)])
return Response(eventStream(), mimetype="text/event-stream")
The syntactic error that I am running into is that the msg_list is exactly the same length (i.e the pushed new message does not get written when i expect it to). Strangely, the second user's session appears to be accessing this information because its stream correctly reflects the addition.
I am using an Amazon RDS MySQL database.
The solution was to utilize a db.session.commit() before my db.session.query(Messages).filter(...) even where no writes were pending. This enabled an immediate read from a different user session, and my code commenced to react to the change in message list length properly.

IntelliJ IDEA LiveTemplate auto increment between usages

I am trying to make my life easier with Live Templates in intelliJ
I need to increment some param by 1 every-time I use the snippet.
So I tried to develop some groovyScript, and I am close, but my groovy capabilities keeps me back. the number is not incremented by 1, but incremented by 57 for some reason... (UTF-8?)
here is the script:
File file = new File("out.txt");
int code = Integer.parseInt(file.getText('UTF-8'));
code=code+1;
try{
if(_1){
code = Integer.parseInt(_1);
}
} catch(Exception e){}
file.text = code.toString();
return code
So whenever there's param passed to this script (with _1) the initial value is set, and otherwise simply incremented.
this script needs to be passed to the live template param with:
groovyScript("File file = new File(\"out.txt\");int code = Integer.parseInt(file.getText(\'UTF-8\'));code=code+1;String propName = \'_1\';if(this.hasProperty(propName) && this.\"$propName\"){code = Integer.parseInt(_1);};file.text =code.toString();return code", "<optional initial value>")

EPiServer 9 - Add block to new page programmatically

I have found some suggestions on how to add a block to a page, but can't get it to work the way I want, so perhaps someone can help out.
What I want to do is to have a scheduled job that reads through a file, creating new pages with a certain pagetype and in the new page adding some blocks to a content property. The blocks fields will be updated with data from the file that is read.
I have the following code in the scheduled job, but it fails at
repo.Save((IContent) newBlock, SaveAction.Publish);
giving the error
The page name must contain at least one visible character.
This is my code:
public override string Execute()
{
//Call OnStatusChanged to periodically notify progress of job for manually started jobs
OnStatusChanged(String.Format("Starting execution of {0}", this.GetType()));
//Create Person page
PageReference parent = PageReference.StartPage;
//IContentRepository contentRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
//IContentTypeRepository contentTypeRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentTypeRepository>();
//var repository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
//var slaegtPage = repository.GetDefault<SlaegtPage>(ContentReference.StartPage);
IContentRepository contentRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
IContentTypeRepository contentTypeRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentTypeRepository>();
SlaegtPage slaegtPage = contentRepository.GetDefault<SlaegtPage>(parent, contentTypeRepository.Load("SlaegtPage").ID);
if (slaegtPage.MainContentArea == null) {
slaegtPage.MainContentArea = new ContentArea();
}
slaegtPage.PageName = "001 Kim";
//Create block
var repo = ServiceLocator.Current.GetInstance<IContentRepository>();
var newBlock = repo.GetDefault<SlaegtPersonBlock1>(ContentReference.GlobalBlockFolder);
newBlock.PersonId = "001";
newBlock.PersonName = "Kim";
newBlock.PersonBirthdate = "01 jan 1901";
repo.Save((IContent) newBlock, SaveAction.Publish);
//Add block
slaegtPage.MainContentArea.Items.Add(new ContentAreaItem
{
ContentLink = ((IContent) newBlock).ContentLink
});
slaegtPage.URLSegment = UrlSegment.CreateUrlSegment(slaegtPage);
contentRepository.Save(slaegtPage, EPiServer.DataAccess.SaveAction.Publish);
_stopSignaled = true;
//For long running jobs periodically check if stop is signaled and if so stop execution
if (_stopSignaled) {
return "Stop of job was called";
}
return "Change to message that describes outcome of execution";
}
You can set the Name by
((IContent) newBlock).Name = "MyName";

Worklight call WL.Server.invokeHttp(input) in a loop

I am novice to Worklight.
I am trying to merge responses from multiple WL.Server.invokeHttp(input).
e.g.
call1: response1 = WL.Server.invokeHttp(input1)
lets say in response1 I get students(names) list loop for every student
call(n):
response(n) = WL.Server.invokeHttp(student) lets say response(n) I get
the score of student
Now I am trying to merge the score of every student in student list.
Adding code:
function getStudentsMarks() {
path = "/edu/students";
WL.Logger.info("path: "+path);
var input = {
method : 'get',
returnedContentType : 'json',
path : path
};
var response = WL.Server.invokeHttp(input);
var students = response.students;
for (var i = 0; i < students.length; i++) {
var student = students[i];
WL.Logger.info("student id: " + student.id);
resp = getStudentMarks("students/"+student.id);
students[i].marks = resp;
}
return response;
}
function getStudentMarks(path) {
path = "/edu/"+ path;
var input = {
method : 'get',
returnedContentType : 'json',
path : path
};
var response = WL.Server.invokeHttp(input);
return response;
}
Thanks in advance.
Your question is a bit too broad and does not contain any code.
Did you try anything yet?
It is important to remember that procedure code is written in JavaScript. So if you know how to do it in JavaScript, you should be able to do it in procedure code as well.
From what I understand, what you should do is create 1 adapter procedure. This procedure will have the different calls to the different HTTP backend requests. In JavaScript, write any merging logic that you need. At the end of the loop, return the processed data that you want.
Before you go deep into your example, maybe try with just 1 invocation, then try to merge 2. Once you are comfortable writing code, try your solution.
Note however that one HTTP adapter can only connect to 1 backend domain name. So if your example requires multiple domain names, your "mashup" adapter needs to call other adapters.
If all your HTTP requests point to the same domain name, then 1 adapter is enough.
I recommend reading this as well: https://www.ibm.com/developerworks/community/blogs/worklight/entry/handling_backend_responses_in_adapters

Get test outcome/result using TFS API

Using the TFS API, how can I get the outcome/result of a specific test case in a given test suite and plan?
With outcome/result I mean the value that tests are grouped by in MTM:
Passed, failed, active, in progress or blocked
This is how I do it.
To get passed and totalTests I use:
ITestRun run*
run.PassedTests and run.TotalTests
To see run state I use:
TestRunSTate.Aborted and TestRunState.InProgress
To see if the failed or is inconclusive I use:
TestOutcome.Failed or TestOutcome.Inconclusive
First I only used ITestRun to easy se results, but I see they lack any kind of "failed" there which I find very disturbing.
So to send the right numbers to my test report that is mailed to the product owner I do the following when talking to the tfs api:
var tfs = Connect(optionsModel.CollectionUri);
var tcm = GetService<ITestManagementService>(tfs);
var wis = GetService<WorkItemStore>(tfs);
_testProject = tcm.GetTeamProject(optionsModel.TeamProjectName);
var plan = _testProject.TestPlans.Find(optionsModel.PlanId);
if (plan == null)
throw new Exception("Could not find plan with that id.");
var run = plan.CreateTestRun(true);
var testSuite = _testProject.TestSuites.Find(optionsModel.SuiteId);
if (testSuite == null)
throw new Exception("Could not find suite with that id.");
AddTestCasesBySuite(testSuite, optionsModel.ConfigId, plan, run);
run.Title = optionsModel.Title;
run.Save();
var failedTests = run.QueryResultsByOutcome(TestOutcome.Failed).Count;
var inconclusiveTests = run.QueryResultsByOutcome(TestOutcome.Inconclusive).Count;
Hope this helps
optionsmodel is the information I take in from the user running the tsts
I was trying to do the same thing, but using the REST API.
Just in case it helps someone, I managed to do that obtaining the testpoints from the suite:
https://dev.azure.com/{organization}/{project}/_apis/testplan/Plans/{planId}/Suites/{suiteId}/TestPoint?api-version=5.1-preview.2
More info: https://learn.microsoft.com/en-us/rest/api/azure/devops/testplan/test%20point/get%20points%20list?view=azure-devops-rest-5.1
You can use ITestManagementService and TestPlan query to get the result of specific Test plan
var server = new Uri("http://servername:8080/tfs/collectionname");
var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(server);
var service = tfs.GetService<ITestManagementService>();
var testProject = service.GetTeamProject(teamProject);
var plans = testProject.TestPlans.Query("SELECT * FROM TestPlan").Where(tp => tp.Name == YOURTESTPLANNAME).FirstOrDefault();
ITestPlanCollection plans = tfsConnectedTeamProject.TestPlans.Query("Select * From TestPlan");
foreach (ITestPlan plan in plans)
{
if (plan.RootSuite != null && plan.RootSuite.Entries.Count > 0)
{
foreach (ITestSuiteEntry suiteEntry in plan.RootSuite.Entries)
{
var suite = suiteEntry.TestSuite as IStaticTestSuite;
if (suite != null)
{
ITestSuiteEntryCollection suiteentrys = suite.TestCases;
foreach (ITestSuiteEntry testcase in suiteentrys)
{
// Write code to get the test case
}
}
}
}
}
I hope this may help you.