Get test outcome/result using TFS API - tfs-sdk

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.

Related

HTTP request won't get data from API. Gamemaker Studio 1.4.9

I'm trying to figure out how to get information from a dictionary API in Gamemaker Studio 1.4.9
I'm lost since I can't figure out how to get around the API's server block. All my return shows is a blank result.
Step Event:
if(keyboard_check_pressed(vk_space)){
http_get("https://api.dictionaryapi.dev/api/v2/entries/en/test");
}
HTTP Event:
var requestResult = ds_map_find_value(async_load, "result");
var resultMap = json_decode(requestResult);
if(resultMap == -1)
{
show_message("Invalid result");
exit;
}
if(ds_map_exists(resultMap,"word")){
var name= ds_map_find_value(resultMap, "word");
show_message("The word name is "+name);
}
Maybe my formatting is wrong? It's supposed to say the word test in the show_message function, but again, all I get returned is a blank result.
Any help would be appreciated, thanks!
You can see through the debugger that the data is coming from the server. But your code does not correctly try to retrieve the Word.
https://imgur.com/a/icQSnnx
This code gets this word
show_debug_message("http received")
var requestResult = ds_map_find_value(async_load, "result");
var resultMap = json_decode(requestResult);
if(resultMap == -1)
{
show_message("Invalid result");
exit;
}
if(ds_map_exists(resultMap,"default")){
var defaultList = ds_map_find_value(resultMap, "default")
var Map = ds_list_find_value(defaultList, 0)
var name= ds_map_find_value(Map, "word");
show_message("The word name is "+name);
}

Unable to branch my tests using a variable in Postman

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.

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";

How to obtain the Hardware information of the computer using Test Complete

Right now I am working on the performance tests and I have come across the situation, where i need to obtain the hardware information of the computer on which tests are been performed. Is there any way to obtain the hardware information using JScript.
Thanks and Regards,
Guru...
** I have got the answer .....posting this as this might be useful for someone else ......**
function RAM_Information()
{
var SystemAttributes = GetObject("winmgmts:");
var RAMSize = 0;
var MemoryPackets = SystemAttributes.ExecQuery("SELECT Capacity FROM Win32_PhysicalMemory");
var enumItems = new Enumerator(MemoryPackets);
for ( ; !enumItems.atEnd(); enumItems.moveNext())
{
RAMSize += aqConvert.StrToFloat(enumItems.item().Capacity);
}
Log.Message("Total physical memory: " + VarToStr(RAMSize*0.000000001) + " GB");
return RAMSize*0.000000001;
}
function ProcessorInformation()
{
return Sys.CPU;
}

Google API for getting maximum number of licenses in a Google Apps domain

I have a Google Apps Script function used for setting up accounts for new employees in our Google Apps domain.
The first thing it does is makes calls to the Google Admin Settings API and retrieves the currentNumberOfUsers and maximumNumberOfUsers, so it can see if there are available seats (otherwise a subsequent step where the user is created using the Admin SDK Directory API would fail).
It's been working fine until recently when our domain had to migrate from Postini to Google Vault for email archiving.
Before the migration, when creating a Google Apps user using the Admin SDK Directory API, it would increment the currentNumberOfUsers by 1 and the new user account user would automatically have access to all Google Apps services.
Now after the migration, when creating a Google Apps user, they aren't automatically assigned a "license," so I modified my script to use the Enterprise License Manager API and now it assigns a "Google-Apps-For-Business" license. That works fine.
However, the currentNumberOfUsers is now different from the number of assigned licenses, and "Google-Apps-For-Business" is only one of several different types of licenses available.
I can get the current number of assigned "Google-Apps-For-Business" licenses by running this:
var currentXml = AdminLicenseManager.LicenseAssignments.listForProductAndSku('Google-Apps', 'Google-Apps-For-Business', 'domain.com', {maxResults: 1000});
var current = currentXml.items.toString().match(/\/sku\/Google-Apps-For-Business\/user\//g).length;
But the number that produces is different from currentNumberOfUsers.
All I really need to do now is get the maximum number of owned "Google-Apps-For-Business" licenses so the new employee setup script can determine whether there are any available.
I checked the API Reference documentation for the following APIs but...
Enterprise License Manager API → Doesn't have a method for getting the maximum or available number of licenses.
Google Admin Settings API → Doesn't deal with licenses, only "users."
Admin SDK Directory API User resource → Doesn't deal with licenses.
Google Apps Reseller API → This API seems to have what I need, but it's only for Reseller accounts.
I know I can program my new employee setup script to just have a try/catch seeing if it would be able to create the user and assign the license, and end the script execution gracefully if it can't, but that doesn't seem efficient.
Also, part of the old script was that if there were less than X seats available, it would email me a heads-up to order more. I can program a loop that attempts to repeatedly create dummy users and assign them licenses and count the number of times it can do that before it fails, then delete all the dummy users, but, once again, that's not efficient at all.
Any ideas?
Update 3/11/2020: Since the Admin Settings API had shut down a few years ago I've been using the Enterprise License Manager API to get the current number of used licenses, like this:
function getCurrentNumberOfUsedGoogleLicenses(skuId) {
var success = false, error = null, count = 0;
var adminEmail = 'admin#domain.com';
var gSuiteDomain = adminEmail.split('#')[1];
// for more information on the domain-wide delegation:
// https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
// the getDomainWideDelegationService() function uses this:
// https://github.com/gsuitedevs/apps-script-oauth2
var service = getDomainWideDelegationService('EnterpriseLicenseManager: ', 'https://www.googleapis.com/auth/apps.licensing', adminEmail);
if (skuId == 'Google-Apps-Unlimited') var productId = 'Google-Apps';
else return { success: success, error: "Unsupported skuId", count: count };
var requestBody = {};
requestBody.headers = {'Authorization': 'Bearer ' + service.getAccessToken()};
requestBody.method = "GET";
requestBody.muteHttpExceptions = false;
var data, pageToken, pageTokenString;
var maxAttempts = 5;
var currentAttempts = 0;
var pauseBetweenAttemptsSeconds = 3;
loopThroughPages:
do {
if (typeof pageToken === 'undefined') pageTokenString = "";
else pageTokenString = "&pageToken=" + encodeURIComponent(pageToken);
var url = 'https://www.googleapis.com/apps/licensing/v1/product/' + productId + '/sku/' + skuId + '/users?maxResults=1000&customerId=' + gSuiteDomain + pageTokenString;
try {
currentAttempts++;
var response = UrlFetchApp.fetch(url, requestBody);
var result = JSON.parse(response.getContentText());
if (result.items) {
var licenseAssignments = result.items;
var licenseAssignmentsString = '';
for (var i = 0; i < licenseAssignments.length; i++) {
licenseAssignmentsString += JSON.stringify(licenseAssignments[i]);
}
if (skuId == 'Google-Apps-Unlimited') count += licenseAssignmentsString.match(/\/sku\/Google-Apps-Unlimited\/user\//g).length;
currentAttempts = 0; // reset currentAttempts before the next page
}
} catch(e) {
error = "Error: " + e.message;
if (currentAttempts >= maxAttempts) {
error = 'Exceeded ' + maxAttempts + ' attempts to get license count: ' + error;
break loopThroughPages;
}
} // end of try catch
if (result) pageToken = result.nextPageToken;
} while (pageToken);
if (!error) success = true;
return { success: success, error: error, count: count };
}
However, there still does not appear to be a way to get the maximum number available to the domain using this API.
Use CustomerUsageReports.
jay0lee is kind enough to provide the GAM source code in Python. I crudely modified the doGetCustomerInfo() function into Apps Script thusly:
function getNumberOfLicenses() {
var tryDate = new Date();
var dateString = tryDate.getFullYear().toString() + "-" + (tryDate.getMonth() + 1).toString() + "-" + tryDate.getDate().toString();
while (true) {
try {
var response = AdminReports.CustomerUsageReports.get(dateString,{parameters : "accounts:gsuite_basic_total_licenses,accounts:gsuite_basic_used_licenses"});
break;
} catch(e) {
//Logger.log(e.warnings.toString());
tryDate.setDate(tryDate.getDate()-1);
dateString = tryDate.getFullYear().toString() + "-" + (tryDate.getMonth() + 1).toString() + "-" + tryDate.getDate().toString();
continue;
}
};
var availLicenseCount = response.usageReports[0].parameters[0].intValue;
var usedLicenseCount = response.usageReports[0].parameters[1].intValue;
Logger.log("Available licenses:" + availLicenseCount.toString());
Logger.log("Used licenses:" + usedLicenseCount.toString());
return availLicenseCount;
}
I would recommend exploring GAM which is a tool that gives command line access to the administration functions of your domain.