Ejemplo n.º 1
0
 public static Model.Build ToModel(this EntityAlias2.Build source)
 {
     return(new Model.Build
     {
         BuildIdentifier = source.Id
     });
 }
Ejemplo n.º 2
0
        public async Task QueueBuildCommand_RecentFailedBuilds_SucceededAndFailed()
        {
            const string path1 = "path1";

            Subscription[] subscriptions = new Subscription[]
            {
                CreateSubscription("repo1")
            };

            List <List <SubscriptionImagePaths> > allSubscriptionImagePaths = new()
            {
                new List <SubscriptionImagePaths>
                {
                    new SubscriptionImagePaths
                    {
                        SubscriptionId = subscriptions[0].Id,
                        ImagePaths     = new string[]
                        {
                            path1
                        }
                    }
                }
            };

            PagedList <WebApi.Build> allBuilds = new();

            WebApi.Build succeeded = CreateBuild($"https://succeededbuild");
            succeeded.Tags.Add(AzdoTags.AutoBuilder);
            succeeded.Status = WebApi.BuildStatus.Completed;
            succeeded.Result = WebApi.BuildResult.Succeeded;
            allBuilds.Add(succeeded);

            for (int i = 0; i < QueueBuildCommand.BuildFailureLimit; i++)
            {
                WebApi.Build failedBuild = CreateBuild($"https://failedbuild-{i}");
                failedBuild.Tags.Add(AzdoTags.AutoBuilder);
                failedBuild.Status = WebApi.BuildStatus.Completed;
                failedBuild.Result = WebApi.BuildResult.Failed;
                allBuilds.Add(failedBuild);
            }

            using TestContext context = new(subscriptions, allSubscriptionImagePaths, new PagedList <WebApi.Build>(), allBuilds);
            await context.ExecuteCommandAsync();

            Dictionary <Subscription, IList <string> > expectedPathsBySubscription = new()
            {
                {
                    subscriptions[0],
                    new List <string>
                    {
                        path1
                    }
                }
            };

            context.Verify(notificationPostCallCount: 1, isQueuedBuildExpected: true, expectedPathsBySubscription);
        }
Ejemplo n.º 3
0
        public Build(BuildDefinitionReference definition, Microsoft.TeamFoundation.Build.WebApi.Build build, IList <Microsoft.TeamFoundation.TestManagement.WebApi.TestRun> testRuns = null)
        {
            Definition = definition;

            Id         = build.Id;
            Status     = build.Status;
            QueueTime  = build.QueueTime;
            StartTime  = build.StartTime;
            FinishTime = build.FinishTime;
            Result     = build.Result;
            TestRuns   = testRuns?.Select(t => new TestRun(t)).ToList() ?? new List <TestRun>();
        }
Ejemplo n.º 4
0
        public async Task<Build2.Build> UpdateBuildNumber(
            int buildId,
            string buildNumber,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            Build2.Build build = new Build2.Build()
            {
                Id = buildId,
                BuildNumber = buildNumber,
                Project = new TeamProjectReference()
                {
                    Id = _projectId,
                },
            };

            return await BuildHttpClient.UpdateBuildAsync(build, _projectId, buildId, cancellationToken);
        }
Ejemplo n.º 5
0
        public async Task <Build2.Build> UpdateBuildNumber(
            int buildId,
            string buildNumber,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            Build2.Build build = new Build2.Build()
            {
                Id          = buildId,
                BuildNumber = buildNumber,
                Project     = new TeamProjectReference()
                {
                    Id = _projectId,
                },
            };

            return(await _buildHttpClient.UpdateBuildAsync(build, cancellationToken : cancellationToken));
        }
Ejemplo n.º 6
0
        public TfsBuild(Microsoft.TeamFoundation.Build.WebApi.Build build)
        {
            _id     = build.Url;
            BuildId = build.Id;
            Id      = build.Id.ToString(CultureInfo.InvariantCulture);

            QueueTime       = build.QueueTime;
            LastChangedTime = build.QueueTime;
            BranchName      = build.SourceBranch;

            _nativeResult = build.Result;
            _nativeStatus = build.Status;
            _nativeReason = build.Reason;

            RequestedBy  = new TfsUser(build.RequestedBy);
            RequestedFor = new TfsUser(build.RequestedFor);
            Definition   = new TfsBuildDefinition(build.Definition);

            Links = new TfsLinks(build);
        }
Ejemplo n.º 7
0
        public async Task <Model.Build> Handle(
            QueueBuildQuery message,
            CancellationToken cancellationToken)
        {
            var connection = _tfsProvider.GetConnection() as VssConnection;

            var buildServer = connection.GetClient <BuildHttpClient>(); // connect to the build server subpart

            if (message.BuildDefinition.BuildDefinitionIdentifier == 0)
            {
                //fill it in
                var builddDefs = await buildServer.GetDefinitionsAsync2(name : message.BuildDefinition.BuildDefinitionName, project : message.BuildDefinition.ProjectId);

                message.BuildDefinition.BuildDefinitionIdentifier = builddDefs.Single().Id;
            }
            var build = new Microsoft.TeamFoundation.Build.WebApi.Build()
            {
                Definition = message.BuildDefinition.ToEntity(),
                Project    = message.BuildDefinition.ToEntity().Project
            };

            try
            {
                var queuedBuild = await buildServer.QueueBuildAsync(build);

                _logger.LogInformation("Queued build for {id} {name}", build.Definition.Id, message.BuildDefinition.BuildDefinitionName);
                do
                {
                    _logger.LogInformation("Build {buildId} is {status}. Waiting 1 second.", queuedBuild.Id, queuedBuild.Status);
                    Thread.Sleep(1000);
                    queuedBuild = await buildServer.GetBuildAsync(message.BuildDefinition.ToEntity().Project.Name, queuedBuild.Id);
                }while (queuedBuild.Status != BuildStatus.Completed);
                _logger.LogInformation("Build is complete. Status {buildResult}", queuedBuild.Result);
                return(queuedBuild.ToModel());
            }
            finally
            {
                // buildServer.DeleteDefinitionAsync(definitionId: buildDefinitionResult.Id, project: buildDefinitionResult.Project.Id).Wait();
                // Console.WriteLine($"Deleted build");
            }
        }
Ejemplo n.º 8
0
            private static Mock <IBuildHttpClient> CreateBuildHttpClientMock(TeamProject project,
                                                                             PagedList <WebApi.Build> inProgressBuilds, PagedList <WebApi.Build> failedBuilds)
            {
                WebApi.Build build = CreateBuild("https://contoso");

                Mock <IBuildHttpClient> buildHttpClientMock = new();

                buildHttpClientMock
                .Setup(o => o.GetBuildsAsync(project.Id, It.IsAny <IEnumerable <int> >(), WebApi.BuildStatus.InProgress))
                .ReturnsAsync(inProgressBuilds);

                buildHttpClientMock
                .Setup(o => o.GetBuildsAsync(project.Id, It.IsAny <IEnumerable <int> >(), null))
                .ReturnsAsync(failedBuilds);

                buildHttpClientMock
                .Setup(o => o.QueueBuildAsync(It.IsAny <WebApi.Build>()))
                .ReturnsAsync(build);

                return(buildHttpClientMock);
            }
Ejemplo n.º 9
0
 /// <summary>
 /// Returns a value indicating whether the <see cref="Build"/> object contains the expected state.
 /// </summary>
 /// <param name="build">The <see cref="Build"/> to validate.</param>
 /// <param name="subscription">Subscription object that contains metadata to compare against the <paramref name="build"/>.</param>
 /// <param name="expectedPaths">The set of expected path arguments that should have been passed to the build.</param>
 private static bool FilterBuildToSubscription(WebApi.Build build, Subscription subscription, IList <string> expectedPaths)
 {
     return(build.Definition.Id == subscription.PipelineTrigger.Id &&
            build.SourceBranch == subscription.Manifest.Branch &&
            FilterBuildToParameters(build.Parameters, subscription.PipelineTrigger.PathVariable, expectedPaths));
 }
Ejemplo n.º 10
0
 private TfsBuild Convert(Microsoft.TeamFoundation.Build.WebApi.Build build) => new TfsBuild(build);
        public bool RunCI()
        {
            VssConnection connection = new VssConnection(new Uri(collectionUri), new VssBasicCredential(string.Empty, pat));

            BuildHttpClient buildClient = connection.GetClient <BuildHttpClient>();

            Task <List <BuildDefinitionReference> > buildDefs = Task.Run(() => buildClient.GetDefinitionsAsync(projectName, null, null, null, null, null, null, null, null, null, null, null));

            buildDefs.Wait();

            List <BuildDefinition> buildDefinitions = new List <BuildDefinition>();

            foreach (BuildDefinitionReference bdr in buildDefs.Result)
            {
                Task <BuildDefinition> bd = Task.Run(() => buildClient.GetDefinitionAsync(projectName, bdr.Id));
                bd.Wait();

                buildDefinitions.Add(bd.Result);
            }

            SortedList <int, BuildDefinition> buildIsNeeded = new SortedList <int, BuildDefinition>();


            foreach (BuildDefinition buildDef in buildDefinitions)
            {
                bool ignoreDefintion = true;

                if (buildDef.Repository != null && buildDef.Repository.Type == "Svn")
                {
                    // get last version from the repository

                    int buildOrder = 0;
                    if (buildDef.Variables.ContainsKey("buildOrder"))
                    {
                        BuildDefinitionVariable bvBuildOrder = null;
                        if (buildDef.Variables.TryGetValue("buildOrder", out bvBuildOrder))
                        {
                            buildOrder = Convert.ToInt32(bvBuildOrder.Value);
                        }
                    }

                    if (buildDef.Variables.ContainsKey("buildCI"))
                    {
                        BuildDefinitionVariable bvBuildCi = null;
                        if (buildDef.Variables.TryGetValue("buildCI", out bvBuildCi))
                        {
                            ignoreDefintion = !Convert.ToBoolean(bvBuildCi.Value);
                        }
                    }

                    if (!ignoreDefintion)
                    {
                        long lastRepositoryVersion = GetLatestCheckinVersion(buildDef.Repository.Id, buildDef.Repository.DefaultBranch);

                        // get last version from builds
                        Task <List <Microsoft.TeamFoundation.Build.WebApi.Build> > taskBuildList = Task.Run(() => buildClient.GetBuildsAsync(projectName, new List <int> {
                            buildDef.Id
                        }));
                        taskBuildList.Wait();

                        Microsoft.TeamFoundation.Build.WebApi.Build latestBuild = taskBuildList.Result[0] as Microsoft.TeamFoundation.Build.WebApi.Build;
                        if (latestBuild != null)
                        {
                            if (Convert.ToInt64(latestBuild.SourceVersion) < lastRepositoryVersion)
                            {
                                Console.WriteLine(string.Format("Build is required for {0} - last built version {1} last checkin version {2}", buildDef.Name, latestBuild.SourceVersion, lastRepositoryVersion));
                                buildIsNeeded.Add(buildOrder, buildDef);
                            }
                            else
                            {
                                Console.WriteLine(string.Format("Build is up to date for {0} - last built version {1} last checkin version {2}", buildDef.Name, latestBuild.SourceVersion, lastRepositoryVersion));
                            }
                        }
                    }
                }
            }

            // now we know what needs to be build, we must trigger any builds...
            foreach (BuildDefinition buildDef in buildIsNeeded.Values)
            {
                Console.WriteLine(string.Format("Triggering build for {0}", buildDef.Name));

                Build build = new Build()
                {
                    Definition = buildDef, Project = buildDef.Project, Reason = BuildReason.IndividualCI
                };
                Task <Build> taskBuild = Task.Run(() => buildClient.QueueBuildAsync(build));
                taskBuild.Wait();

                return(true); // ONLY ALLOW **ONE** BUILD PER TIME
            }

            return(false);
        }
Ejemplo n.º 12
0
        private Dictionary<string, int> GetTestResultsRest(TfsTeamProjectCollection teamProjectCollection, DefinitionReference definitionReference, Build build)
        {
            var testResults = new Dictionary<string, int>();
            try
            {
                var testManagementService = teamProjectCollection.GetService<ITestManagementService>();

                var testManagementTeamProject = testManagementService.GetTeamProject(definitionReference.Project.Name);
                var testRuns = testManagementTeamProject.TestRuns.ByBuild(build.Uri).ToList();

                if (testRuns.Any())
                {
                    

                    var totalTests = testRuns.Sum(x => x.TotalTests);
                    var totalPassedTests = testRuns.Sum(x => x.PassedTests);

                    testResults.Add("PassedTests", totalPassedTests);
                    testResults.Add("TotalTests", totalTests);
                }
                
            }
            catch (Exception e)
            {
                LogService.WriteError(e);
                throw;
            }
            return testResults;


        }
Ejemplo n.º 13
0
 public Task <WebApi.Build> QueueBuildAsync(WebApi.Build build) =>
 _inner.QueueBuildAsync(build);