Ejemplo n.º 1
0
    static void Main(string[] args)
    {
        string ur = "https://xxxxxxx/";
        TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(new Uri(ur));
        //Get build information
        BuildHttpClient bhc         = ttpc.GetClient <BuildHttpClient>();
        string          projectname = "Project";
        int             buildId     = 1;
        Build           bui         = bhc.GetBuildAsync(projectname, buildId).Result;
        //Get test run for the build
        TestManagementHttpClient ithc = ttpc.GetClient <TestManagementHttpClient>();

        Console.WriteLine(bui.BuildNumber);

        QueryModel qm = new QueryModel("Select * From TestRun Where BuildNumber Contains '" + bui.BuildNumber + "'");

        List <TestRun> testruns = ithc.GetTestRunsByQueryAsync(qm, projectname).Result;

        foreach (TestRun testrun in testruns)
        {
            List <TestCaseResult> testresults = ithc.GetTestResultsAsync(projectname, testrun.Id).Result;
            foreach (TestCaseResult tcr in testresults)
            {
                Console.WriteLine(tcr.TestCase.Name);
                Console.WriteLine(tcr.Outcome);
            }

            Console.ReadLine();
        }
        Console.ReadLine();
    }
        static void Main(string[] args)
        {
            string collectionUri;

            //set to Uri of the TFS collection
            //if this code is running in Build/Release workflow, we will fetch collection Uri from environment variable
            //See https://www.visualstudio.com/en-us/docs/build/define/variables for full list of agent environment variables
            if (Environment.GetEnvironmentVariable("TF_BUILD") == "True")
            {
                collectionUri = Environment.GetEnvironmentVariable("SYSTEM_TEAMFOUNDATIONCOLLECTIONURI");
                Console.WriteLine("Fetched Collection (or VSTS account) from environment variable SYSTEM_TEAMFOUNDATIONCOLLECTIONURI: {0}", collectionUri);
            }
            else // set it to TFS instance of your choice
            {
                collectionUri = "http://buildmachine1:8080/tfs/DefaultCollection";
                Console.WriteLine("Using Collection (or VSTS account): {0}", collectionUri);
            }

            //authentication..
            VssConnection connection = new VssConnection(new Uri(collectionUri), new VssCredentials());

            //set the team project name in which the test results must be published...
            // get team project name from the agent environment variables if the script is running in Build workflow..
            string teamProject;

            if (Environment.GetEnvironmentVariable("TF_BUILD") == "True")
            {
                teamProject = Environment.GetEnvironmentVariable("SYSTEM_TEAMPROJECT");
                Console.WriteLine("Fetched team project from environment variable SYSTEM_TEAMPROJECT: {0}", teamProject);
            }
            else //else set it the team project of your choice...
            {
                teamProject = "FabrikamFiber";
                Console.WriteLine("Using team project: {0}", teamProject);
            }

            // get the build number to publis results against...

            string buildNumber = null, buildUri = null, releaseUri = null, releaseEnvironmentUri = null; int buildId;

            // if this code is running in build/release workflow, we will use agent environment variables for fetch build/release Uris to associate information
            if (Environment.GetEnvironmentVariable("TF_BUILD") == "True")
            {
                //If RELEASE_RELEASEURI variable is set, then this code is running in the Release workflow, so we fetch release details
                if (Environment.GetEnvironmentVariable("RELEASE_RELEASEURI") != "")
                {
                    releaseUri = Environment.GetEnvironmentVariable("RELEASE_RELEASEURI");
                    Console.WriteLine("Fetched release uri from environment variable RELEASE_RELEASEURI: {0}", releaseUri);

                    releaseEnvironmentUri = Environment.GetEnvironmentVariable("RELEASE_ENVIRONMENTURI");
                    Console.WriteLine("Fetched release environemnt uri from environment variable RELEASE_ENVIRONMENTURI: {0}", releaseEnvironmentUri);
                }
                //note that the build used to deploy and test a Release is an Aritfact.
                //If you have multiple builds or are using external artifacts like Jenkins, make sure you use Aritfact variables to find the build information
                //See https://www.visualstudio.com/en-us/docs/release/author-release-definition/understanding-tasks#predefvariables for pre-defined variables available in release
                //See https://www.visualstudio.com/en-us/docs/release/author-release-definition/understanding-artifacts#variables for artifact variables documentation
                //For example, you'll have to use RELEASE_ARTIFACTS_<aftifactname>_BUILDID to find the build number.
                //Here we are assuming a simple setup, where we are working with Team Build and using Build variables instead...

                //build number is human readable format of the build name, you can confiure it's format in build options..
                buildNumber = Environment.GetEnvironmentVariable("BUILD_BUILDNUMBER");
                Console.WriteLine("Fetched build number from environment variable BUILD_BUILDNUMBER: {0}", buildNumber);

                //build id is the id associated with the build number, which we will use to associate the test run with...
                buildId = Convert.ToInt32(Environment.GetEnvironmentVariable("BUILD_BUILDID"));
                Console.WriteLine("Fetched build id from environment variable BUILD_BUILDID: {0}", buildId);

                //build uri is a more elaborate form of build id, in the vstfs:///Build/Build/<id> format...
                //We will use this for querying test runs against this build...
                buildUri = Environment.GetEnvironmentVariable("BUILD_BUILDURI");
                Console.WriteLine("Fetched build uri from environment variable BUILD_BUILDURI: {0}", buildUri);
            }
            else //if the code is running in standalone mode, you'll have to use Build and Release APIs to fetch the build and release information...
            //see https://www.visualstudio.com/en-us/docs/integrate/api/build/overview for build APIs...
            //and https://www.visualstudio.com/en-us/docs/release/overview for release APIs...
            {
                buildNumber           = "20161124.2";
                buildId               = 3;
                buildUri              = "vstfs:///Build/Build/40";
                releaseUri            = "vstfs:///ReleaseManagement/Release/2";
                releaseEnvironmentUri = "vstfs:///ReleaseManagement/Environment/2";
                Console.WriteLine("Using build number: {0}; build id: {1}; build uri: {2}; release uri: {3}; release environment uri: {4}", buildNumber, buildId, buildUri, releaseUri, releaseEnvironmentUri);
            }


            //Client to use test run and test result APIs...

            TestManagementHttpClient client        = connection.GetClient <TestManagementHttpClient>();

            //Query all test runs publishing against a release environmment...
            //Ideally, we'd use the GetTestRunsAsync with release uri and release environment uri filters here,
            //but GetTestRunsAsync does not support those filters yet...
            //Hence we will use GetTestRunsByQueryAsync...

            QueryModel      runQuery               = new QueryModel("Select * from TestRun where releaseUri='" + releaseUri + "' and releaseEnvironmentUri='" + releaseEnvironmentUri + "'");
            IList <TestRun> TestRunsAgainstRelease = client.GetTestRunsByQueryAsync(runQuery, teamProject).Result;

            // if any of the test runs has tests that have not passed, then flag failure...

            bool notAllTestsPassed = false;

            foreach (TestRun t in TestRunsAgainstRelease)
            {
                Console.WriteLine("Test run: {0}; Total tests: {1}; Passed tests: {2} ", t.Name, t.TotalTests, t.PassedTests);
                if (t.TotalTests != t.PassedTests)
                {
                    notAllTestsPassed = true;
                }
                //though we don't need to get test results,
                //we are getting test results and printing tests that failed just to demo how to query results in a test run
                IList <TestCaseResult> TestResutsInRun = client.GetTestResultsAsync(project: teamProject, runId: t.Id).Result;
                foreach (TestCaseResult r in TestResutsInRun)
                {
                    Console.WriteLine("Test: {0}; Outcome {1}", r.TestCaseTitle, r.Outcome);
                }
            }

            if (notAllTestsPassed)
            {
                Console.WriteLine("Not all tests passed.. Returning failure... ");
                Environment.Exit(1);
            }
            else
            {
                Console.WriteLine("All tests passed.. Returning success... ");
                Environment.Exit(0);
            }
        }
        public static void AddScreenshots(string tfsURL, string tfsToken, string projectId, string buildDefinitionName, string projectName, string nameOfProjectWithTests)
        {
            var dictionary = DictionaryInteractions.ReadFromPropertiesFile(ReturnPath.SolutionFolderPath() + nameOfProjectWithTests + "/ExtentReport/ReportProperties.txt");

            string[] fileArray       = Directory.GetFiles(dictionary["ReportPath"]);
            var      onlyScreenshots = fileArray.Where(s => s.IndexOf(".png") != -1);

            if (onlyScreenshots.ToList().Count != 0)
            {
                VssConnection     vc  = new VssConnection(new Uri(tfsURL), new VssBasicCredential(string.Empty, tfsToken));
                BuildHttpClient   bhc = vc.GetClient <BuildHttpClient>();
                ProjectHttpClient ddd = vc.GetClient <ProjectHttpClient>();

                //ITestManagementTeamProject ddd1 = ddd.GetProject("hgfyjh");



                var   buildsPerProject = bhc.GetBuildsAsync(projectId).GetAwaiter().GetResult();
                var   lastBuildId      = buildsPerProject.Where <Build>(x => x.Definition.Name == buildDefinitionName).Max <Build>(z => z.Id);
                Build lastBuild        = buildsPerProject.FirstOrDefault <Build>(x => x.Id == lastBuildId);

                Console.Write("Last Build Number: " + lastBuildId);
                TestManagementHttpClient ithc = vc.GetClient <TestManagementHttpClient>();
                QueryModel     qm             = new QueryModel("Select * From TestRun Where BuildNumber Contains '" + lastBuild.BuildNumber + "'");
                List <TestRun> testruns       = ithc.GetTestRunsByQueryAsync(qm, projectName).Result;
                Console.Write("testruns.Count: " + testruns.Count);

                foreach (TestRun testrun in testruns)
                {
                    List <TestCaseResult> testresults = ithc.GetTestResultsAsync(projectName, testrun.Id).Result;
                    Console.Write("testresults.Count: " + testresults.Count);
                    foreach (TestCaseResult tcr in testresults)
                    {
                        var testNamesFromScreents = onlyScreenshots.Select(s => s.ToLower().Split(new string[] { "sec\\" }, StringSplitOptions.None)[1].Split(new string[] { "20" }, StringSplitOptions.None)[0]).Distinct();
                        //var screentsShotPerTest = onlyScreenshots.Where(s => s.Split(new string[] { "sec\\" }, StringSplitOptions.None)[1].Split(new string[] { "20" }, StringSplitOptions.None)[0] == scenarioName.Replace(" ", string.Empty));

                        Console.WriteLine("tcr.Id: " + tcr.Id);
                        if (testNamesFromScreents.ToList().Contains(tcr.AutomatedTestName.Split('.').Last().ToLower()))
                        {
                            Console.WriteLine("recognize Test: " + tcr.AutomatedTestName.Split('.').Last().ToLower());
                            using (var client = new HttpClient())
                            {
                                string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", tfsToken)));
                                client.BaseAddress = new Uri(tfsURL);  //url of our account
                                client.DefaultRequestHeaders.Accept.Clear();
                                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
                                var screentsShotPerTest = onlyScreenshots.Where(s => s.Split(new string[] { "sec\\" }, StringSplitOptions.None)[1].Split(new string[] { "20" }, StringSplitOptions.None)[0].ToLower() == tcr.AutomatedTestName.Split('.').Last().ToLower());

                                foreach (var screenshot in screentsShotPerTest)
                                {
                                    Console.WriteLine("screentsShotPerTest: " + screenshot);
                                    var post = new PostImageTfs()
                                    {
                                        Stream         = Convert.ToBase64String(File.ReadAllBytes(screenshot)),
                                        AttachmentType = "GeneralAttachment",
                                        Comment        = "screenshot of error",
                                        FileName       = screenshot.Split(new string[] { "sec\\" }, StringSplitOptions.None)[1]
                                    };
                                    Console.WriteLine("tcr.TestRun.Id: " + tcr.TestRun.Id);
                                    Console.WriteLine("tcr.Id: " + tcr.Id);
                                    Console.WriteLine("screenshot.Split(new string[] { DateTime.Now.Year.ToString() }, StringSplitOptions.None)[2] " + screenshot.Split(new string[] { DateTime.Now.Year.ToString() }, StringSplitOptions.None)[2]);

                                    var test = new StringContent($"{{\"stream\": \"{post.Stream}\",\"fileName\": \"{post.FileName}\",\"comment\": \"{post.Comment}\",\"attachmentType\": \"{post.AttachmentType}\"}}", Encoding.UTF8, "application/json");

                                    HttpResponseMessage response = client.PostAsync("/DefaultCollection/" + projectName + "/_apis/test/runs/" + tcr.TestRun.Id + "/results/" + tcr.Id + "/attachments?api-version=2.0-preview.1", test).Result;
                                    Console.WriteLine("response: " + response.StatusCode);
                                }
                            }
                        }
                    }
                }
            }
        }