diff --git a/CloneDevOpsTemplate/Controllers/BoardsController.cs b/CloneDevOpsTemplate/Controllers/BoardsController.cs index da38f0b..577a5dc 100644 --- a/CloneDevOpsTemplate/Controllers/BoardsController.cs +++ b/CloneDevOpsTemplate/Controllers/BoardsController.cs @@ -7,11 +7,12 @@ namespace CloneDevOpsTemplate.Controllers; [Authorize] -public class BoardsController(IBoardService boardService, ICloneManager cloneManager, ITeamsService teamsService) : Controller +public class BoardsController(IBoardService boardService, ICloneManager cloneManager, ITeamsService teamsService, IMigrationProgressTracker progressTracker) : Controller { private readonly IBoardService _boardService = boardService; private readonly ICloneManager _cloneManager = cloneManager; private readonly ITeamsService _teamsService = teamsService; + private readonly IMigrationProgressTracker _progressTracker = progressTracker; public async Task Boards(Guid projectId, Guid teamId) { @@ -62,24 +63,27 @@ public async Task CardStyles(Guid projectId, Guid teamId, Guid bo } [HttpGet] - public async Task CloneBoards() + public async Task CloneBoards(Guid operationId = default) { - var teams = await _teamsService.GetAllTeamsAsync() ?? new(); - return View(teams.Value); + return await CloneFormView(nameof(CloneBoards), _progressTracker.TakeFinished(operationId)); } [HttpPost] - public async Task CloneBoards(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId) + public async Task CloneBoards(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId, Guid operationId = default) { if (!ModelState.IsValid) { - return await CloneBoards(); + return await CloneFormView(nameof(CloneBoards)); } - await _cloneManager.CloneBoardsAsync(templateProjectId, projectId, templateTeamId, projectTeamId); - ViewBag.SuccessMessage = "Success"; + operationId = await _progressTracker.RunAsync(operationId, "Cloning boards...", "Boards cloned successfully.", + progress => _cloneManager.CloneBoardsAsync(templateProjectId, projectId, templateTeamId, projectTeamId, progress)); + return RedirectToAction(nameof(CloneBoards), new { operationId }); + } - return await CloneBoards(); + private async Task CloneFormView(string action, MigrationProgress? finishedMigration = null) + { + Teams teams = await _teamsService.GetAllTeamsAsync() ?? new(); + return View(action, new CloneFormViewModel(teams.Value, "Boards", action, finishedMigration)); } } - diff --git a/CloneDevOpsTemplate/Controllers/IterationController.cs b/CloneDevOpsTemplate/Controllers/IterationController.cs index 62ca821..c17796e 100644 --- a/CloneDevOpsTemplate/Controllers/IterationController.cs +++ b/CloneDevOpsTemplate/Controllers/IterationController.cs @@ -7,11 +7,12 @@ namespace CloneDevOpsTemplate.Controllers; [Authorize] -public class IterationController(IIterationService iterationService, ICloneManager cloneManager, IProjectService projectService) : Controller +public class IterationController(IIterationService iterationService, ICloneManager cloneManager, IProjectService projectService, IMigrationProgressTracker progressTracker) : Controller { private readonly IIterationService _iterationService = iterationService; private readonly ICloneManager _cloneManager = cloneManager; private readonly IProjectService _projectService = projectService; + private readonly IMigrationProgressTracker _progressTracker = progressTracker; public async Task Iterations(Guid projectId) { @@ -40,43 +41,46 @@ public async Task Areas(Guid projectId) } [HttpGet] - public async Task CloneIterations() + public async Task CloneIterations(Guid operationId = default) { - var projects = await _projectService.GetAllProjectsAsync() ?? new(); - return View(projects.Value); + return await CloneFormView(nameof(CloneIterations), _progressTracker.TakeFinished(operationId)); } [HttpPost] - public async Task CloneIterations(Guid templateProjectId, Guid projectId) + public async Task CloneIterations(Guid templateProjectId, Guid projectId, Guid operationId = default) { if (!ModelState.IsValid) { - return await CloneIterations(); + return await CloneFormView(nameof(CloneIterations)); } - await _cloneManager.CloneClassificationNodes(templateProjectId, projectId, TreeStructureGroup.Iterations); - ViewBag.SuccessMessage = "Success"; - - return await CloneIterations(); + operationId = await _progressTracker.RunAsync(operationId, "Cloning iterations...", "Iterations cloned successfully.", + progress => _cloneManager.CloneClassificationNodes(templateProjectId, projectId, TreeStructureGroup.Iterations, progress)); + return RedirectToAction(nameof(CloneIterations), new { operationId }); } [HttpGet] - public async Task CloneAreas() + public async Task CloneAreas(Guid operationId = default) { - return await CloneIterations(); + return await CloneFormView(nameof(CloneAreas), _progressTracker.TakeFinished(operationId)); } [HttpPost] - public async Task CloneAreas(Guid templateProjectId, Guid projectId) + public async Task CloneAreas(Guid templateProjectId, Guid projectId, Guid operationId = default) { if (!ModelState.IsValid) { - return await CloneIterations(); + return await CloneFormView(nameof(CloneAreas)); } - await _cloneManager.CloneClassificationNodes(templateProjectId, projectId, TreeStructureGroup.Areas); - ViewBag.SuccessMessage = "Success"; + operationId = await _progressTracker.RunAsync(operationId, "Cloning areas...", "Areas cloned successfully.", + progress => _cloneManager.CloneClassificationNodes(templateProjectId, projectId, TreeStructureGroup.Areas, progress)); + return RedirectToAction(nameof(CloneAreas), new { operationId }); + } - return await CloneIterations(); + private async Task CloneFormView(string action, MigrationProgress? finishedMigration = null) + { + Projects projects = await _projectService.GetAllProjectsAsync() ?? new(); + return View(action, new CloneFormViewModel(projects.Value, "Iteration", action, finishedMigration)); } -} \ No newline at end of file +} diff --git a/CloneDevOpsTemplate/Controllers/ProjectController.cs b/CloneDevOpsTemplate/Controllers/ProjectController.cs index 85ff366..9cc3701 100644 --- a/CloneDevOpsTemplate/Controllers/ProjectController.cs +++ b/CloneDevOpsTemplate/Controllers/ProjectController.cs @@ -7,10 +7,11 @@ namespace CloneDevOpsTemplate.Controllers; [Authorize] -public class ProjectController(IProjectService projectService, ICloneManager cloneManager) : Controller +public class ProjectController(IProjectService projectService, ICloneManager cloneManager, IMigrationProgressTracker progressTracker) : Controller { private readonly IProjectService _projectService = projectService; private readonly ICloneManager _cloneManager = cloneManager; + private readonly IMigrationProgressTracker _progressTracker = progressTracker; [HttpGet] public async Task Projects() @@ -48,65 +49,98 @@ public async Task ProjectProperties(Guid projectId) } [HttpGet] - public async Task CreateProject() + public async Task CreateProject(Guid operationId = default) { - return await Projects(); + return await ProjectFormView(nameof(CreateProject), _progressTracker.TakeFinished(operationId)); } [HttpPost] - public async Task CreateProject(Guid templateProjectId, string newProjectName, string description, Visibility visibility) + public async Task CreateProject(Guid templateProjectId, string newProjectName, string description, Visibility visibility, Guid operationId = default) { if (!ModelState.IsValid) { - return await CreateProject(); + return await ProjectFormView(nameof(CreateProject)); } - var cloneProjectResult = await _cloneManager.CloneProjectAsync(templateProjectId, newProjectName, description, visibility); - - if (cloneProjectResult.ErrorMessage is not null) + operationId = MigrationProgressTrackerExtensions.EnsureOperationId(operationId); + var details = _progressTracker.CreateDetailReporter(operationId); + CloneProjectResult cloneProjectResult = null!; + + (string Message, Func> Run)[] steps = + [ + ("Creating project...", async () => + { + cloneProjectResult = await _cloneManager.CloneProjectAsync(templateProjectId, newProjectName, description, visibility, details); + return CloneResult.FromError(cloneProjectResult.ErrorMessage); + }), + ("Cloning iterations and areas...", async () => CloneResult.Combine(await Task.WhenAll( + _cloneManager.CloneClassificationNodes(templateProjectId, cloneProjectResult.Project.Id, TreeStructureGroup.Iterations, details), + _cloneManager.CloneClassificationNodes(templateProjectId, cloneProjectResult.Project.Id, TreeStructureGroup.Areas, details)))), + ("Cloning teams, settings, boards and repositories...", async () => CloneResult.Combine(await Task.WhenAll( + _cloneManager.CloneTeamsAndSettingsAndBoardsAsync(cloneProjectResult.TemplateProject, cloneProjectResult.Project, details), + _cloneManager.CloneRepositoriesAsync(templateProjectId, cloneProjectResult.Project.Id, details)))), + ("Cloning pull requests...", () => + _cloneManager.CloneGitPullRequestsAsync(templateProjectId, cloneProjectResult.Project.Id, details)), + ]; + + try { - ModelState.AddModelError("ErrorMessage", cloneProjectResult.ErrorMessage); - return await CreateProject(); + _progressTracker.Start(operationId, steps.Length); + for (int i = 0; i < steps.Length; i++) + { + _progressTracker.Report(operationId, i + 1, steps[i].Message); + var stepResult = await steps[i].Run(); + + if (!stepResult.Succeeded) + { + _progressTracker.Fail(operationId, $"{steps[i].Message.TrimEnd('.')} failed: {stepResult.ErrorMessage}"); + return RedirectToAction(nameof(CreateProject), new { operationId }); + } + } + } + catch + { + _progressTracker.Remove(operationId); + throw; } - await Task.WhenAll( - _cloneManager.CloneClassificationNodes(templateProjectId, cloneProjectResult.Project.Id, TreeStructureGroup.Iterations), - _cloneManager.CloneClassificationNodes(templateProjectId, cloneProjectResult.Project.Id, TreeStructureGroup.Areas) - ); - await Task.WhenAll( - _cloneManager.CloneTeamsAndSettingsAndBoardsAsync(cloneProjectResult.TemplateProject, cloneProjectResult.Project), - _cloneManager.CloneRepositoriesAsync(templateProjectId, cloneProjectResult.Project.Id) - ); - - await _cloneManager.CloneGitPullRequestsAsync(templateProjectId, cloneProjectResult.Project.Id); - + _progressTracker.Remove(operationId); return RedirectToAction("Project", new { projectId = cloneProjectResult.Project.Id }); } [HttpGet] - public async Task CloneProject() + public IActionResult MigrationProgress(Guid operationId) + { + var progress = _progressTracker.Get(operationId); + return progress is null ? NoContent() : Json(progress); + } + + [HttpGet] + public async Task CloneProject(Guid operationId = default) { - return await Projects(); + return await ProjectFormView(nameof(CloneProject), _progressTracker.TakeFinished(operationId)); } [HttpPost] - public async Task CloneProject(Guid templateProjectId, string newProjectName, string description, Visibility visibility) + public async Task CloneProject(Guid templateProjectId, string newProjectName, string description, Visibility visibility, Guid operationId = default) { if (!ModelState.IsValid) { - return await Projects(); + return await ProjectFormView(nameof(CloneProject)); } - var cloneProjectResult = await _cloneManager.CloneProjectAsync(templateProjectId, newProjectName, description, visibility); - if (cloneProjectResult.ErrorMessage is not null) - { - ModelState.AddModelError("ErrorMessage", cloneProjectResult.ErrorMessage); - } - else - { - ViewBag.SuccessMessage = "Success"; - } + operationId = await _progressTracker.RunAsync(operationId, "Creating project...", $"Project '{newProjectName}' cloned successfully.", + async progress => + { + var cloneProjectResult = await _cloneManager.CloneProjectAsync(templateProjectId, newProjectName, description, visibility, progress); + return CloneResult.FromError(cloneProjectResult.ErrorMessage); + }); + return RedirectToAction(nameof(CloneProject), new { operationId }); + } - return await Projects(); + private async Task ProjectFormView(string action, MigrationProgress? finishedMigration = null) + { + Projects projects = await _projectService.GetAllProjectsAsync() ?? new(); + return View(action, new CloneFormViewModel(projects.Value, "Project", action, finishedMigration)); } -} \ No newline at end of file +} diff --git a/CloneDevOpsTemplate/Controllers/RepositoryController.cs b/CloneDevOpsTemplate/Controllers/RepositoryController.cs index 9438710..ecd90e3 100644 --- a/CloneDevOpsTemplate/Controllers/RepositoryController.cs +++ b/CloneDevOpsTemplate/Controllers/RepositoryController.cs @@ -7,11 +7,12 @@ namespace CloneDevOpsTemplate.Controllers; [Authorize] -public class RepositoryController(IRepositoryService repositoryService, ICloneManager cloneManager, IProjectService projectService) : Controller +public class RepositoryController(IRepositoryService repositoryService, ICloneManager cloneManager, IProjectService projectService, IMigrationProgressTracker progressTracker) : Controller { private readonly IRepositoryService _repositoryService = repositoryService; private readonly ICloneManager _cloneManager = cloneManager; private readonly IProjectService _projectService = projectService; + private readonly IMigrationProgressTracker _progressTracker = progressTracker; public async Task Repositories() { @@ -53,43 +54,46 @@ public async Task PullRequests(Guid projectId) } [HttpGet] - public async Task CloneRepository() + public async Task CloneRepository(Guid operationId = default) { - Projects projects = await _projectService.GetAllProjectsAsync() ?? new(); - return View(projects.Value); + return await CloneFormView(nameof(CloneRepository), _progressTracker.TakeFinished(operationId)); } [HttpPost] - public async Task CloneRepository(Guid templateProjectId, Guid projectId) + public async Task CloneRepository(Guid templateProjectId, Guid projectId, Guid operationId = default) { if (!ModelState.IsValid) { - return await CloneRepository(); + return await CloneFormView(nameof(CloneRepository)); } - await _cloneManager.CloneRepositoriesAsync(templateProjectId, projectId); - ViewBag.SuccessMessage = "Success"; - - return await CloneRepository(); + operationId = await _progressTracker.RunAsync(operationId, "Cloning repositories...", "Repositories cloned successfully.", + progress => _cloneManager.CloneRepositoriesAsync(templateProjectId, projectId, progress)); + return RedirectToAction(nameof(CloneRepository), new { operationId }); } [HttpGet] - public async Task ClonePullRequests() + public async Task ClonePullRequests(Guid operationId = default) { - return await CloneRepository(); + return await CloneFormView(nameof(ClonePullRequests), _progressTracker.TakeFinished(operationId)); } [HttpPost] - public async Task ClonePullRequests(Guid templateProjectId, Guid projectId) + public async Task ClonePullRequests(Guid templateProjectId, Guid projectId, Guid operationId = default) { if (!ModelState.IsValid) { - return await ClonePullRequests(); + return await CloneFormView(nameof(ClonePullRequests)); } - await _cloneManager.CloneGitPullRequestsAsync(templateProjectId, projectId); - ViewBag.SuccessMessage = "Success"; + operationId = await _progressTracker.RunAsync(operationId, "Cloning pull requests...", "Pull requests cloned successfully.", + progress => _cloneManager.CloneGitPullRequestsAsync(templateProjectId, projectId, progress)); + return RedirectToAction(nameof(ClonePullRequests), new { operationId }); + } - return await ClonePullRequests(); + private async Task CloneFormView(string action, MigrationProgress? finishedMigration = null) + { + Projects projects = await _projectService.GetAllProjectsAsync() ?? new(); + return View(action, new CloneFormViewModel(projects.Value, "Repository", action, finishedMigration)); } -} \ No newline at end of file +} diff --git a/CloneDevOpsTemplate/Controllers/TeamController.cs b/CloneDevOpsTemplate/Controllers/TeamController.cs index a8f878a..ce7dd70 100644 --- a/CloneDevOpsTemplate/Controllers/TeamController.cs +++ b/CloneDevOpsTemplate/Controllers/TeamController.cs @@ -7,11 +7,12 @@ namespace CloneDevOpsTemplate.Controllers; [Authorize] -public class TeamController(ITeamsService teamsService, ICloneManager cloneManager, IProjectService projectService) : Controller +public class TeamController(ITeamsService teamsService, ICloneManager cloneManager, IProjectService projectService, IMigrationProgressTracker progressTracker) : Controller { private readonly ITeamsService _teamsService = teamsService; private readonly ICloneManager _cloneManager = cloneManager; private readonly IProjectService _projectService = projectService; + private readonly IMigrationProgressTracker _progressTracker = progressTracker; public async Task Teams() { @@ -46,43 +47,52 @@ public async Task ProjectTeams(Guid projectId) } [HttpGet] - public async Task CloneTeams() + public async Task CloneTeams(Guid operationId = default) { - var projects = await _projectService.GetAllProjectsAsync() ?? new(); - return View(projects.Value); + return await ProjectCloneFormView(nameof(CloneTeams), _progressTracker.TakeFinished(operationId)); } [HttpPost] - public async Task CloneTeams(Guid templateProjectId, Guid projectId) + public async Task CloneTeams(Guid templateProjectId, Guid projectId, Guid operationId = default) { if (!ModelState.IsValid) { - return await CloneTeams(); + return await ProjectCloneFormView(nameof(CloneTeams)); } - await _cloneManager.CloneTeamsAsync(templateProjectId, projectId); - ViewBag.SuccessMessage = "Success"; - - return await CloneTeams(); + operationId = await _progressTracker.RunAsync(operationId, "Cloning teams...", "Teams cloned successfully.", + async progress => await _cloneManager.CloneTeamsAsync(templateProjectId, projectId, progress)); + return RedirectToAction(nameof(CloneTeams), new { operationId }); } [HttpGet] - public async Task CloneTeamFieldValues() + public async Task CloneTeamFieldValues(Guid operationId = default) { - return await Teams(); + return await TeamCloneFormView(nameof(CloneTeamFieldValues), _progressTracker.TakeFinished(operationId)); } [HttpPost] - public async Task CloneTeamFieldValues(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId) + public async Task CloneTeamFieldValues(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId, Guid operationId = default) { if (!ModelState.IsValid) { - return await CloneTeamFieldValues(); + return await TeamCloneFormView(nameof(CloneTeamFieldValues)); } - await _cloneManager.CloneTeamFieldValuesAsync(templateProjectId, projectId, templateTeamId, projectTeamId); - ViewBag.SuccessMessage = "Success"; + operationId = await _progressTracker.RunAsync(operationId, "Cloning team field values...", "Team field values cloned successfully.", + progress => _cloneManager.CloneTeamFieldValuesAsync(templateProjectId, projectId, templateTeamId, projectTeamId, progress)); + return RedirectToAction(nameof(CloneTeamFieldValues), new { operationId }); + } - return await CloneTeamFieldValues(); + private async Task ProjectCloneFormView(string action, MigrationProgress? finishedMigration = null) + { + Projects projects = await _projectService.GetAllProjectsAsync() ?? new(); + return View(action, new CloneFormViewModel(projects.Value, "Team", action, finishedMigration)); + } + + private async Task TeamCloneFormView(string action, MigrationProgress? finishedMigration = null) + { + Teams teams = await _teamsService.GetAllTeamsAsync() ?? new(); + return View(action, new CloneFormViewModel(teams.Value, "Team", action, finishedMigration)); } -} \ No newline at end of file +} diff --git a/CloneDevOpsTemplate/Controllers/TeamSettingsController.cs b/CloneDevOpsTemplate/Controllers/TeamSettingsController.cs index 593836b..ec68921 100644 --- a/CloneDevOpsTemplate/Controllers/TeamSettingsController.cs +++ b/CloneDevOpsTemplate/Controllers/TeamSettingsController.cs @@ -7,11 +7,12 @@ namespace CloneDevOpsTemplate.Controllers; [Authorize] -public class TeamSettingsController(ITeamSettingsService teamSettingsService, ICloneManager cloneManager, ITeamsService teamsService) : Controller +public class TeamSettingsController(ITeamSettingsService teamSettingsService, ICloneManager cloneManager, ITeamsService teamsService, IMigrationProgressTracker progressTracker) : Controller { private readonly ITeamSettingsService _teamSettingsService = teamSettingsService; private readonly ICloneManager _cloneManager = cloneManager; private readonly ITeamsService _teamsService = teamsService; + private readonly IMigrationProgressTracker _progressTracker = progressTracker; public async Task TeamSettings(Guid projectId, Guid teamId) { @@ -54,43 +55,46 @@ public async Task Iterations(Guid projectId, Guid teamId) } [HttpGet] - public async Task CloneTeamSettings() + public async Task CloneTeamSettings(Guid operationId = default) { - var teams = await _teamsService.GetAllTeamsAsync() ?? new(); - return View(teams.Value); + return await CloneFormView(nameof(CloneTeamSettings), _progressTracker.TakeFinished(operationId)); } [HttpPost] - public async Task CloneTeamSettings(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId) + public async Task CloneTeamSettings(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId, Guid operationId = default) { if (!ModelState.IsValid) { - return await CloneTeamSettings(); + return await CloneFormView(nameof(CloneTeamSettings)); } - await _cloneManager.CloneTeamSettingsAsync(templateProjectId, projectId, templateTeamId, projectTeamId); - ViewBag.SuccessMessage = "Success"; - - return await CloneTeamSettings(); + operationId = await _progressTracker.RunAsync(operationId, "Cloning team settings...", "Team settings cloned successfully.", + progress => _cloneManager.CloneTeamSettingsAsync(templateProjectId, projectId, templateTeamId, projectTeamId, progress)); + return RedirectToAction(nameof(CloneTeamSettings), new { operationId }); } [HttpGet] - public async Task CloneTeamIterations() + public async Task CloneTeamIterations(Guid operationId = default) { - return await CloneTeamSettings(); + return await CloneFormView(nameof(CloneTeamIterations), _progressTracker.TakeFinished(operationId)); } [HttpPost] - public async Task CloneTeamIterations(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId) + public async Task CloneTeamIterations(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId, Guid operationId = default) { if (!ModelState.IsValid) { - return await CloneTeamIterations(); + return await CloneFormView(nameof(CloneTeamIterations)); } - await _cloneManager.CloneTeamIterationsAsync(templateProjectId, projectId, templateTeamId, projectTeamId); - ViewBag.SuccessMessage = "Success"; + operationId = await _progressTracker.RunAsync(operationId, "Cloning team iterations...", "Team iterations cloned successfully.", + progress => _cloneManager.CloneTeamIterationsAsync(templateProjectId, projectId, templateTeamId, projectTeamId, progress)); + return RedirectToAction(nameof(CloneTeamIterations), new { operationId }); + } - return await CloneTeamIterations(); + private async Task CloneFormView(string action, MigrationProgress? finishedMigration = null) + { + Teams teams = await _teamsService.GetAllTeamsAsync() ?? new(); + return View(action, new CloneFormViewModel(teams.Value, "TeamSettings", action, finishedMigration)); } } diff --git a/CloneDevOpsTemplate/IServices/IBoardService.cs b/CloneDevOpsTemplate/IServices/IBoardService.cs index 1916043..30f1d37 100644 --- a/CloneDevOpsTemplate/IServices/IBoardService.cs +++ b/CloneDevOpsTemplate/IServices/IBoardService.cs @@ -9,17 +9,17 @@ public interface IBoardService Task GetBoardColumnsAsync(Guid projectId, Guid teamId, Guid boardId); Task UpdateBoardColumnsAsync(Guid projectId, Guid teamId, Guid boardId, BoardColumns boardColumns); - Task MoveBoardColumnsAsync(Guid projectId, Guid projectTeamId, Guid templateProjectId, Guid templateTeamId, Boards projectBoards); + Task MoveBoardColumnsAsync(Guid projectId, Guid projectTeamId, Guid templateProjectId, Guid templateTeamId, Boards projectBoards); Task GetBoardRowsAsync(Guid projectId, Guid teamId, Guid boardId); Task UpdateBoardRowsAsync(Guid projectId, Guid teamId, Guid boardId, BoardRows boardRows); - Task MoveBoardRowsAsync(Guid projectId, Guid projectTeamId, Guid templateProjectId, Guid templateTeamId, Boards projectBoards); + Task MoveBoardRowsAsync(Guid projectId, Guid projectTeamId, Guid templateProjectId, Guid templateTeamId, Boards projectBoards); Task GetCardSettingsAsync(Guid projectId, Guid teamId, Guid boardId); Task UpdateCardSettingsAsync(Guid projectId, Guid teamId, Guid boardId, CardSettings boardCards); - Task MoveCardSettingsAsync(Guid projectId, Guid projectTeamId, Guid templateProjectId, Guid templateTeamId, Boards projectBoards); + Task MoveCardSettingsAsync(Guid projectId, Guid projectTeamId, Guid templateProjectId, Guid templateTeamId, Boards projectBoards); Task GetCardStylesAsync(Guid projectId, Guid teamId, Guid boardId); Task UpdateCardStylesAsync(Guid projectId, Guid teamId, Guid boardId, CardStyles cardStyle); - Task MoveCardStylesAsync(Guid projectId, Guid projectTeamId, Guid templateProjectId, Guid templateTeamId, Boards projectBoards); + Task MoveCardStylesAsync(Guid projectId, Guid projectTeamId, Guid templateProjectId, Guid templateTeamId, Boards projectBoards); } diff --git a/CloneDevOpsTemplate/IServices/IIterationService.cs b/CloneDevOpsTemplate/IServices/IIterationService.cs index 62ee4bc..fa0b142 100644 --- a/CloneDevOpsTemplate/IServices/IIterationService.cs +++ b/CloneDevOpsTemplate/IServices/IIterationService.cs @@ -8,7 +8,7 @@ public interface IIterationService Task GetAsync(Guid projectId, TreeStructureGroup structureGroup, int depth); Task GetAllAsync(Guid projectId, TreeStructureGroup structureGroup); Task CreateAsync(Guid projectId, TreeStructureGroup structureGroup, ClassificationNodeBase classificationNode, string path); - Task CreateAsync(Guid projectId, Iteration classificationNodes, TreeStructureGroup structureGroup, string path); + Task CreateAsync(Guid projectId, Iteration classificationNodes, TreeStructureGroup structureGroup, string path); Task DeleteAsync(Guid projectId, TreeStructureGroup structureGroup, string name); - Task DeleteAsync(Guid projectId, TreeStructureGroup structureGroup, Iteration classificationNodes); + Task DeleteAsync(Guid projectId, TreeStructureGroup structureGroup, Iteration classificationNodes); } diff --git a/CloneDevOpsTemplate/Managers/CloneManager.cs b/CloneDevOpsTemplate/Managers/CloneManager.cs index ac83b9f..8028ea7 100644 --- a/CloneDevOpsTemplate/Managers/CloneManager.cs +++ b/CloneDevOpsTemplate/Managers/CloneManager.cs @@ -13,9 +13,11 @@ public class CloneManager(IProjectService projectService, IIterationService iter private readonly IRepositoryService _repositoryService = repositoryService; private readonly IServiceService _serviceService = serviceService; - public async Task CloneProjectAsync(Guid templateProjectId, string newProjectName, string description, Visibility visibility) + public async Task CloneProjectAsync(Guid templateProjectId, string newProjectName, string description, Visibility visibility, IProgress? progress = null) { + progress?.Report("Reading template project..."); Project templateProject = await _projectService.GetProjectAsync(templateProjectId) ?? new(); + progress?.Report($"Requesting creation of project '{newProjectName}' based on template '{templateProject.Name}'..."); CreateProjectResponse createProjectResponse = await _projectService.CreateProjectAsync( newProjectName, description, @@ -23,14 +25,17 @@ public async Task CloneProjectAsync(Guid templateProjectId, templateProject.Capabilities.Versioncontrol.SourceControlType, visibility ) ?? new(); - Project project = await WaitForProjectCreationAsync(newProjectName); + progress?.Report($"Waiting for project '{newProjectName}' to be ready..."); + Project project = await WaitForProjectCreationAsync(newProjectName, progress); + progress?.Report($"Project '{newProjectName}' is ready."); return new CloneProjectResult { Project = project, TemplateProject = templateProject, ErrorMessage = createProjectResponse.Message }; } - private async Task WaitForProjectCreationAsync(string newProjectName) + private async Task WaitForProjectCreationAsync(string newProjectName, IProgress? progress = null) { var timeout = DateTime.UtcNow.AddMinutes(5); + ProjectState? lastState = null; while (DateTime.UtcNow < timeout) { @@ -40,19 +45,44 @@ private async Task WaitForProjectCreationAsync(string newProjectName) { return project; } + + if (project is not null && project.State != lastState) + { + lastState = project.State; + progress?.Report($"Project '{newProjectName}' state: {project.State}"); + } } throw new TimeoutException("Project creation timed out."); } - public async Task CloneClassificationNodes(Guid templateProjectId, Guid projectId, TreeStructureGroup structureGroup) + public async Task CloneClassificationNodes(Guid templateProjectId, Guid projectId, TreeStructureGroup structureGroup, IProgress? progress = null) { - var classificationNodes = await _iterationService.GetAllAsync(projectId, structureGroup) ?? new(); - await _iterationService.DeleteAsync(projectId, structureGroup, classificationNodes); - var templateClassificationNodes = await _iterationService.GetAllAsync(templateProjectId, structureGroup) ?? new(); - await _iterationService.CreateAsync(projectId, templateClassificationNodes, structureGroup, ""); + var result = new CloneResult(); + var templateClassificationNodes = await _iterationService.GetAllAsync(templateProjectId, structureGroup); + if (templateClassificationNodes is null) + { + AddError(result, progress, $"{structureGroup}: could not read the template project's nodes."); + return result; + } + + var classificationNodes = await _iterationService.GetAllAsync(projectId, structureGroup); + if (classificationNodes is null) + { + AddError(result, progress, $"{structureGroup}: could not read the target project's nodes."); + return result; + } + + progress?.Report($"{structureGroup}: removing {CountChildNodes(classificationNodes)} default node(s)..."); + AddErrors(result, progress, $"{structureGroup}", await _iterationService.DeleteAsync(projectId, structureGroup, classificationNodes)); + progress?.Report($"{structureGroup}: creating {CountChildNodes(templateClassificationNodes)} node(s) from template..."); + AddErrors(result, progress, $"{structureGroup}", await _iterationService.CreateAsync(projectId, templateClassificationNodes, structureGroup, "")); + progress?.Report($"{structureGroup}: done."); + return result; } + private static int CountChildNodes(Iteration node) => node.Children.Sum(child => 1 + CountChildNodes(child)); + private async Task> MapClassificationNodes(Guid templateProjectId, Guid projectId, TreeStructureGroup structureGroup) { var templateClassificationNodes = await _iterationService.GetAllAsync(templateProjectId, structureGroup) ?? new(); @@ -80,77 +110,212 @@ public static void MapClassificationNodes(Iteration templateIterations, Iteratio } } - public async Task CloneTeamsAndSettingsAndBoardsAsync(Project templateProject, Project project) + public async Task CloneTeamsAndSettingsAndBoardsAsync(Project templateProject, Project project, IProgress? progress = null) { - Dictionary mapTeams = await CloneTeamsAsync(templateProject, project); + progress?.Report("Teams: cloning teams from template..."); + var teamsResult = await CloneTeamsAsync(templateProject, project, progress); + var result = CloneResult.Combine(teamsResult); + var mapTeams = teamsResult.TeamMap; + progress?.Report($"Teams: {mapTeams.Count} team(s) mapped."); + int index = 0; foreach (var mappedTeam in mapTeams) { - await CloneTeamSettingsAsync(templateProject.Id, project.Id, mappedTeam.Key, mappedTeam.Value); - await CloneTeamIterationsAsync(templateProject.Id, project.Id, mappedTeam.Key, mappedTeam.Value); - await CloneTeamFieldValuesAsync(templateProject, project, mappedTeam.Key, mappedTeam.Value); - await CloneBoardsAsync(templateProject.Id, project.Id, mappedTeam.Key, mappedTeam.Value); + index++; + var teamName = teamsResult.TemplateTeams.FirstOrDefault(t => t.Id == mappedTeam.Key)?.Name ?? mappedTeam.Key.ToString(); + var prefix = $"Team '{teamName}' ({index}/{mapTeams.Count})"; + var errorPrefix = $"Team '{teamName}'"; + + progress?.Report($"{prefix}: cloning settings..."); + await CloneTeamSettingsCoreAsync(templateProject.Id, project.Id, mappedTeam.Key, mappedTeam.Value, result, errorPrefix, progress); + progress?.Report($"{prefix}: cloning iterations..."); + await CloneTeamIterationsCoreAsync(templateProject.Id, project.Id, mappedTeam.Key, mappedTeam.Value, result, errorPrefix, progress); + progress?.Report($"{prefix}: cloning area field values..."); + await CloneTeamFieldValuesCoreAsync(templateProject, project, mappedTeam.Key, mappedTeam.Value, result, errorPrefix, progress); + progress?.Report($"{prefix}: cloning boards..."); + await CloneBoardsCoreAsync(templateProject.Id, project.Id, mappedTeam.Key, mappedTeam.Value, result, errorPrefix, progress); + progress?.Report($"{prefix}: done."); } + + return result; } - public async Task CloneRepositoriesAsync(Guid templateProjectId, Guid projectId) + public async Task CloneRepositoriesAsync(Guid templateProjectId, Guid projectId, IProgress? progress = null) { - var repositories = await _repositoryService.GetRepositoriesAsync(projectId) ?? new(); - var templateRepositories = await _repositoryService.GetRepositoriesAsync(templateProjectId) ?? new(); + var result = new CloneResult(); + var templateRepositories = await _repositoryService.GetRepositoriesAsync(templateProjectId); + if (templateRepositories is null) + { + AddError(result, progress, "Repositories: could not read the template project's repositories."); + return result; + } + + var repositories = await _repositoryService.GetRepositoriesAsync(projectId); + if (repositories is null) + { + AddError(result, progress, "Repositories: could not read the target project's repositories."); + return result; + } + + int total = templateRepositories.Value.Length; + int completed = 0; + progress?.Report($"Repositories: {total} repository(ies) to clone."); await Parallel.ForEachAsync(templateRepositories.Value, async (templateRepository, ct) => { - var repository = repositories.Value.FirstOrDefault(r => r.Name == templateRepository.Name) - ?? await _repositoryService.CreateRepositoryAsync(projectId, templateRepository.Name) ?? new(); + var name = templateRepository.Name; + var repository = repositories.Value.FirstOrDefault(r => r.Name == name); + if (repository is null) + { + progress?.Report($"Repository '{name}': creating..."); + repository = await _repositoryService.CreateRepositoryAsync(projectId, name); + if (repository is null) + { + AddError(result, progress, $"Repository '{name}': could not be created."); + return; + } + } - if (repository.Size > 0) return; + if (repository.Size > 0) + { + progress?.Report($"Repository '{name}': already has content, skipped ({Interlocked.Increment(ref completed)}/{total})."); + return; + } var serviceModel = (await _serviceService.GetServicesAsync(projectId) ?? new()) - .Value.FirstOrDefault(s => s.Name == templateRepository.Name) - ?? await _serviceService.CreateServiceAsync(templateRepository.Name, templateRepository.RemoteUrl, templateRepository.Name, projectId) ?? new(); + .Value.FirstOrDefault(s => s.Name == name); + if (serviceModel is null) + { + progress?.Report($"Repository '{name}': creating service connection..."); + serviceModel = await _serviceService.CreateServiceAsync(name, templateRepository.RemoteUrl, name, projectId); + if (serviceModel is null) + { + AddError(result, progress, $"Repository '{name}': could not create the service connection."); + return; + } + } + progress?.Report($"Repository '{name}': importing..."); var importRequest = await _repositoryService.CreateImportRequestAsync(projectId, repository.Id, templateRepository.RemoteUrl, serviceModel.Id); - await WaitForImportAsync(projectId, repository.Id, importRequest?.ImportRequestId ?? 0); + if (importRequest is null) + { + AddError(result, progress, $"Repository '{name}': could not start the import."); + return; + } + + var importStatus = await WaitForImportAsync(projectId, repository.Id, importRequest.ImportRequestId, name, progress); + if (importStatus != GitAsyncOperationStatus.Completed) + { + AddError(result, progress, $"Repository '{name}': import {importStatus}."); + return; + } + + progress?.Report($"Repository '{name}': imported ({Interlocked.Increment(ref completed)}/{total})."); }); - await Parallel.ForEachAsync(repositories.Value.Where(r => r.Size == 0), async (repository, ct) => + var emptyRepositories = repositories.Value.Where(r => r.Size == 0).ToArray(); + if (emptyRepositories.Length > 0) + { + progress?.Report($"Repositories: removing {emptyRepositories.Length} empty default repository(ies)..."); + } + + await Parallel.ForEachAsync(emptyRepositories, async (repository, ct) => { - await _repositoryService.DeleteRepositoryAsync(projectId, repository.Id); + var response = await _repositoryService.DeleteRepositoryAsync(projectId, repository.Id); + await CheckResponseAsync(response, result, progress, $"Repository '{repository.Name}': removing"); }); + + return result; } - private async Task WaitForImportAsync(Guid projectId, Guid repositoryId, int importRequestId) + private async Task WaitForImportAsync(Guid projectId, Guid repositoryId, int importRequestId, string repositoryName, IProgress? progress) { var timeout = DateTime.UtcNow.AddMinutes(5); + GitAsyncOperationStatus? lastStatus = null; while (DateTime.UtcNow < timeout) { await Task.Delay(1000); var importRequest = await _repositoryService.GetImportRequestAsync(projectId, repositoryId, importRequestId); - if (importRequest?.Status == GitAsyncOperationStatus.Completed) + if (importRequest?.Status is GitAsyncOperationStatus.Completed or GitAsyncOperationStatus.Failed or GitAsyncOperationStatus.Abandoned) { - return; + return importRequest.Status; + } + + if (importRequest is not null && importRequest.Status != lastStatus) + { + lastStatus = importRequest.Status; + progress?.Report($"Repository '{repositoryName}': import status {importRequest.Status}"); } } - throw new TimeoutException("Project creation timed out."); + throw new TimeoutException($"Import of repository '{repositoryName}' timed out."); } - public async Task> CloneTeamsAsync(Project templateProject, Project project) + public async Task CloneTeamsAsync(Project templateProject, Project project, IProgress? progress = null) { - Teams templateTeams = await _teamsService.GetTeamsAsync(templateProject.Id) ?? new(); - return await _teamsService.CreateTeamFromTemplateAsync(project.Id, templateTeams.Value, templateProject.DefaultTeam.Id, project.DefaultTeam.Id); + Teams? templateTeams = await _teamsService.GetTeamsAsync(templateProject.Id); + if (templateTeams is null) + { + var failed = new CloneTeamsResult(); + AddError(failed, progress, "Teams: could not read the template project's teams."); + return failed; + } + + var teamMap = await _teamsService.CreateTeamFromTemplateAsync(project.Id, templateTeams.Value, templateProject.DefaultTeam.Id, project.DefaultTeam.Id); + var result = new CloneTeamsResult { TemplateTeams = templateTeams.Value, TeamMap = teamMap }; + + // The teams service returns an empty id when a team could not be created. + foreach (var (templateTeamId, _) in teamMap.Where(t => t.Value == Guid.Empty).ToArray()) + { + var teamName = templateTeams.Value.FirstOrDefault(t => t.Id == templateTeamId)?.Name ?? templateTeamId.ToString(); + AddError(result, progress, $"Team '{teamName}': could not be created."); + teamMap.Remove(templateTeamId); + } + + return result; } - public async Task> CloneTeamsAsync(Guid templateProjectId, Guid projectId) + public async Task CloneTeamsAsync(Guid templateProjectId, Guid projectId, IProgress? progress = null) { - Project templateProject = await _projectService.GetProjectAsync(templateProjectId) ?? new(); - Project project = await _projectService.GetProjectAsync(projectId) ?? new(); + var (templateProject, project, error) = await GetProjectsAsync(templateProjectId, projectId); + if (error is not null) + { + var failed = new CloneTeamsResult(); + AddError(failed, progress, error); + return failed; + } + + var result = await CloneTeamsAsync(templateProject, project, progress); + progress?.Report($"Teams: {result.TeamMap.Count} team(s) mapped."); + return result; + } + + private async Task<(Project TemplateProject, Project Project, string? Error)> GetProjectsAsync(Guid templateProjectId, Guid projectId) + { + var templateProject = await _projectService.GetProjectAsync(templateProjectId); + if (templateProject is null) + { + return (new(), new(), "Could not read the template project."); + } + + var project = await _projectService.GetProjectAsync(projectId); + if (project is null) + { + return (new(), new(), "Could not read the target project."); + } + + return (templateProject, project, null); + } - return await CloneTeamsAsync(templateProject, project); + public async Task CloneTeamSettingsAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId, IProgress? progress = null) + { + var result = new CloneResult(); + await CloneTeamSettingsCoreAsync(templateProjectId, projectId, templateTeamId, projectTeamId, result, "Team", progress); + return result; } - public async Task CloneTeamSettingsAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId) + private async Task CloneTeamSettingsCoreAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId, CloneResult result, string prefix, IProgress? progress) { var templateTeamSettings = await _teamSettingsService.GetTeamSettings(templateProjectId, templateTeamId) ?? new(); var iterationMap = await MapClassificationNodes(templateProjectId, projectId, TreeStructureGroup.Iterations); @@ -166,10 +331,18 @@ public async Task CloneTeamSettingsAsync(Guid templateProjectId, Guid projectId, DefaultIterationMacro = templateTeamSettings.DefaultIterationMacro, WorkingDays = templateTeamSettings.WorkingDays }; - await _teamSettingsService.UpdateTeamSettings(projectId, projectTeamId, newTeamSettings); + var response = await _teamSettingsService.UpdateTeamSettings(projectId, projectTeamId, newTeamSettings); + await CheckResponseAsync(response, result, progress, $"{prefix}: updating settings"); + } + + public async Task CloneTeamFieldValuesAsync(Project templateProject, Project project, Guid templateTeamId, Guid projectTeamId, IProgress? progress = null) + { + var result = new CloneResult(); + await CloneTeamFieldValuesCoreAsync(templateProject, project, templateTeamId, projectTeamId, result, "Team", progress); + return result; } - public async Task CloneTeamFieldValuesAsync(Project templateProject, Project project, Guid templateTeamId, Guid projectTeamId) + private async Task CloneTeamFieldValuesCoreAsync(Project templateProject, Project project, Guid templateTeamId, Guid projectTeamId, CloneResult result, string prefix, IProgress? progress) { var teamFieldValues = await _teamSettingsService.GetTeamFieldValues(templateProject.Id, templateTeamId) ?? new(); teamFieldValues.DefaultValue = teamFieldValues.DefaultValue.Replace(templateProject.Name, project.Name); @@ -177,33 +350,66 @@ public async Task CloneTeamFieldValuesAsync(Project templateProject, Project pro { value.Value = value.Value.Replace(templateProject.Name, project.Name); } - await _teamSettingsService.UpdateTeamFieldValues(project.Id, projectTeamId, teamFieldValues); + var response = await _teamSettingsService.UpdateTeamFieldValues(project.Id, projectTeamId, teamFieldValues); + await CheckResponseAsync(response, result, progress, $"{prefix}: updating area field values"); } - public async Task CloneTeamFieldValuesAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId) + public async Task CloneTeamFieldValuesAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId, IProgress? progress = null) { - var templateProject = await _projectService.GetProjectAsync(templateProjectId) ?? new(); - var project = await _projectService.GetProjectAsync(projectId) ?? new(); - await CloneTeamFieldValuesAsync(templateProject, project, templateTeamId, projectTeamId); + var (templateProject, project, error) = await GetProjectsAsync(templateProjectId, projectId); + if (error is not null) + { + var failed = new CloneResult(); + AddError(failed, progress, error); + return failed; + } + + return await CloneTeamFieldValuesAsync(templateProject, project, templateTeamId, projectTeamId, progress); } - public async Task CloneBoardsAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId) + public async Task CloneBoardsAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId, IProgress? progress = null) { - Boards projectBoards = await _boardService.GetBoardsAsync(projectId, projectTeamId) ?? new(); - await Task.WhenAll( + var result = new CloneResult(); + await CloneBoardsCoreAsync(templateProjectId, projectId, templateTeamId, projectTeamId, result, "Team", progress); + return result; + } + + private async Task CloneBoardsCoreAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId, CloneResult result, string prefix, IProgress? progress) + { + Boards? projectBoards = await _boardService.GetBoardsAsync(projectId, projectTeamId); + if (projectBoards is null) + { + AddError(result, progress, $"{prefix}: could not read the target team's boards."); + return; + } + + var moveResults = await Task.WhenAll( _boardService.MoveBoardColumnsAsync(projectId, projectTeamId, templateProjectId, templateTeamId, projectBoards), _boardService.MoveBoardRowsAsync(projectId, projectTeamId, templateProjectId, templateTeamId, projectBoards), _boardService.MoveCardSettingsAsync(projectId, projectTeamId, templateProjectId, templateTeamId, projectBoards), _boardService.MoveCardStylesAsync(projectId, projectTeamId, templateProjectId, templateTeamId, projectBoards) ); + // Each move reads the template boards itself, so a read failure would otherwise be reported four times. + foreach (var error in moveResults.SelectMany(r => r.Errors).Distinct()) + { + AddError(result, progress, $"{prefix}: {error}"); + } } - public async Task CloneTeamIterationsAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId) + public async Task CloneTeamIterationsAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId, IProgress? progress = null) + { + var result = new CloneResult(); + await CloneTeamIterationsCoreAsync(templateProjectId, projectId, templateTeamId, projectTeamId, result, "Team", progress); + return result; + } + + private async Task CloneTeamIterationsCoreAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId, CloneResult result, string prefix, IProgress? progress) { var oldIterations = await _teamSettingsService.GetIterations(projectId, projectTeamId) ?? new(); foreach (var iteration in oldIterations.Value) { - await _teamSettingsService.DeleteIteration(projectId, projectTeamId, iteration.Id); + var response = await _teamSettingsService.DeleteIteration(projectId, projectTeamId, iteration.Id); + await CheckResponseAsync(response, result, progress, $"{prefix}: removing iteration '{iteration.Name}'"); } var iterations = await _teamSettingsService.GetIterations(templateProjectId, templateTeamId) ?? new(); @@ -212,20 +418,43 @@ public async Task CloneTeamIterationsAsync(Guid templateProjectId, Guid projectI { if (iterationMap.TryGetValue(iteration.Id, out var mappedIterationId)) { - await _teamSettingsService.CreateIteration(projectId, projectTeamId, mappedIterationId); + var response = await _teamSettingsService.CreateIteration(projectId, projectTeamId, mappedIterationId); + await CheckResponseAsync(response, result, progress, $"{prefix}: adding iteration '{iteration.Name}'"); } } } - public async Task CloneGitPullRequestsAsync(Guid templateProjectId, Guid projectId) + public async Task CloneGitPullRequestsAsync(Guid templateProjectId, Guid projectId, IProgress? progress = null) { - var templatePullRequests = await _repositoryService.GetGitPullRequestAsync(templateProjectId) ?? new(); + var result = new CloneResult(); + var templatePullRequests = await _repositoryService.GetGitPullRequestAsync(templateProjectId); + if (templatePullRequests is null) + { + AddError(result, progress, "Pull requests: could not read the template project's pull requests."); + return result; + } + var mappedRespositories = await MapRepositories(templateProjectId, projectId); + int total = templatePullRequests.Value.Length; + progress?.Report($"Pull requests: {total} pull request(s) to clone."); + + int index = 0; foreach (var templatePullRequest in templatePullRequests.Value) { - var repository = mappedRespositories.GetValueOrDefault(templatePullRequest.Repository.Id); - await _repositoryService.CreateGitPullRequestAsync(projectId, repository, templatePullRequest); + index++; + var label = $"Pull request '{templatePullRequest.Title}'"; + progress?.Report($"{label} ({index}/{total}): creating..."); + if (!mappedRespositories.TryGetValue(templatePullRequest.Repository.Id, out var repository)) + { + AddError(result, progress, $"{label}: repository '{templatePullRequest.Repository.Name}' not found in the target project."); + continue; + } + + var response = await _repositoryService.CreateGitPullRequestAsync(projectId, repository, templatePullRequest); + await CheckResponseAsync(response, result, progress, $"{label}: creating"); } + + return result; } public async Task> MapRepositories(Guid templateProjectId, Guid projectId) @@ -245,4 +474,27 @@ public async Task> MapRepositories(Guid templateProjectId return mappedRespositories; } -} \ No newline at end of file + + private static void AddError(CloneResult result, IProgress? progress, string error) + { + result.AddError(error); + progress?.Report($"Error: {error}"); + } + + private static void AddErrors(CloneResult result, IProgress? progress, string prefix, CloneResult source) + { + foreach (var error in source.Errors) + { + AddError(result, progress, $"{prefix}: {error}"); + } + } + + private static async Task CheckResponseAsync(HttpResponseMessage? response, CloneResult result, IProgress? progress, string action) + { + var responseResult = new CloneResult(); + if (!await responseResult.CheckResponseAsync(response, action)) + { + AddError(result, progress, responseResult.Errors[0]); + } + } +} diff --git a/CloneDevOpsTemplate/Managers/ICloneManager.cs b/CloneDevOpsTemplate/Managers/ICloneManager.cs index d00eb7c..f466469 100644 --- a/CloneDevOpsTemplate/Managers/ICloneManager.cs +++ b/CloneDevOpsTemplate/Managers/ICloneManager.cs @@ -4,16 +4,16 @@ namespace CloneDevOpsTemplate.Managers; public interface ICloneManager { - Task CloneClassificationNodes(Guid templateProjectId, Guid projectId, TreeStructureGroup structureGroup); - Task CloneBoardsAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId); - Task CloneProjectAsync(Guid templateProjectId, string newProjectName, string description, Visibility visibility); - Task CloneRepositoriesAsync(Guid templateProjectId, Guid projectId); - Task CloneTeamFieldValuesAsync(Project templateProject, Project project, Guid templateTeamId, Guid projectTeamId); - Task CloneTeamFieldValuesAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId); - Task> CloneTeamsAsync(Project templateProject, Project project); - Task> CloneTeamsAsync(Guid templateProjectId, Guid projectId); - Task CloneTeamsAndSettingsAndBoardsAsync(Project templateProject, Project project); - Task CloneTeamSettingsAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId); - Task CloneTeamIterationsAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId); - Task CloneGitPullRequestsAsync(Guid templateProjectId, Guid projectId); + Task CloneClassificationNodes(Guid templateProjectId, Guid projectId, TreeStructureGroup structureGroup, IProgress? progress = null); + Task CloneBoardsAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId, IProgress? progress = null); + Task CloneProjectAsync(Guid templateProjectId, string newProjectName, string description, Visibility visibility, IProgress? progress = null); + Task CloneRepositoriesAsync(Guid templateProjectId, Guid projectId, IProgress? progress = null); + Task CloneTeamFieldValuesAsync(Project templateProject, Project project, Guid templateTeamId, Guid projectTeamId, IProgress? progress = null); + Task CloneTeamFieldValuesAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId, IProgress? progress = null); + Task CloneTeamsAsync(Project templateProject, Project project, IProgress? progress = null); + Task CloneTeamsAsync(Guid templateProjectId, Guid projectId, IProgress? progress = null); + Task CloneTeamsAndSettingsAndBoardsAsync(Project templateProject, Project project, IProgress? progress = null); + Task CloneTeamSettingsAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId, IProgress? progress = null); + Task CloneTeamIterationsAsync(Guid templateProjectId, Guid projectId, Guid templateTeamId, Guid projectTeamId, IProgress? progress = null); + Task CloneGitPullRequestsAsync(Guid templateProjectId, Guid projectId, IProgress? progress = null); } diff --git a/CloneDevOpsTemplate/Managers/IMigrationProgressTracker.cs b/CloneDevOpsTemplate/Managers/IMigrationProgressTracker.cs new file mode 100644 index 0000000..9754396 --- /dev/null +++ b/CloneDevOpsTemplate/Managers/IMigrationProgressTracker.cs @@ -0,0 +1,16 @@ +using CloneDevOpsTemplate.Models; + +namespace CloneDevOpsTemplate.Managers; + +public interface IMigrationProgressTracker +{ + void Start(Guid operationId, int totalSteps); + void Report(Guid operationId, int step, string message); + void ReportDetail(Guid operationId, string detail); + IProgress CreateDetailReporter(Guid operationId); + void Complete(Guid operationId, string message); + void Fail(Guid operationId, string message); + MigrationProgress? Get(Guid operationId); + MigrationProgress? TakeFinished(Guid operationId); + void Remove(Guid operationId); +} diff --git a/CloneDevOpsTemplate/Managers/MigrationProgressTracker.cs b/CloneDevOpsTemplate/Managers/MigrationProgressTracker.cs new file mode 100644 index 0000000..73a6e5e --- /dev/null +++ b/CloneDevOpsTemplate/Managers/MigrationProgressTracker.cs @@ -0,0 +1,150 @@ +using System.Collections.Concurrent; +using CloneDevOpsTemplate.Models; + +namespace CloneDevOpsTemplate.Managers; + +public class MigrationProgressTracker : IMigrationProgressTracker +{ + public const int MaxDetails = 200; + public static readonly TimeSpan FinishedRetention = TimeSpan.FromMinutes(10); + + private readonly ConcurrentDictionary _progress = new(); + + public void Start(Guid operationId, int totalSteps) + { + if (operationId == Guid.Empty) + { + return; + } + + _progress[operationId] = new MigrationProgress { TotalSteps = totalSteps }; + } + + public void Report(Guid operationId, int step, string message) + { + if (operationId == Guid.Empty) + { + return; + } + + var progress = _progress.GetOrAdd(operationId, _ => new MigrationProgress()); + lock (progress) + { + progress.Step = step; + // Guards against a missing or too small Start total so the UI never exceeds 100%. + progress.TotalSteps = Math.Max(progress.TotalSteps, step); + progress.Message = message; + progress.CurrentDetail = null; + AddDetail(progress, $"Step {step} of {progress.TotalSteps}: {message}"); + } + } + + public void ReportDetail(Guid operationId, string detail) + { + if (operationId == Guid.Empty || string.IsNullOrWhiteSpace(detail)) + { + return; + } + + var progress = _progress.GetOrAdd(operationId, _ => new MigrationProgress()); + lock (progress) + { + progress.CurrentDetail = detail; + AddDetail(progress, detail); + } + } + + public void Complete(Guid operationId, string message) => Finish(operationId, MigrationStatus.Succeeded, message); + + public void Fail(Guid operationId, string message) => Finish(operationId, MigrationStatus.Failed, message); + + private void Finish(Guid operationId, MigrationStatus status, string message) + { + if (operationId == Guid.Empty) + { + return; + } + + var progress = _progress.GetOrAdd(operationId, _ => new MigrationProgress()); + lock (progress) + { + progress.Status = status; + if (status == MigrationStatus.Succeeded) + { + progress.Step = progress.TotalSteps; + } + progress.Message = message; + progress.CurrentDetail = null; + progress.FinishedAt = DateTimeOffset.UtcNow; + AddDetail(progress, message); + } + + RemoveExpiredFinished(); + } + + public IProgress CreateDetailReporter(Guid operationId) => new DetailReporter(this, operationId); + + public MigrationProgress? Get(Guid operationId) + { + if (!_progress.TryGetValue(operationId, out var progress)) + { + return null; + } + + lock (progress) + { + return new MigrationProgress + { + Status = progress.Status, + Step = progress.Step, + TotalSteps = progress.TotalSteps, + Message = progress.Message, + CurrentDetail = progress.CurrentDetail, + FinishedAt = progress.FinishedAt, + Details = [.. progress.Details] + }; + } + } + + public MigrationProgress? TakeFinished(Guid operationId) + { + var progress = Get(operationId); + if (progress is null || progress.Status == MigrationStatus.Running) + { + return null; + } + + Remove(operationId); + return progress; + } + + public void Remove(Guid operationId) => _progress.TryRemove(operationId, out _); + + // Finished runs are kept until the result page reads them; drop the ones that were never picked up. + private void RemoveExpiredFinished() + { + var expiredBefore = DateTimeOffset.UtcNow - FinishedRetention; + foreach (var (operationId, progress) in _progress) + { + if (progress.FinishedAt < expiredBefore) + { + _progress.TryRemove(operationId, out _); + } + } + } + + private static void AddDetail(MigrationProgress progress, string message) + { + progress.Details.Add(new MigrationProgressDetail { Timestamp = DateTimeOffset.UtcNow, Step = progress.Step, Message = message }); + if (progress.Details.Count > MaxDetails) + { + progress.Details.RemoveRange(0, progress.Details.Count - MaxDetails); + } + } + + // Reports synchronously, unlike System.Progress, so detail ordering is preserved. + private sealed class DetailReporter(IMigrationProgressTracker tracker, Guid operationId) : IProgress + { + public void Report(string value) => tracker.ReportDetail(operationId, value); + } +} diff --git a/CloneDevOpsTemplate/Managers/MigrationProgressTrackerExtensions.cs b/CloneDevOpsTemplate/Managers/MigrationProgressTrackerExtensions.cs new file mode 100644 index 0000000..bcd39a2 --- /dev/null +++ b/CloneDevOpsTemplate/Managers/MigrationProgressTrackerExtensions.cs @@ -0,0 +1,41 @@ +using CloneDevOpsTemplate.Models; + +namespace CloneDevOpsTemplate.Managers; + +public static class MigrationProgressTrackerExtensions +{ + // The result page reads the outcome from the tracker, so every run needs an operation id. + public static Guid EnsureOperationId(Guid operationId) => operationId == Guid.Empty ? Guid.NewGuid() : operationId; + + /// + /// Runs a single-step clone, records its outcome and returns the operation id to show the result with. + /// + public static async Task RunAsync(this IMigrationProgressTracker tracker, Guid operationId, string stepMessage, string successMessage, Func, Task> clone) + { + operationId = EnsureOperationId(operationId); + tracker.Start(operationId, 1); + tracker.Report(operationId, 1, stepMessage); + + CloneResult result; + try + { + result = await clone(tracker.CreateDetailReporter(operationId)); + } + catch + { + tracker.Remove(operationId); + throw; + } + + if (result.Succeeded) + { + tracker.Complete(operationId, successMessage); + } + else + { + tracker.Fail(operationId, $"{stepMessage.TrimEnd('.')} failed: {result.ErrorMessage}"); + } + + return operationId; + } +} diff --git a/CloneDevOpsTemplate/Models/CloneFormViewModel.cs b/CloneDevOpsTemplate/Models/CloneFormViewModel.cs new file mode 100644 index 0000000..3d6cd9a --- /dev/null +++ b/CloneDevOpsTemplate/Models/CloneFormViewModel.cs @@ -0,0 +1,3 @@ +namespace CloneDevOpsTemplate.Models; + +public record CloneFormViewModel(TItem[] Items, string Controller, string Action, MigrationProgress? FinishedMigration = null); diff --git a/CloneDevOpsTemplate/Models/CloneResult.cs b/CloneDevOpsTemplate/Models/CloneResult.cs new file mode 100644 index 0000000..1b5b35b --- /dev/null +++ b/CloneDevOpsTemplate/Models/CloneResult.cs @@ -0,0 +1,88 @@ +using System.Net.Http.Json; +using System.Text.Json; + +namespace CloneDevOpsTemplate.Models; + +public class CloneResult +{ + private readonly List _errors = []; + + public IReadOnlyList Errors + { + get + { + lock (_errors) + { + return [.. _errors]; + } + } + } + + public bool Succeeded => Errors.Count == 0; + + public string? ErrorMessage => Succeeded ? null : string.Join(" ", Errors); + + // Thread-safe, because repositories are cloned in parallel. + public void AddError(string error) + { + lock (_errors) + { + _errors.Add(error); + } + } + + public async Task CheckResponseAsync(HttpResponseMessage? response, string action) + { + if (response?.IsSuccessStatusCode == true) + { + return true; + } + + AddError($"{action} failed ({await DescribeFailureAsync(response)})."); + return false; + } + + public static async Task DescribeFailureAsync(HttpResponseMessage? response) + { + if (response is null) + { + return "no response"; + } + + var status = $"{(int)response.StatusCode} {response.ReasonPhrase}".TrimEnd(); + try + { + var error = await response.Content.ReadFromJsonAsync(); + if (!string.IsNullOrWhiteSpace(error?.Message)) + { + return $"{status}: {error.Message}"; + } + } + catch (Exception ex) when (ex is JsonException or NotSupportedException) + { + // The body is not an Azure DevOps error payload; the status code is enough. + } + + return status; + } + + public static CloneResult FromError(string? error) + { + var result = new CloneResult(); + if (!string.IsNullOrWhiteSpace(error)) + { + result.AddError(error); + } + return result; + } + + public static CloneResult Combine(params IEnumerable results) + { + var combined = new CloneResult(); + foreach (var error in results.SelectMany(r => r.Errors)) + { + combined.AddError(error); + } + return combined; + } +} diff --git a/CloneDevOpsTemplate/Models/CloneTeamsResult.cs b/CloneDevOpsTemplate/Models/CloneTeamsResult.cs new file mode 100644 index 0000000..cae7fc8 --- /dev/null +++ b/CloneDevOpsTemplate/Models/CloneTeamsResult.cs @@ -0,0 +1,7 @@ +namespace CloneDevOpsTemplate.Models; + +public class CloneTeamsResult : CloneResult +{ + public Team[] TemplateTeams { get; init; } = []; + public Dictionary TeamMap { get; init; } = []; +} diff --git a/CloneDevOpsTemplate/Models/MigrationProgress.cs b/CloneDevOpsTemplate/Models/MigrationProgress.cs new file mode 100644 index 0000000..7cf9ef9 --- /dev/null +++ b/CloneDevOpsTemplate/Models/MigrationProgress.cs @@ -0,0 +1,29 @@ +using System.Text.Json.Serialization; + +namespace CloneDevOpsTemplate.Models; + +public class MigrationProgress +{ + public MigrationStatus Status { get; set; } + public int Step { get; set; } + public int TotalSteps { get; set; } + public string Message { get; set; } = string.Empty; + public string? CurrentDetail { get; set; } + public DateTimeOffset? FinishedAt { get; set; } + public List Details { get; set; } = []; +} + +public class MigrationProgressDetail +{ + public DateTimeOffset Timestamp { get; set; } + public int Step { get; set; } + public string Message { get; set; } = string.Empty; +} + +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum MigrationStatus +{ + Running, + Succeeded, + Failed +} diff --git a/CloneDevOpsTemplate/Models/MigrationProgressPanelViewModel.cs b/CloneDevOpsTemplate/Models/MigrationProgressPanelViewModel.cs new file mode 100644 index 0000000..ab70967 --- /dev/null +++ b/CloneDevOpsTemplate/Models/MigrationProgressPanelViewModel.cs @@ -0,0 +1,3 @@ +namespace CloneDevOpsTemplate.Models; + +public record MigrationProgressPanelViewModel(Guid OperationId, string FormId, string SubmitButtonId, MigrationProgress? FinishedMigration); diff --git a/CloneDevOpsTemplate/Program.cs b/CloneDevOpsTemplate/Program.cs index 591469e..fa28d34 100644 --- a/CloneDevOpsTemplate/Program.cs +++ b/CloneDevOpsTemplate/Program.cs @@ -34,6 +34,7 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); +builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/CloneDevOpsTemplate/Services/BoardService.cs b/CloneDevOpsTemplate/Services/BoardService.cs index ca9ae73..651a52f 100644 --- a/CloneDevOpsTemplate/Services/BoardService.cs +++ b/CloneDevOpsTemplate/Services/BoardService.cs @@ -33,11 +33,12 @@ public Task UpdateBoardColumnsAsync(Guid projectId, Guid te }); } - public Task MoveBoardColumnsAsync(Guid projectId, Guid projectTeamId, Guid templateProjectId, Guid templateTeamId, Boards projectBoards) + public Task MoveBoardColumnsAsync(Guid projectId, Guid projectTeamId, Guid templateProjectId, Guid templateTeamId, Boards projectBoards) { return ForAllMatchingBoards(templateProjectId, templateTeamId, projectBoards, - async (templateBoardId, matchingProjectBoardId) => + async (templateBoard, matchingProjectBoardId, result) => { + var templateBoardId = templateBoard.Id; BoardColumns currentBoardColumns = await GetBoardColumnsAsync(projectId, projectTeamId, matchingProjectBoardId) ?? new(); var incomingColumnId = currentBoardColumns.Value.FirstOrDefault(c => c.ColumnType == BoardColumnType.Incoming)?.Id; var outgoingColumnId = currentBoardColumns.Value.FirstOrDefault(c => c.ColumnType == BoardColumnType.Outgoing)?.Id; @@ -59,7 +60,8 @@ public Task MoveBoardColumnsAsync(Guid projectId, Guid projectTeamId, Guid templ } } - await UpdateBoardColumnsAsync(projectId, projectTeamId, matchingProjectBoardId, templateBoardColumns); + var response = await UpdateBoardColumnsAsync(projectId, projectTeamId, matchingProjectBoardId, templateBoardColumns); + await result.CheckResponseAsync(response, $"Board '{templateBoard.Name}': updating columns"); }); } @@ -76,13 +78,14 @@ public Task UpdateBoardRowsAsync(Guid projectId, Guid teamI }); } - public Task MoveBoardRowsAsync(Guid projectId, Guid projectTeamId, Guid templateProjectId, Guid templateTeamId, Boards projectBoards) + public Task MoveBoardRowsAsync(Guid projectId, Guid projectTeamId, Guid templateProjectId, Guid templateTeamId, Boards projectBoards) { return ForAllMatchingBoards(templateProjectId, templateTeamId, projectBoards, - async (templateBoardId, matchingProjectBoardId) => + async (templateBoard, matchingProjectBoardId, result) => { - BoardRows templateBoardRows = await GetBoardRowsAsync(templateProjectId, templateTeamId, templateBoardId) ?? new(); - await UpdateBoardRowsAsync(projectId, projectTeamId, matchingProjectBoardId, templateBoardRows); + BoardRows templateBoardRows = await GetBoardRowsAsync(templateProjectId, templateTeamId, templateBoard.Id) ?? new(); + var response = await UpdateBoardRowsAsync(projectId, projectTeamId, matchingProjectBoardId, templateBoardRows); + await result.CheckResponseAsync(response, $"Board '{templateBoard.Name}': updating rows"); }); } @@ -100,13 +103,14 @@ public Task UpdateCardSettingsAsync(Guid projectId, Guid te }); } - public Task MoveCardSettingsAsync(Guid projectId, Guid projectTeamId, Guid templateProjectId, Guid templateTeamId, Boards projectBoards) + public Task MoveCardSettingsAsync(Guid projectId, Guid projectTeamId, Guid templateProjectId, Guid templateTeamId, Boards projectBoards) { return ForAllMatchingBoards(templateProjectId, templateTeamId, projectBoards, - async (templateBoardId, matchingProjectBoardId) => + async (templateBoard, matchingProjectBoardId, result) => { - CardSettings templateBoardCards = await GetCardSettingsAsync(templateProjectId, templateTeamId, templateBoardId) ?? new(); - await UpdateCardSettingsAsync(projectId, projectTeamId, matchingProjectBoardId, templateBoardCards); + CardSettings templateBoardCards = await GetCardSettingsAsync(templateProjectId, templateTeamId, templateBoard.Id) ?? new(); + var response = await UpdateCardSettingsAsync(projectId, projectTeamId, matchingProjectBoardId, templateBoardCards); + await result.CheckResponseAsync(response, $"Board '{templateBoard.Name}': updating card settings"); }); } @@ -124,26 +128,36 @@ public Task UpdateCardStylesAsync(Guid projectId, Guid team }); } - public Task MoveCardStylesAsync(Guid projectId, Guid projectTeamId, Guid templateProjectId, Guid templateTeamId, Boards projectBoards) + public Task MoveCardStylesAsync(Guid projectId, Guid projectTeamId, Guid templateProjectId, Guid templateTeamId, Boards projectBoards) { return ForAllMatchingBoards(templateProjectId, templateTeamId, projectBoards, - async (templateBoardId, matchingProjectBoardId) => + async (templateBoard, matchingProjectBoardId, result) => { - CardStyles templateCardStyles = await GetCardStylesAsync(templateProjectId, templateTeamId, templateBoardId) ?? new(); - await UpdateCardStylesAsync(projectId, projectTeamId, matchingProjectBoardId, templateCardStyles); + CardStyles templateCardStyles = await GetCardStylesAsync(templateProjectId, templateTeamId, templateBoard.Id) ?? new(); + var response = await UpdateCardStylesAsync(projectId, projectTeamId, matchingProjectBoardId, templateCardStyles); + await result.CheckResponseAsync(response, $"Board '{templateBoard.Name}': updating card styles"); }); } - public async Task ForAllMatchingBoards(Guid templateProjectId, Guid templateTeamId, Boards projectBoards, Action moveAction) + public async Task ForAllMatchingBoards(Guid templateProjectId, Guid templateTeamId, Boards projectBoards, Func moveAction) { - Boards templateBoards = await GetBoardsAsync(templateProjectId, templateTeamId) ?? new(); + var result = new CloneResult(); + Boards? templateBoards = await GetBoardsAsync(templateProjectId, templateTeamId); + if (templateBoards is null) + { + result.AddError("Could not read the template team's boards."); + return result; + } + foreach (BoardValue templateBoard in templateBoards.Value) { var matchingProjectBoard = projectBoards.Value.SingleOrDefault(b => string.Compare(b.Name, templateBoard.Name, StringComparison.InvariantCultureIgnoreCase) == 0); if (matchingProjectBoard != null) { - moveAction(templateBoard.Id, matchingProjectBoard.Id); + await moveAction(templateBoard, matchingProjectBoard.Id, result); } } + + return result; } } diff --git a/CloneDevOpsTemplate/Services/IterationService.cs b/CloneDevOpsTemplate/Services/IterationService.cs index 6428ead..696f61e 100644 --- a/CloneDevOpsTemplate/Services/IterationService.cs +++ b/CloneDevOpsTemplate/Services/IterationService.cs @@ -27,12 +27,24 @@ public async Task CreateAsync(Guid projectId, TreeStructure return await _client.PostAsJsonAsync($"{projectId}/_apis/wit/classificationNodes/{structureGroup}/{path}?api-version=7.1", classificationNode); } - public async Task CreateAsync(Guid projectId, Iteration classificationNodes, TreeStructureGroup structureGroup, string path) + public async Task CreateAsync(Guid projectId, Iteration classificationNodes, TreeStructureGroup structureGroup, string path) + { + var result = new CloneResult(); + await CreateChildrenAsync(projectId, classificationNodes, structureGroup, path, result); + return result; + } + + private async Task CreateChildrenAsync(Guid projectId, Iteration classificationNodes, TreeStructureGroup structureGroup, string path, CloneResult result) { foreach (var classificationNode in classificationNodes.Children) { - await CreateAsync(projectId, structureGroup, classificationNode, path); - await CreateAsync(projectId, classificationNode, structureGroup, classificationNode.Name); + var nodePath = string.IsNullOrEmpty(path) ? classificationNode.Name : $"{path}/{classificationNode.Name}"; + var response = await CreateAsync(projectId, structureGroup, classificationNode, path); + // Children of a node that could not be created would fail too, so skip them. + if (await result.CheckResponseAsync(response, $"Creating '{nodePath}'")) + { + await CreateChildrenAsync(projectId, classificationNode, structureGroup, nodePath, result); + } } } @@ -41,11 +53,14 @@ public async Task DeleteAsync(Guid projectId, TreeStructure return await _client.DeleteAsync($"{projectId}/_apis/wit/classificationNodes/{structureGroup}/{name}?api-version=7.1"); } - public async Task DeleteAsync(Guid projectId, TreeStructureGroup structureGroup, Iteration classificationNodes) + public async Task DeleteAsync(Guid projectId, TreeStructureGroup structureGroup, Iteration classificationNodes) { + var result = new CloneResult(); foreach (var classificationNode in classificationNodes.Children) { - await DeleteAsync(projectId, structureGroup, classificationNode.Name); + var response = await DeleteAsync(projectId, structureGroup, classificationNode.Name); + await result.CheckResponseAsync(response, $"Removing '{classificationNode.Name}'"); } + return result; } } diff --git a/CloneDevOpsTemplate/Views/Boards/CloneBoards.cshtml b/CloneDevOpsTemplate/Views/Boards/CloneBoards.cshtml index 9816e5d..27e5cb9 100644 --- a/CloneDevOpsTemplate/Views/Boards/CloneBoards.cshtml +++ b/CloneDevOpsTemplate/Views/Boards/CloneBoards.cshtml @@ -1,8 +1,8 @@ -@model Team[] +@model CloneFormViewModel @{ ViewData["Title"] = "Clone boards"; }

Clone boards

-@{ await Html.RenderPartialAsync("_CloneByTeam", Tuple.Create(Model, "Boards", "CloneBoards")); } +@{ await Html.RenderPartialAsync("_CloneByTeam", Model); } diff --git a/CloneDevOpsTemplate/Views/Iteration/CloneAreas.cshtml b/CloneDevOpsTemplate/Views/Iteration/CloneAreas.cshtml index 0028e6a..1b9ff18 100644 --- a/CloneDevOpsTemplate/Views/Iteration/CloneAreas.cshtml +++ b/CloneDevOpsTemplate/Views/Iteration/CloneAreas.cshtml @@ -1,4 +1,4 @@ -@model ProjectBase[] +@model CloneFormViewModel @{ ViewData["Title"] = "Clone areas"; } @@ -6,5 +6,5 @@

Clone areas

@{ - await Html.RenderPartialAsync("_CloneByProject", Tuple.Create(Model, "Iteration", "CloneAreas")); + await Html.RenderPartialAsync("_CloneByProject", Model); } diff --git a/CloneDevOpsTemplate/Views/Iteration/CloneIterations.cshtml b/CloneDevOpsTemplate/Views/Iteration/CloneIterations.cshtml index 24f20f7..b8afa46 100644 --- a/CloneDevOpsTemplate/Views/Iteration/CloneIterations.cshtml +++ b/CloneDevOpsTemplate/Views/Iteration/CloneIterations.cshtml @@ -1,4 +1,4 @@ -@model ProjectBase[] +@model CloneFormViewModel @{ ViewData["Title"] = "Clone iterations"; } @@ -6,5 +6,5 @@

Clone iterations

@{ - await Html.RenderPartialAsync("_CloneByProject", Tuple.Create(Model, "Iteration", "CloneIterations")); + await Html.RenderPartialAsync("_CloneByProject", Model); } diff --git a/CloneDevOpsTemplate/Views/Project/CloneProject.cshtml b/CloneDevOpsTemplate/Views/Project/CloneProject.cshtml index 6f361b4..da0d473 100644 --- a/CloneDevOpsTemplate/Views/Project/CloneProject.cshtml +++ b/CloneDevOpsTemplate/Views/Project/CloneProject.cshtml @@ -1,10 +1,8 @@ -@model ProjectBase[] +@model CloneFormViewModel @{ ViewData["Title"] = "Clone project"; }

Clone project

-

@ViewBag.SuccessMessage

- -@{ await Html.RenderPartialAsync("_CreateProjectForm", Tuple.Create(Model, "Project", "CloneProject")); } +@{ await Html.RenderPartialAsync("_CreateProjectForm", Model); } diff --git a/CloneDevOpsTemplate/Views/Project/CreateProject.cshtml b/CloneDevOpsTemplate/Views/Project/CreateProject.cshtml index 6950830..cf6eb07 100644 --- a/CloneDevOpsTemplate/Views/Project/CreateProject.cshtml +++ b/CloneDevOpsTemplate/Views/Project/CreateProject.cshtml @@ -1,8 +1,8 @@ -@model ProjectBase[] +@model CloneFormViewModel @{ ViewData["Title"] = "Create project from template"; }

Create project from template

-@{ await Html.RenderPartialAsync("_CreateProjectForm", Tuple.Create(Model, "Project", "CreateProject")); } +@{ await Html.RenderPartialAsync("_CreateProjectForm", Model); } diff --git a/CloneDevOpsTemplate/Views/Project/_CreateProjectForm.cshtml b/CloneDevOpsTemplate/Views/Project/_CreateProjectForm.cshtml index eedf89a..f44ee64 100644 --- a/CloneDevOpsTemplate/Views/Project/_CreateProjectForm.cshtml +++ b/CloneDevOpsTemplate/Views/Project/_CreateProjectForm.cshtml @@ -1,13 +1,17 @@ -@model Tuple +@model CloneFormViewModel +@{ + var operationId = Guid.NewGuid(); +} @Html.ValidationSummary(false, "", new { @class = "text-danger" }) -@using (Html.BeginForm(Model.Item3, Model.Item2, FormMethod.Post, new { @class = "form-container-clone input-group-lg" })) +@using (Html.BeginForm(Model.Action, Model.Controller, FormMethod.Post, new { @class = "form-container-clone input-group-lg", id = "createProjectForm" })) { + @Html.Hidden("operationId", operationId)
@Html.Label("templateProjectId", "Select a project to clone", new { @class = "col-sm-2 col-form-label" })
- @Html.DropDownList("templateProjectId", new SelectList(Model.Item1, "Id", "Name"), "Select a project", new { @class = "form-select form-control" }) + @Html.DropDownList("templateProjectId", new SelectList(Model.Items, "Id", "Name"), "Select a project", new { @class = "form-select form-control" })
@@ -39,3 +43,5 @@ } + +@{ await Html.RenderPartialAsync("_MigrationProgress", new MigrationProgressPanelViewModel(operationId, "createProjectForm", "createButton", Model.FinishedMigration)); } diff --git a/CloneDevOpsTemplate/Views/Repository/ClonePullRequests.cshtml b/CloneDevOpsTemplate/Views/Repository/ClonePullRequests.cshtml index e7aa999..e4c73ed 100644 --- a/CloneDevOpsTemplate/Views/Repository/ClonePullRequests.cshtml +++ b/CloneDevOpsTemplate/Views/Repository/ClonePullRequests.cshtml @@ -1,4 +1,4 @@ -@model ProjectBase[] +@model CloneFormViewModel @{ ViewData["Title"] = "Clone pull requests"; } @@ -6,5 +6,5 @@

Clone pull requests

@{ - await Html.RenderPartialAsync("_CloneByProject", Tuple.Create(Model, "Repository", "ClonePullRequests")); + await Html.RenderPartialAsync("_CloneByProject", Model); } diff --git a/CloneDevOpsTemplate/Views/Repository/CloneRepository.cshtml b/CloneDevOpsTemplate/Views/Repository/CloneRepository.cshtml index 908bd18..2a6100c 100644 --- a/CloneDevOpsTemplate/Views/Repository/CloneRepository.cshtml +++ b/CloneDevOpsTemplate/Views/Repository/CloneRepository.cshtml @@ -1,8 +1,8 @@ -@model ProjectBase[] +@model CloneFormViewModel @{ ViewData["Title"] = "Clone repository"; }

Clone repository

-@{ await Html.RenderPartialAsync("_CloneByProject", Tuple.Create(Model, "Repository", "CloneRepository")); } +@{ await Html.RenderPartialAsync("_CloneByProject", Model); } diff --git a/CloneDevOpsTemplate/Views/Shared/_CloneByProject.cshtml b/CloneDevOpsTemplate/Views/Shared/_CloneByProject.cshtml index 51b461a..72231e5 100644 --- a/CloneDevOpsTemplate/Views/Shared/_CloneByProject.cshtml +++ b/CloneDevOpsTemplate/Views/Shared/_CloneByProject.cshtml @@ -1,22 +1,24 @@ -@model Tuple - -

@ViewBag.SuccessMessage

+@model CloneFormViewModel +@{ + var operationId = Guid.NewGuid(); +} @Html.ValidationSummary(false, "", new { @class = "text-danger" }) -@using (Html.BeginForm(Model.Item3, Model.Item2, FormMethod.Post, new { @class = "form-container-clone input-group-lg" })) +@using (Html.BeginForm(Model.Action, Model.Controller, FormMethod.Post, new { @class = "form-container-clone input-group-lg", id = "cloneForm" })) { + @Html.Hidden("operationId", operationId)
@Html.Label("templateProjectId", "Select a source project", new { @class = "col-sm-2 col-form-label" })
- @Html.DropDownList("templateProjectId", new SelectList(Model.Item1, "Id", "Name"), "Select a project", new { @class = "form-select form-control" }) + @Html.DropDownList("templateProjectId", new SelectList(Model.Items, "Id", "Name"), "Select a project", new { @class = "form-select form-control" })
@Html.Label("newProjectName", "Select a target project", new { @class = "col-sm-2 col-form-label" })
- @Html.DropDownList("projectId", new SelectList(Model.Item1, "Id", "Name"), "Select a project", new { @class = "form-select form-control" }) + @Html.DropDownList("projectId", new SelectList(Model.Items, "Id", "Name"), "Select a project", new { @class = "form-select form-control" })
@@ -27,3 +29,5 @@ } + +@{ await Html.RenderPartialAsync("_MigrationProgress", new MigrationProgressPanelViewModel(operationId, "cloneForm", "cloneButton", Model.FinishedMigration)); } diff --git a/CloneDevOpsTemplate/Views/Shared/_CloneByTeam.cshtml b/CloneDevOpsTemplate/Views/Shared/_CloneByTeam.cshtml index 99c44d0..15ae3f5 100644 --- a/CloneDevOpsTemplate/Views/Shared/_CloneByTeam.cshtml +++ b/CloneDevOpsTemplate/Views/Shared/_CloneByTeam.cshtml @@ -1,9 +1,10 @@ -@model Tuple - -

@ViewBag.SuccessMessage

+@model CloneFormViewModel +@{ + var operationId = Guid.NewGuid(); +} diff --git a/CloneDevOpsTemplate/Views/Team/CloneTeamFieldValues.cshtml b/CloneDevOpsTemplate/Views/Team/CloneTeamFieldValues.cshtml index 8125706..826ce91 100644 --- a/CloneDevOpsTemplate/Views/Team/CloneTeamFieldValues.cshtml +++ b/CloneDevOpsTemplate/Views/Team/CloneTeamFieldValues.cshtml @@ -1,8 +1,8 @@ -@model Team[] +@model CloneFormViewModel @{ ViewData["Title"] = "Clone team field values"; }

Clone team field values

-@{ await Html.RenderPartialAsync("_CloneByTeam", Tuple.Create(Model, "Team", "CloneTeamFieldValues")); } +@{ await Html.RenderPartialAsync("_CloneByTeam", Model); } diff --git a/CloneDevOpsTemplate/Views/Team/CloneTeams.cshtml b/CloneDevOpsTemplate/Views/Team/CloneTeams.cshtml index 41325bb..fc6dd57 100644 --- a/CloneDevOpsTemplate/Views/Team/CloneTeams.cshtml +++ b/CloneDevOpsTemplate/Views/Team/CloneTeams.cshtml @@ -1,8 +1,8 @@ -@model ProjectBase[] +@model CloneFormViewModel @{ ViewData["Title"] = "Clone teams"; }

Clone teams

-@{ await Html.RenderPartialAsync("_CloneByProject", Tuple.Create(Model, "Team", "CloneTeams")); } +@{ await Html.RenderPartialAsync("_CloneByProject", Model); } diff --git a/CloneDevOpsTemplate/Views/TeamSettings/CloneTeamIterations.cshtml b/CloneDevOpsTemplate/Views/TeamSettings/CloneTeamIterations.cshtml index 7437183..3092d27 100644 --- a/CloneDevOpsTemplate/Views/TeamSettings/CloneTeamIterations.cshtml +++ b/CloneDevOpsTemplate/Views/TeamSettings/CloneTeamIterations.cshtml @@ -1,4 +1,4 @@ -@model Team[] +@model CloneFormViewModel @{ ViewData["Title"] = "Clone team iterations"; } @@ -6,5 +6,5 @@

Clone team iterations

@{ - await Html.RenderPartialAsync("_CloneByTeam", Tuple.Create(Model, "TeamSettings", "CloneTeamIterations")); + await Html.RenderPartialAsync("_CloneByTeam", Model); } diff --git a/CloneDevOpsTemplate/Views/TeamSettings/CloneTeamSettings.cshtml b/CloneDevOpsTemplate/Views/TeamSettings/CloneTeamSettings.cshtml index 223749e..27c3280 100644 --- a/CloneDevOpsTemplate/Views/TeamSettings/CloneTeamSettings.cshtml +++ b/CloneDevOpsTemplate/Views/TeamSettings/CloneTeamSettings.cshtml @@ -1,8 +1,8 @@ -@model Team[] +@model CloneFormViewModel @{ ViewData["Title"] = "Clone team settings"; }

Clone team settings

-@{ await Html.RenderPartialAsync("_CloneByTeam", Tuple.Create(Model, "TeamSettings", "CloneTeamSettings")); } +@{ await Html.RenderPartialAsync("_CloneByTeam", Model); } diff --git a/CloneDevOpsTemplateTest/Controllers/BoardsControllerTest.cs b/CloneDevOpsTemplateTest/Controllers/BoardsControllerTest.cs index 8064406..ab4a309 100644 --- a/CloneDevOpsTemplateTest/Controllers/BoardsControllerTest.cs +++ b/CloneDevOpsTemplateTest/Controllers/BoardsControllerTest.cs @@ -12,6 +12,7 @@ public class BoardsControllerTest private readonly Mock _mockBoardService; private readonly Mock _mockCloneManager; private readonly Mock _mockTeamsService; + private readonly MigrationProgressTracker _progressTracker = new(); private readonly BoardsController _controller; public BoardsControllerTest() @@ -19,7 +20,7 @@ public BoardsControllerTest() _mockBoardService = new Mock(); _mockCloneManager = new Mock(); _mockTeamsService = new Mock(); - _controller = new BoardsController(_mockBoardService.Object, _mockCloneManager.Object, _mockTeamsService.Object); + _controller = new BoardsController(_mockBoardService.Object, _mockCloneManager.Object, _mockTeamsService.Object, _progressTracker); } [Fact] @@ -243,95 +244,110 @@ public async Task CardStyles_ValidModelState_ReturnsCardStylesView() } [Fact] - public async Task CloneBoards_ReturnsTeamsView() + public async Task CloneBoards_Get_ReturnsCloneFormWithItems() { // Arrange - var mockTeams = new Teams - { - Value = - [ - new Team { Id = Guid.NewGuid(), Name = "Team1" }, - new Team { Id = Guid.NewGuid(), Name = "Team2" } - ] - }; - - _mockTeamsService.Setup(s => s.GetAllTeamsAsync()) - .ReturnsAsync(mockTeams); + _mockTeamsService.Setup(s => s.GetAllTeamsAsync()).ReturnsAsync(new Teams { Value = [new Team { Name = "Source" }] }); // Act var result = await _controller.CloneBoards(); // Assert var viewResult = Assert.IsType(result); - var model = Assert.IsType(viewResult.Model); - Assert.Equal(2, model.Length); - Assert.Equal("Team1", model[0].Name); - Assert.Equal("Team2", model[1].Name); + Assert.Equal(nameof(BoardsController.CloneBoards), viewResult.ViewName); + var model = Assert.IsType>(viewResult.Model); + Assert.Equal("Source", Assert.Single(model.Items).Name); + Assert.Equal("Boards", model.Controller); + Assert.Equal(nameof(BoardsController.CloneBoards), model.Action); + Assert.Null(model.FinishedMigration); } [Fact] - public async Task CloneBoards_NullTeams_ReturnsEmptyView() + public async Task CloneBoards_Get_NullItems_ReturnsEmptyCloneForm() { // Arrange - _mockTeamsService.Setup(s => s.GetAllTeamsAsync()) - .ReturnsAsync((Teams)null!); + _mockTeamsService.Setup(s => s.GetAllTeamsAsync()).ReturnsAsync((Teams?)null); // Act var result = await _controller.CloneBoards(); // Assert - var viewResult = Assert.IsType(result); - var model = Assert.IsType(viewResult.Model); - Assert.Empty(model); + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Empty(model.Items); + } + + [Fact] + public async Task CloneBoards_Get_WithFinishedOperation_ShowsItOnce() + { + // Arrange + var operationId = Guid.NewGuid(); + _progressTracker.Fail(operationId, "Boom"); + + // Act + var result = await _controller.CloneBoards(operationId); + + // Assert + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Equal(MigrationStatus.Failed, model.FinishedMigration?.Status); + Assert.Null(_progressTracker.Get(operationId)); } [Fact] - public async Task CloneBoards_InvalidModelState_ReturnsTeamsView() + public async Task CloneBoards_Post_InvalidModelState_ReturnsCloneFormWithoutCloning() { // Arrange + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(), templateTeamId = Guid.NewGuid(), projectTeamId = Guid.NewGuid(); _controller.ModelState.AddModelError("Error", "Invalid model state"); // Act - var result = await _controller.CloneBoards(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()); + var result = await _controller.CloneBoards(templateProjectId, projectId, templateTeamId, projectTeamId); // Assert var viewResult = Assert.IsType(result); - var model = Assert.IsType(viewResult.Model); - Assert.Empty(model); + Assert.Equal(nameof(BoardsController.CloneBoards), viewResult.ViewName); + Assert.IsType>(viewResult.Model); + Assert.Empty(_mockCloneManager.Invocations); } [Fact] - public async Task CloneBoards_ValidModelState_ClonesBoardsAndReturnsTeamsView() + public async Task CloneBoards_Post_Success_CompletesProgressAndRedirects() { // Arrange - var templateProjectId = Guid.NewGuid(); - var projectId = Guid.NewGuid(); - var templateTeamId = Guid.NewGuid(); - var projectTeamId = Guid.NewGuid(); + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(), templateTeamId = Guid.NewGuid(), projectTeamId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + _mockCloneManager.Setup(m => m.CloneBoardsAsync(templateProjectId, projectId, templateTeamId, projectTeamId, It.IsAny?>())).ReturnsAsync(new CloneResult()); - var mockTeams = new Teams - { - Value = - [ - new Team { Id = Guid.NewGuid(), Name = "Team1" }, - new Team { Id = Guid.NewGuid(), Name = "Team2" } - ] - }; + // Act + var result = await _controller.CloneBoards(templateProjectId, projectId, templateTeamId, projectTeamId, operationId); - _mockTeamsService.Setup(s => s.GetAllTeamsAsync()) - .ReturnsAsync(mockTeams); + // Assert + var redirectResult = Assert.IsType(result); + Assert.Equal(nameof(BoardsController.CloneBoards), redirectResult.ActionName); + Assert.Equal(operationId, redirectResult.RouteValues?["operationId"]); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Succeeded, progress?.Status); + Assert.Equal("Boards cloned successfully.", progress?.Message); + _mockCloneManager.Verify(m => m.CloneBoardsAsync(templateProjectId, projectId, templateTeamId, projectTeamId, It.IsAny?>()), Times.Once); + } + + [Fact] + public async Task CloneBoards_Post_Failure_FailsProgressAndRedirects() + { + // Arrange + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(), templateTeamId = Guid.NewGuid(), projectTeamId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + var failure = new CloneResult(); + failure.AddError("Boom"); + _mockCloneManager.Setup(m => m.CloneBoardsAsync(templateProjectId, projectId, templateTeamId, projectTeamId, It.IsAny?>())).ReturnsAsync(failure); // Act - var result = await _controller.CloneBoards(templateProjectId, projectId, templateTeamId, projectTeamId); + var result = await _controller.CloneBoards(templateProjectId, projectId, templateTeamId, projectTeamId, operationId); // Assert - _mockCloneManager.Verify(m => m.CloneBoardsAsync(templateProjectId, projectId, templateTeamId, projectTeamId), Times.Once); - - var viewResult = Assert.IsType(result); - var model = Assert.IsType(viewResult.Model); - Assert.Equal(2, model.Length); - Assert.Equal("Team1", model[0].Name); - Assert.Equal("Team2", model[1].Name); - Assert.Equal("Success", _controller.ViewBag.SuccessMessage); + Assert.IsType(result); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Failed, progress?.Status); + Assert.Equal("Cloning boards failed: Boom", progress?.Message); + Assert.Equal(0, _controller.ModelState.ErrorCount); } -} \ No newline at end of file +} diff --git a/CloneDevOpsTemplateTest/Controllers/IterationControllerTest.cs b/CloneDevOpsTemplateTest/Controllers/IterationControllerTest.cs index c882d45..54d0238 100644 --- a/CloneDevOpsTemplateTest/Controllers/IterationControllerTest.cs +++ b/CloneDevOpsTemplateTest/Controllers/IterationControllerTest.cs @@ -12,6 +12,7 @@ public class IterationControllerTest private readonly Mock _mockIterationService; private readonly Mock _mockCloneManager; private readonly Mock _mockProjectService; + private readonly MigrationProgressTracker _progressTracker = new(); private readonly IterationController _controller; public IterationControllerTest() @@ -19,7 +20,7 @@ public IterationControllerTest() _mockIterationService = new Mock(); _mockCloneManager = new Mock(); _mockProjectService = new Mock(); - _controller = new IterationController(_mockIterationService.Object, _mockCloneManager.Object, _mockProjectService.Object); + _controller = new IterationController(_mockIterationService.Object, _mockCloneManager.Object, _mockProjectService.Object, _progressTracker); } [Fact] @@ -129,138 +130,218 @@ public async Task Areas_ReturnsViewResult_WithNewIteration_WhenModelStateIsInval } [Fact] - public async Task CloneIterations_ReturnsViewResult_WithProjects() + public async Task CloneIterations_Get_ReturnsCloneFormWithItems() { // Arrange - ProjectBase[] expectedProjects = []; - _mockProjectService - .Setup(service => service.GetAllProjectsAsync()) - .ReturnsAsync(new Projects { Value = expectedProjects }); + _mockProjectService.Setup(s => s.GetAllProjectsAsync()).ReturnsAsync(new Projects { Value = [new ProjectBase { Name = "Source" }] }); // Act var result = await _controller.CloneIterations(); // Assert var viewResult = Assert.IsType(result); - Assert.Equal(expectedProjects, viewResult.Model); + Assert.Equal(nameof(IterationController.CloneIterations), viewResult.ViewName); + var model = Assert.IsType>(viewResult.Model); + Assert.Equal("Source", Assert.Single(model.Items).Name); + Assert.Equal("Iteration", model.Controller); + Assert.Equal(nameof(IterationController.CloneIterations), model.Action); + Assert.Null(model.FinishedMigration); } [Fact] - public async Task CloneIterations_ReturnsViewResult_WithEmptyProjects_WhenServiceReturnsNull() + public async Task CloneIterations_Get_NullItems_ReturnsEmptyCloneForm() { // Arrange - _mockProjectService - .Setup(service => service.GetAllProjectsAsync()) - .ReturnsAsync((Projects?)null); + _mockProjectService.Setup(s => s.GetAllProjectsAsync()).ReturnsAsync((Projects?)null); // Act var result = await _controller.CloneIterations(); // Assert - var viewResult = Assert.IsType(result); - Assert.NotNull(viewResult.Model); - var model = Assert.IsType(viewResult.Model); - Assert.Empty(model); + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Empty(model.Items); } [Fact] - public async Task CloneIterations_Post_ReturnsViewResult_WithSuccessMessage_WhenModelStateIsValid() + public async Task CloneIterations_Get_WithFinishedOperation_ShowsItOnce() { // Arrange - var templateProjectId = Guid.NewGuid(); - var projectId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + _progressTracker.Fail(operationId, "Boom"); // Act - var result = await _controller.CloneIterations(templateProjectId, projectId); + var result = await _controller.CloneIterations(operationId); // Assert - Assert.IsType(result); - Assert.Equal("Success", _controller.ViewBag.SuccessMessage); - _mockCloneManager.Verify(manager => manager.CloneClassificationNodes(templateProjectId, projectId, TreeStructureGroup.Iterations), Times.Once); + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Equal(MigrationStatus.Failed, model.FinishedMigration?.Status); + Assert.Null(_progressTracker.Get(operationId)); } [Fact] - public async Task CloneIterations_Post_ReturnsViewResult_WhenModelStateIsInvalid() + public async Task CloneIterations_Post_InvalidModelState_ReturnsCloneFormWithoutCloning() { // Arrange - var templateProjectId = Guid.NewGuid(); - var projectId = Guid.NewGuid(); + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(); _controller.ModelState.AddModelError("Error", "Invalid model state"); // Act var result = await _controller.CloneIterations(templateProjectId, projectId); // Assert - Assert.IsType(result); - Assert.Null(_controller.ViewBag.SuccessMessage); - _mockCloneManager.Verify(manager => manager.CloneClassificationNodes(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + var viewResult = Assert.IsType(result); + Assert.Equal(nameof(IterationController.CloneIterations), viewResult.ViewName); + Assert.IsType>(viewResult.Model); + Assert.Empty(_mockCloneManager.Invocations); + } + + [Fact] + public async Task CloneIterations_Post_Success_CompletesProgressAndRedirects() + { + // Arrange + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + _mockCloneManager.Setup(m => m.CloneClassificationNodes(templateProjectId, projectId, TreeStructureGroup.Iterations, It.IsAny?>())).ReturnsAsync(new CloneResult()); + + // Act + var result = await _controller.CloneIterations(templateProjectId, projectId, operationId); + + // Assert + var redirectResult = Assert.IsType(result); + Assert.Equal(nameof(IterationController.CloneIterations), redirectResult.ActionName); + Assert.Equal(operationId, redirectResult.RouteValues?["operationId"]); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Succeeded, progress?.Status); + Assert.Equal("Iterations cloned successfully.", progress?.Message); + _mockCloneManager.Verify(m => m.CloneClassificationNodes(templateProjectId, projectId, TreeStructureGroup.Iterations, It.IsAny?>()), Times.Once); + } + + [Fact] + public async Task CloneIterations_Post_Failure_FailsProgressAndRedirects() + { + // Arrange + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + var failure = new CloneResult(); + failure.AddError("Boom"); + _mockCloneManager.Setup(m => m.CloneClassificationNodes(templateProjectId, projectId, TreeStructureGroup.Iterations, It.IsAny?>())).ReturnsAsync(failure); + + // Act + var result = await _controller.CloneIterations(templateProjectId, projectId, operationId); + + // Assert + Assert.IsType(result); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Failed, progress?.Status); + Assert.Equal("Cloning iterations failed: Boom", progress?.Message); + Assert.Equal(0, _controller.ModelState.ErrorCount); } [Fact] - public async Task CloneAreas_ReturnsViewResult_WithProjects() + public async Task CloneAreas_Get_ReturnsCloneFormWithItems() { // Arrange - ProjectBase[] expectedProjects = []; - _mockProjectService - .Setup(service => service.GetAllProjectsAsync()) - .ReturnsAsync(new Projects { Value = expectedProjects }); + _mockProjectService.Setup(s => s.GetAllProjectsAsync()).ReturnsAsync(new Projects { Value = [new ProjectBase { Name = "Source" }] }); // Act var result = await _controller.CloneAreas(); // Assert var viewResult = Assert.IsType(result); - Assert.Equal(expectedProjects, viewResult.Model); + Assert.Equal(nameof(IterationController.CloneAreas), viewResult.ViewName); + var model = Assert.IsType>(viewResult.Model); + Assert.Equal("Source", Assert.Single(model.Items).Name); + Assert.Equal("Iteration", model.Controller); + Assert.Equal(nameof(IterationController.CloneAreas), model.Action); + Assert.Null(model.FinishedMigration); } [Fact] - public async Task CloneAreas_ReturnsViewResult_WithEmptyProjects_WhenServiceReturnsNull() + public async Task CloneAreas_Get_NullItems_ReturnsEmptyCloneForm() { // Arrange - _mockProjectService - .Setup(service => service.GetAllProjectsAsync()) - .ReturnsAsync((Projects?)null); + _mockProjectService.Setup(s => s.GetAllProjectsAsync()).ReturnsAsync((Projects?)null); // Act var result = await _controller.CloneAreas(); // Assert - var viewResult = Assert.IsType(result); - Assert.NotNull(viewResult.Model); - var model = Assert.IsType(viewResult.Model); - Assert.Empty(model); + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Empty(model.Items); } [Fact] - public async Task CloneAreas_Post_ReturnsViewResult_WithSuccessMessage_WhenModelStateIsValid() + public async Task CloneAreas_Get_WithFinishedOperation_ShowsItOnce() { // Arrange - var templateProjectId = Guid.NewGuid(); - var projectId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + _progressTracker.Fail(operationId, "Boom"); // Act - var result = await _controller.CloneAreas(templateProjectId, projectId); + var result = await _controller.CloneAreas(operationId); // Assert - Assert.IsType(result); - Assert.Equal("Success", _controller.ViewBag.SuccessMessage); - _mockCloneManager.Verify(manager => manager.CloneClassificationNodes(templateProjectId, projectId, TreeStructureGroup.Areas), Times.Once); + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Equal(MigrationStatus.Failed, model.FinishedMigration?.Status); + Assert.Null(_progressTracker.Get(operationId)); } [Fact] - public async Task CloneAreas_Post_ReturnsViewResult_WhenModelStateIsInvalid() + public async Task CloneAreas_Post_InvalidModelState_ReturnsCloneFormWithoutCloning() { // Arrange - var templateProjectId = Guid.NewGuid(); - var projectId = Guid.NewGuid(); + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(); _controller.ModelState.AddModelError("Error", "Invalid model state"); // Act var result = await _controller.CloneAreas(templateProjectId, projectId); // Assert - Assert.IsType(result); - Assert.Null(_controller.ViewBag.SuccessMessage); - _mockCloneManager.Verify(manager => manager.CloneClassificationNodes(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + var viewResult = Assert.IsType(result); + Assert.Equal(nameof(IterationController.CloneAreas), viewResult.ViewName); + Assert.IsType>(viewResult.Model); + Assert.Empty(_mockCloneManager.Invocations); + } + + [Fact] + public async Task CloneAreas_Post_Success_CompletesProgressAndRedirects() + { + // Arrange + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + _mockCloneManager.Setup(m => m.CloneClassificationNodes(templateProjectId, projectId, TreeStructureGroup.Areas, It.IsAny?>())).ReturnsAsync(new CloneResult()); + + // Act + var result = await _controller.CloneAreas(templateProjectId, projectId, operationId); + + // Assert + var redirectResult = Assert.IsType(result); + Assert.Equal(nameof(IterationController.CloneAreas), redirectResult.ActionName); + Assert.Equal(operationId, redirectResult.RouteValues?["operationId"]); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Succeeded, progress?.Status); + Assert.Equal("Areas cloned successfully.", progress?.Message); + _mockCloneManager.Verify(m => m.CloneClassificationNodes(templateProjectId, projectId, TreeStructureGroup.Areas, It.IsAny?>()), Times.Once); + } + + [Fact] + public async Task CloneAreas_Post_Failure_FailsProgressAndRedirects() + { + // Arrange + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + var failure = new CloneResult(); + failure.AddError("Boom"); + _mockCloneManager.Setup(m => m.CloneClassificationNodes(templateProjectId, projectId, TreeStructureGroup.Areas, It.IsAny?>())).ReturnsAsync(failure); + + // Act + var result = await _controller.CloneAreas(templateProjectId, projectId, operationId); + + // Assert + Assert.IsType(result); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Failed, progress?.Status); + Assert.Equal("Cloning areas failed: Boom", progress?.Message); + Assert.Equal(0, _controller.ModelState.ErrorCount); } -} \ No newline at end of file +} diff --git a/CloneDevOpsTemplateTest/Controllers/ProjectControllerTest.cs b/CloneDevOpsTemplateTest/Controllers/ProjectControllerTest.cs index da310be..2ed7502 100644 --- a/CloneDevOpsTemplateTest/Controllers/ProjectControllerTest.cs +++ b/CloneDevOpsTemplateTest/Controllers/ProjectControllerTest.cs @@ -11,6 +11,7 @@ public class ProjectControllerTest { private readonly Mock _mockProjectService; private readonly Mock _mockCloneManager; + private readonly MigrationProgressTracker _progressTracker = new(); private readonly ProjectController _controller; public ProjectControllerTest() @@ -20,7 +21,8 @@ public ProjectControllerTest() _controller = new ProjectController( _mockProjectService.Object, - _mockCloneManager.Object + _mockCloneManager.Object, + _progressTracker ); } @@ -143,7 +145,27 @@ public async Task CreateProject_InvalidModelState_ReturnsCreateProjectView() // Assert var viewResult = Assert.IsType(result); - Assert.IsType(viewResult.Model); + Assert.Equal(nameof(ProjectController.CreateProject), viewResult.ViewName); + var model = Assert.IsType>(viewResult.Model); + Assert.Equal(nameof(ProjectController.CreateProject), model.Action); + } + + [Fact] + public async Task CreateProject_WithFinishedOperation_ShowsFinishedMigration() + { + // Arrange + var operationId = Guid.NewGuid(); + _progressTracker.Fail(operationId, "Boom"); + + // Act + var result = await _controller.CreateProject(operationId); + + // Assert + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.NotNull(model.FinishedMigration); + Assert.Equal(MigrationStatus.Failed, model.FinishedMigration.Status); + Assert.Equal("Boom", model.FinishedMigration.Message); + Assert.Null(_progressTracker.Get(operationId)); } [Fact] @@ -160,37 +182,44 @@ public async Task CreateProject_ValidInput_RedirectsToProject() string? message = null; _mockCloneManager - .Setup(manager => manager.CloneProjectAsync(templateProjectId, newProjectName, description, visibility)) + .Setup(manager => manager.CloneProjectAsync(templateProjectId, newProjectName, description, visibility, It.IsAny?>())) .ReturnsAsync(new CloneProjectResult { Project = project, TemplateProject = templateProject, ErrorMessage = message }); _mockCloneManager - .Setup(manager => manager.CloneClassificationNodes(templateProjectId, project.Id, TreeStructureGroup.Iterations)) - .Returns(Task.CompletedTask); + .Setup(manager => manager.CloneClassificationNodes(templateProjectId, project.Id, TreeStructureGroup.Iterations, It.IsAny?>())) + .ReturnsAsync(new CloneResult()); + + _mockCloneManager + .Setup(manager => manager.CloneClassificationNodes(templateProjectId, project.Id, TreeStructureGroup.Areas, It.IsAny?>())) + .ReturnsAsync(new CloneResult()); _mockCloneManager - .Setup(manager => manager.CloneClassificationNodes(templateProjectId, project.Id, TreeStructureGroup.Areas)) - .Returns(Task.CompletedTask); + .Setup(manager => manager.CloneTeamsAndSettingsAndBoardsAsync(templateProject, project, It.IsAny?>())) + .ReturnsAsync(new CloneResult()); _mockCloneManager - .Setup(manager => manager.CloneTeamsAndSettingsAndBoardsAsync(templateProject, project)) - .Returns(Task.CompletedTask); + .Setup(manager => manager.CloneRepositoriesAsync(templateProjectId, project.Id, It.IsAny?>())) + .ReturnsAsync(new CloneResult()); _mockCloneManager - .Setup(manager => manager.CloneRepositoriesAsync(templateProjectId, project.Id)) - .Returns(Task.CompletedTask); + .Setup(manager => manager.CloneGitPullRequestsAsync(templateProjectId, project.Id, It.IsAny?>())) + .ReturnsAsync(new CloneResult()); + + var operationId = Guid.NewGuid(); // Act - var result = await _controller.CreateProject(templateProjectId, newProjectName, description, visibility); + var result = await _controller.CreateProject(templateProjectId, newProjectName, description, visibility, operationId); // Assert var redirectResult = Assert.IsType(result); Assert.Equal("Project", redirectResult.ActionName); Assert.NotNull(redirectResult.RouteValues); Assert.Equal(project.Id, redirectResult.RouteValues["projectId"]); + Assert.Null(_progressTracker.Get(operationId)); } [Fact] - public async Task CreateProject_CloneProjectReturnsMessage_ReturnsCreateProjectViewWithError() + public async Task CreateProject_CloneProjectReturnsMessage_FailsProgressAndRedirects() { // Arrange var templateProjectId = Guid.NewGuid(); @@ -203,17 +232,59 @@ public async Task CreateProject_CloneProjectReturnsMessage_ReturnsCreateProjectV string? message = "Error cloning project"; _mockCloneManager - .Setup(manager => manager.CloneProjectAsync(templateProjectId, newProjectName, description, visibility)) + .Setup(manager => manager.CloneProjectAsync(templateProjectId, newProjectName, description, visibility, It.IsAny?>())) .ReturnsAsync(new CloneProjectResult { Project = project, TemplateProject = templateProject, ErrorMessage = message }); + var operationId = Guid.NewGuid(); + // Act - var result = await _controller.CreateProject(templateProjectId, newProjectName, description, visibility); + var result = await _controller.CreateProject(templateProjectId, newProjectName, description, visibility, operationId); // Assert - var viewResult = Assert.IsType(result); - Assert.Empty(viewResult.Model as ProjectBase[] ?? []); - Assert.True(_controller.ModelState.ContainsKey("ErrorMessage")); - Assert.Equal(message, _controller.ModelState["ErrorMessage"]?.Errors?.FirstOrDefault()?.ErrorMessage); + var redirectResult = Assert.IsType(result); + Assert.Equal(nameof(ProjectController.CreateProject), redirectResult.ActionName); + Assert.Equal(operationId, redirectResult.RouteValues?["operationId"]); + Assert.False(_controller.ModelState.ContainsKey("ErrorMessage")); + var progress = _progressTracker.Get(operationId); + Assert.NotNull(progress); + Assert.Equal(MigrationStatus.Failed, progress.Status); + Assert.Equal($"Creating project failed: {message}", progress.Message); + Assert.Equal(1, progress.Step); + _mockCloneManager.Verify(manager => manager.CloneClassificationNodes(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny?>()), Times.Never); + _mockCloneManager.Verify(manager => manager.CloneGitPullRequestsAsync(It.IsAny(), It.IsAny(), It.IsAny?>()), Times.Never); + } + + [Fact] + public async Task CreateProject_StepReturnsErrors_FailsAtThatStepAndSkipsRemainingSteps() + { + // Arrange + var templateProjectId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + var project = new Project { Id = Guid.NewGuid() }; + + _mockCloneManager + .Setup(manager => manager.CloneProjectAsync(templateProjectId, "New Project", "Description", Visibility.Private, It.IsAny?>())) + .ReturnsAsync(new CloneProjectResult { Project = project, TemplateProject = new Project() }); + _mockCloneManager + .Setup(manager => manager.CloneClassificationNodes(templateProjectId, project.Id, TreeStructureGroup.Iterations, It.IsAny?>())) + .ReturnsAsync(CloneResult.FromError("Iterations: could not read the template project's nodes.")); + _mockCloneManager + .Setup(manager => manager.CloneClassificationNodes(templateProjectId, project.Id, TreeStructureGroup.Areas, It.IsAny?>())) + .ReturnsAsync(new CloneResult()); + + // Act + var result = await _controller.CreateProject(templateProjectId, "New Project", "Description", Visibility.Private, operationId); + + // Assert + var redirectResult = Assert.IsType(result); + Assert.Equal(nameof(ProjectController.CreateProject), redirectResult.ActionName); + var progress = _progressTracker.Get(operationId); + Assert.NotNull(progress); + Assert.Equal(MigrationStatus.Failed, progress.Status); + Assert.Equal(2, progress.Step); + Assert.Equal("Cloning iterations and areas failed: Iterations: could not read the template project's nodes.", progress.Message); + _mockCloneManager.Verify(manager => manager.CloneTeamsAndSettingsAndBoardsAsync(It.IsAny(), It.IsAny(), It.IsAny?>()), Times.Never); + _mockCloneManager.Verify(manager => manager.CloneGitPullRequestsAsync(It.IsAny(), It.IsAny(), It.IsAny?>()), Times.Never); } [Fact] @@ -228,25 +299,52 @@ public async Task CloneProject_ReturnsViewWithProjects() // Assert var viewResult = Assert.IsType(result); - Assert.Equal(projects.Value, viewResult.Model); + var model = Assert.IsType>(viewResult.Model); + Assert.Equal(projects.Value, model.Items); + Assert.Equal("Project", model.Controller); + Assert.Equal(nameof(ProjectController.CloneProject), model.Action); + Assert.Null(model.FinishedMigration); } [Fact] - public async Task CloneProject_InvalidModelState_ReturnsDefaultView() + public async Task CloneProject_WithCompletedOperation_ShowsFinishedMigrationOnce() { // Arrange - _controller.ModelState.AddModelError("Error", "Invalid model state"); + var operationId = Guid.NewGuid(); + _progressTracker.Start(operationId, 1); + _progressTracker.Complete(operationId, "Done"); // Act - var result = await _controller.CloneProject(); + var firstResult = await _controller.CloneProject(operationId); + var firstModel = Assert.IsType>(Assert.IsType(firstResult).Model); + var firstFinishedMigration = firstModel.FinishedMigration; + var secondResult = await _controller.CloneProject(operationId); // Assert - var viewResult = Assert.IsType(result); - Assert.IsType(viewResult.Model); + Assert.NotNull(firstFinishedMigration); + Assert.Equal("Done", firstFinishedMigration.Message); + var secondModel = Assert.IsType>(Assert.IsType(secondResult).Model); + Assert.Null(secondModel.FinishedMigration); + } + + [Fact] + public async Task CloneProject_WithRunningOperation_DoesNotShowOrRemoveIt() + { + // Arrange + var operationId = Guid.NewGuid(); + _progressTracker.Start(operationId, 1); + + // Act + var result = await _controller.CloneProject(operationId); + + // Assert + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Null(model.FinishedMigration); + Assert.NotNull(_progressTracker.Get(operationId)); } [Fact] - public async Task CloneProject_InvalidModelState_ReturnsProjectsView() + public async Task CloneProject_InvalidModelState_ReturnsCloneProjectView() { // Arrange _controller.ModelState.AddModelError("Error", "Invalid model state"); @@ -256,51 +354,98 @@ public async Task CloneProject_InvalidModelState_ReturnsProjectsView() // Assert var viewResult = Assert.IsType(result); + Assert.Equal(nameof(ProjectController.CloneProject), viewResult.ViewName); Assert.True(_controller.ModelState.ContainsKey("Error")); - Assert.IsType(viewResult.Model); + Assert.IsType>(viewResult.Model); + _mockCloneManager.Verify(manager => manager.CloneProjectAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny?>()), Times.Never); } [Fact] - public async Task CloneProject_CloneProjectReturnsMessage_AddsErrorMessageAndReturnsProjectsView() + public async Task CloneProject_CloneProjectReturnsMessage_FailsProgressAndRedirects() { // Arrange var templateProjectId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); var newProjectName = "New Project"; var description = "Description"; var visibility = Visibility.Private; var message = "Error cloning project"; _mockCloneManager - .Setup(manager => manager.CloneProjectAsync(templateProjectId, newProjectName, description, visibility)) + .Setup(manager => manager.CloneProjectAsync(templateProjectId, newProjectName, description, visibility, It.IsAny?>())) .ReturnsAsync(new CloneProjectResult { Project = null!, TemplateProject = null!, ErrorMessage = message }); // Act - var result = await _controller.CloneProject(templateProjectId, newProjectName, description, visibility); + var result = await _controller.CloneProject(templateProjectId, newProjectName, description, visibility, operationId); // Assert - Assert.IsType(result); - Assert.True(_controller.ModelState.ContainsKey("ErrorMessage")); - Assert.Equal(message, _controller.ModelState["ErrorMessage"]?.Errors?.FirstOrDefault()?.ErrorMessage); + var redirectResult = Assert.IsType(result); + Assert.Equal(nameof(ProjectController.CloneProject), redirectResult.ActionName); + Assert.Equal(operationId, redirectResult.RouteValues?["operationId"]); + Assert.False(_controller.ModelState.ContainsKey("ErrorMessage")); + var progress = _progressTracker.Get(operationId); + Assert.NotNull(progress); + Assert.Equal(MigrationStatus.Failed, progress.Status); + Assert.Equal($"Creating project failed: {message}", progress.Message); } [Fact] - public async Task CloneProject_CloneProjectSuccess_AddsSuccessMessageAndReturnsProjectsView() + public async Task CloneProject_WithoutOperationId_GeneratesOneSoResultIsTracked() + { + // Arrange + _mockCloneManager + .Setup(manager => manager.CloneProjectAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny?>())) + .ReturnsAsync(new CloneProjectResult { Project = null!, TemplateProject = null!, ErrorMessage = null }); + + // Act + var result = await _controller.CloneProject(Guid.NewGuid(), "New Project", "Description", Visibility.Private); + + // Assert + var redirectResult = Assert.IsType(result); + var operationId = Assert.IsType(redirectResult.RouteValues?["operationId"]); + Assert.NotEqual(Guid.Empty, operationId); + Assert.Equal(MigrationStatus.Succeeded, _progressTracker.Get(operationId)?.Status); + } + + [Fact] + public async Task CloneProject_CloneProjectThrows_RemovesProgress() + { + // Arrange + var operationId = Guid.NewGuid(); + _mockCloneManager + .Setup(manager => manager.CloneProjectAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny?>())) + .ThrowsAsync(new TimeoutException()); + + // Act & Assert + await Assert.ThrowsAsync(() => _controller.CloneProject(Guid.NewGuid(), "New Project", "Description", Visibility.Private, operationId)); + Assert.Null(_progressTracker.Get(operationId)); + } + + [Fact] + public async Task CloneProject_CloneProjectSuccess_CompletesProgressAndRedirects() { // Arrange var templateProjectId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); var newProjectName = "New Project"; var description = "Description"; var visibility = Visibility.Private; _mockCloneManager - .Setup(manager => manager.CloneProjectAsync(templateProjectId, newProjectName, description, visibility)) + .Setup(manager => manager.CloneProjectAsync(templateProjectId, newProjectName, description, visibility, It.IsAny?>())) .ReturnsAsync(new CloneProjectResult { Project = null!, TemplateProject = null!, ErrorMessage = null }); // Act - var result = await _controller.CloneProject(templateProjectId, newProjectName, description, visibility); + var result = await _controller.CloneProject(templateProjectId, newProjectName, description, visibility, operationId); // Assert - Assert.IsType(result); - Assert.Equal("Success", _controller.ViewBag.SuccessMessage); + var redirectResult = Assert.IsType(result); + Assert.Equal(nameof(ProjectController.CloneProject), redirectResult.ActionName); + Assert.Equal(operationId, redirectResult.RouteValues?["operationId"]); + + var progress = _progressTracker.Get(operationId); + Assert.NotNull(progress); + Assert.Equal(MigrationStatus.Succeeded, progress.Status); + Assert.Equal("Project 'New Project' cloned successfully.", progress.Message); } -} \ No newline at end of file +} diff --git a/CloneDevOpsTemplateTest/Controllers/RepositoryControllerTest.cs b/CloneDevOpsTemplateTest/Controllers/RepositoryControllerTest.cs index 4b07bf4..fea68a9 100644 --- a/CloneDevOpsTemplateTest/Controllers/RepositoryControllerTest.cs +++ b/CloneDevOpsTemplateTest/Controllers/RepositoryControllerTest.cs @@ -12,6 +12,7 @@ public class RepositoryControllerTest private readonly Mock _mockRepositoryService; private readonly Mock _mockCloneManager; private readonly Mock _mockProjectService; + private readonly MigrationProgressTracker _progressTracker = new(); private readonly RepositoryController _controller; public RepositoryControllerTest() @@ -19,7 +20,7 @@ public RepositoryControllerTest() _mockRepositoryService = new Mock(); _mockCloneManager = new Mock(); _mockProjectService = new Mock(); - _controller = new RepositoryController(_mockRepositoryService.Object, _mockCloneManager.Object, _mockProjectService.Object); + _controller = new RepositoryController(_mockRepositoryService.Object, _mockCloneManager.Object, _mockProjectService.Object, _progressTracker); } [Fact] @@ -124,199 +125,269 @@ public async Task ProjectRepositories_ReturnsViewWithEmptyRepositories_WhenServi } [Fact] - public async Task CloneRepository_ReturnsViewWithProjects() + public async Task PullRequests_InvalidModelState_ReturnsDefaultView() { // Arrange - var mockProjects = new Projects { Value = Array.Empty() }; - _mockProjectService - .Setup(service => service.GetAllProjectsAsync()) - .ReturnsAsync(mockProjects); + _controller.ModelState.AddModelError("Error", "Invalid model state"); // Act - var result = await _controller.CloneRepository(); + var result = await _controller.PullRequests(Guid.NewGuid()); // Assert var viewResult = Assert.IsType(result); - Assert.Equal(mockProjects.Value, viewResult.Model); + var viewModel = Assert.IsType(viewResult.Model); + Assert.Empty(viewModel); } [Fact] - public async Task CloneRepository_ReturnsViewWithEmptyProjects_WhenServiceReturnsNull() + public async Task PullRequests_ReturnsViewWithPullRequests() { // Arrange - _mockProjectService - .Setup(service => service.GetAllProjectsAsync()) - .ReturnsAsync((Projects?)null); + var projectId = Guid.NewGuid(); + var mockPullRequests = new GitPullRequests { Value = Array.Empty() }; + _mockRepositoryService + .Setup(service => service.GetGitPullRequestAsync(projectId)) + .ReturnsAsync(mockPullRequests); // Act - var result = await _controller.CloneRepository(); + var result = await _controller.PullRequests(projectId); // Assert var viewResult = Assert.IsType(result); - var viewModel = Assert.IsType(viewResult.Model); - Assert.Empty(viewModel); + Assert.Equal(mockPullRequests.Value, viewResult.Model); } [Fact] - public async Task CloneRepository_InvalidModelState_ReturnsViewWithProjects() + public async Task PullRequests_ReturnsViewWithEmptyPullRequests_WhenServiceReturnsNull() { // Arrange - _controller.ModelState.AddModelError("Error", "Invalid model state"); - var mockProjects = new Projects { Value = [] }; - _mockProjectService - .Setup(service => service.GetAllProjectsAsync()) - .ReturnsAsync(mockProjects); + var projectId = Guid.NewGuid(); + _mockRepositoryService + .Setup(service => service.GetGitPullRequestAsync(projectId)) + .ReturnsAsync((GitPullRequests?)null); // Act - var result = await _controller.CloneRepository(Guid.NewGuid(), Guid.NewGuid()); + var result = await _controller.PullRequests(projectId); // Assert var viewResult = Assert.IsType(result); - Assert.Equal(mockProjects.Value, viewResult.Model); + var viewModel = Assert.IsType(viewResult.Model); + Assert.Empty(viewModel); } [Fact] - public async Task CloneRepository_ValidModelState_ClonesRepositoriesAndReturnsViewWithProjects() + public async Task CloneRepository_Get_ReturnsCloneFormWithItems() { // Arrange - var templateProjectId = Guid.NewGuid(); - var projectId = Guid.NewGuid(); - var mockProjects = new Projects { Value = [] }; - _mockProjectService - .Setup(service => service.GetAllProjectsAsync()) - .ReturnsAsync(mockProjects); + _mockProjectService.Setup(s => s.GetAllProjectsAsync()).ReturnsAsync(new Projects { Value = [new ProjectBase { Name = "Source" }] }); // Act - var result = await _controller.CloneRepository(templateProjectId, projectId); + var result = await _controller.CloneRepository(); // Assert - _mockCloneManager.Verify(manager => manager.CloneRepositoriesAsync(templateProjectId, projectId), Times.Once); var viewResult = Assert.IsType(result); - Assert.Equal(mockProjects.Value, viewResult.Model); - Assert.Equal("Success", _controller.ViewBag.SuccessMessage); + Assert.Equal(nameof(RepositoryController.CloneRepository), viewResult.ViewName); + var model = Assert.IsType>(viewResult.Model); + Assert.Equal("Source", Assert.Single(model.Items).Name); + Assert.Equal("Repository", model.Controller); + Assert.Equal(nameof(RepositoryController.CloneRepository), model.Action); + Assert.Null(model.FinishedMigration); } [Fact] - public async Task PullRequests_InvalidModelState_ReturnsDefaultView() + public async Task CloneRepository_Get_NullItems_ReturnsEmptyCloneForm() + { + // Arrange + _mockProjectService.Setup(s => s.GetAllProjectsAsync()).ReturnsAsync((Projects?)null); + + // Act + var result = await _controller.CloneRepository(); + + // Assert + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Empty(model.Items); + } + + [Fact] + public async Task CloneRepository_Get_WithFinishedOperation_ShowsItOnce() + { + // Arrange + var operationId = Guid.NewGuid(); + _progressTracker.Fail(operationId, "Boom"); + + // Act + var result = await _controller.CloneRepository(operationId); + + // Assert + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Equal(MigrationStatus.Failed, model.FinishedMigration?.Status); + Assert.Null(_progressTracker.Get(operationId)); + } + + [Fact] + public async Task CloneRepository_Post_InvalidModelState_ReturnsCloneFormWithoutCloning() { // Arrange + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(); _controller.ModelState.AddModelError("Error", "Invalid model state"); // Act - var result = await _controller.PullRequests(Guid.NewGuid()); + var result = await _controller.CloneRepository(templateProjectId, projectId); // Assert var viewResult = Assert.IsType(result); - var viewModel = Assert.IsType(viewResult.Model); - Assert.Empty(viewModel); + Assert.Equal(nameof(RepositoryController.CloneRepository), viewResult.ViewName); + Assert.IsType>(viewResult.Model); + Assert.Empty(_mockCloneManager.Invocations); } [Fact] - public async Task PullRequests_ReturnsViewWithPullRequests() + public async Task CloneRepository_Post_Success_CompletesProgressAndRedirects() { // Arrange - var projectId = Guid.NewGuid(); - var mockPullRequests = new GitPullRequests { Value = Array.Empty() }; - _mockRepositoryService - .Setup(service => service.GetGitPullRequestAsync(projectId)) - .ReturnsAsync(mockPullRequests); + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + _mockCloneManager.Setup(m => m.CloneRepositoriesAsync(templateProjectId, projectId, It.IsAny?>())).ReturnsAsync(new CloneResult()); // Act - var result = await _controller.PullRequests(projectId); + var result = await _controller.CloneRepository(templateProjectId, projectId, operationId); // Assert - var viewResult = Assert.IsType(result); - Assert.Equal(mockPullRequests.Value, viewResult.Model); + var redirectResult = Assert.IsType(result); + Assert.Equal(nameof(RepositoryController.CloneRepository), redirectResult.ActionName); + Assert.Equal(operationId, redirectResult.RouteValues?["operationId"]); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Succeeded, progress?.Status); + Assert.Equal("Repositories cloned successfully.", progress?.Message); + _mockCloneManager.Verify(m => m.CloneRepositoriesAsync(templateProjectId, projectId, It.IsAny?>()), Times.Once); } [Fact] - public async Task PullRequests_ReturnsViewWithEmptyPullRequests_WhenServiceReturnsNull() + public async Task CloneRepository_Post_Failure_FailsProgressAndRedirects() { // Arrange - var projectId = Guid.NewGuid(); - _mockRepositoryService - .Setup(service => service.GetGitPullRequestAsync(projectId)) - .ReturnsAsync((GitPullRequests?)null); + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + var failure = new CloneResult(); + failure.AddError("Boom"); + _mockCloneManager.Setup(m => m.CloneRepositoriesAsync(templateProjectId, projectId, It.IsAny?>())).ReturnsAsync(failure); // Act - var result = await _controller.PullRequests(projectId); + var result = await _controller.CloneRepository(templateProjectId, projectId, operationId); // Assert - var viewResult = Assert.IsType(result); - var viewModel = Assert.IsType(viewResult.Model); - Assert.Empty(viewModel); + Assert.IsType(result); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Failed, progress?.Status); + Assert.Equal("Cloning repositories failed: Boom", progress?.Message); + Assert.Equal(0, _controller.ModelState.ErrorCount); } [Fact] - public async Task ClonePullRequests_Get_ReturnsViewWithProjects() + public async Task ClonePullRequests_Get_ReturnsCloneFormWithItems() { // Arrange - var mockProjects = new Projects { Value = Array.Empty() }; - _mockProjectService - .Setup(service => service.GetAllProjectsAsync()) - .ReturnsAsync(mockProjects); + _mockProjectService.Setup(s => s.GetAllProjectsAsync()).ReturnsAsync(new Projects { Value = [new ProjectBase { Name = "Source" }] }); // Act var result = await _controller.ClonePullRequests(); // Assert var viewResult = Assert.IsType(result); - Assert.Equal(mockProjects.Value, viewResult.Model); + Assert.Equal(nameof(RepositoryController.ClonePullRequests), viewResult.ViewName); + var model = Assert.IsType>(viewResult.Model); + Assert.Equal("Source", Assert.Single(model.Items).Name); + Assert.Equal("Repository", model.Controller); + Assert.Equal(nameof(RepositoryController.ClonePullRequests), model.Action); + Assert.Null(model.FinishedMigration); } [Fact] - public async Task ClonePullRequests_Get_ReturnsViewWithEmptyProjects_WhenServiceReturnsNull() + public async Task ClonePullRequests_Get_NullItems_ReturnsEmptyCloneForm() { // Arrange - _mockProjectService - .Setup(service => service.GetAllProjectsAsync()) - .ReturnsAsync((Projects?)null); + _mockProjectService.Setup(s => s.GetAllProjectsAsync()).ReturnsAsync((Projects?)null); // Act var result = await _controller.ClonePullRequests(); // Assert - var viewResult = Assert.IsType(result); - var viewModel = Assert.IsType(viewResult.Model); - Assert.Empty(viewModel); + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Empty(model.Items); } [Fact] - public async Task ClonePullRequests_Post_InvalidModelState_ReturnsViewWithProjects() + public async Task ClonePullRequests_Get_WithFinishedOperation_ShowsItOnce() { // Arrange - _controller.ModelState.AddModelError("Error", "Invalid model state"); - var mockProjects = new Projects { Value = Array.Empty() }; - _mockProjectService - .Setup(service => service.GetAllProjectsAsync()) - .ReturnsAsync(mockProjects); + var operationId = Guid.NewGuid(); + _progressTracker.Fail(operationId, "Boom"); // Act - var result = await _controller.ClonePullRequests(Guid.NewGuid(), Guid.NewGuid()); + var result = await _controller.ClonePullRequests(operationId); // Assert - var viewResult = Assert.IsType(result); - Assert.Equal(mockProjects.Value, viewResult.Model); + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Equal(MigrationStatus.Failed, model.FinishedMigration?.Status); + Assert.Null(_progressTracker.Get(operationId)); } [Fact] - public async Task ClonePullRequests_Post_ValidModelState_ClonesPullRequestsAndReturnsViewWithProjects() + public async Task ClonePullRequests_Post_InvalidModelState_ReturnsCloneFormWithoutCloning() { // Arrange - var templateProjectId = Guid.NewGuid(); - var projectId = Guid.NewGuid(); - var mockProjects = new Projects { Value = Array.Empty() }; - _mockProjectService - .Setup(service => service.GetAllProjectsAsync()) - .ReturnsAsync(mockProjects); + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(); + _controller.ModelState.AddModelError("Error", "Invalid model state"); // Act var result = await _controller.ClonePullRequests(templateProjectId, projectId); // Assert - _mockCloneManager.Verify(manager => manager.CloneGitPullRequestsAsync(templateProjectId, projectId), Times.Once); var viewResult = Assert.IsType(result); - Assert.Equal(mockProjects.Value, viewResult.Model); - Assert.Equal("Success", _controller.ViewBag.SuccessMessage); + Assert.Equal(nameof(RepositoryController.ClonePullRequests), viewResult.ViewName); + Assert.IsType>(viewResult.Model); + Assert.Empty(_mockCloneManager.Invocations); + } + + [Fact] + public async Task ClonePullRequests_Post_Success_CompletesProgressAndRedirects() + { + // Arrange + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + _mockCloneManager.Setup(m => m.CloneGitPullRequestsAsync(templateProjectId, projectId, It.IsAny?>())).ReturnsAsync(new CloneResult()); + + // Act + var result = await _controller.ClonePullRequests(templateProjectId, projectId, operationId); + + // Assert + var redirectResult = Assert.IsType(result); + Assert.Equal(nameof(RepositoryController.ClonePullRequests), redirectResult.ActionName); + Assert.Equal(operationId, redirectResult.RouteValues?["operationId"]); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Succeeded, progress?.Status); + Assert.Equal("Pull requests cloned successfully.", progress?.Message); + _mockCloneManager.Verify(m => m.CloneGitPullRequestsAsync(templateProjectId, projectId, It.IsAny?>()), Times.Once); + } + + [Fact] + public async Task ClonePullRequests_Post_Failure_FailsProgressAndRedirects() + { + // Arrange + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + var failure = new CloneResult(); + failure.AddError("Boom"); + _mockCloneManager.Setup(m => m.CloneGitPullRequestsAsync(templateProjectId, projectId, It.IsAny?>())).ReturnsAsync(failure); + + // Act + var result = await _controller.ClonePullRequests(templateProjectId, projectId, operationId); + + // Assert + Assert.IsType(result); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Failed, progress?.Status); + Assert.Equal("Cloning pull requests failed: Boom", progress?.Message); + Assert.Equal(0, _controller.ModelState.ErrorCount); } -} \ No newline at end of file +} diff --git a/CloneDevOpsTemplateTest/Controllers/TeamControllerTest.cs b/CloneDevOpsTemplateTest/Controllers/TeamControllerTest.cs index d5e8691..4cf89be 100644 --- a/CloneDevOpsTemplateTest/Controllers/TeamControllerTest.cs +++ b/CloneDevOpsTemplateTest/Controllers/TeamControllerTest.cs @@ -12,6 +12,7 @@ public class TeamControllerTest private readonly Mock _mockTeamsService; private readonly Mock _mockCloneManager; private readonly Mock _mockProjectService; + private readonly MigrationProgressTracker _progressTracker = new(); private readonly TeamController _controller; public TeamControllerTest() @@ -19,7 +20,7 @@ public TeamControllerTest() _mockTeamsService = new Mock(); _mockCloneManager = new Mock(); _mockProjectService = new Mock(); - _controller = new TeamController(_mockTeamsService.Object, _mockCloneManager.Object, _mockProjectService.Object); + _controller = new TeamController(_mockTeamsService.Object, _mockCloneManager.Object, _mockProjectService.Object, _progressTracker); } [Fact] @@ -114,136 +115,218 @@ public async Task ProjectTeams_ReturnsViewWithTeams() } [Fact] - public async Task CloneTeams_ReturnsViewWithProjects() + public async Task CloneTeams_Get_ReturnsCloneFormWithItems() { // Arrange - var mockProjects = new Projects - { - Value = - [ - new Project { Id = Guid.NewGuid(), Name = "Project A" } - ] - }; - _mockProjectService.Setup(service => service.GetAllProjectsAsync()).ReturnsAsync(mockProjects); + _mockProjectService.Setup(s => s.GetAllProjectsAsync()).ReturnsAsync(new Projects { Value = [new ProjectBase { Name = "Source" }] }); // Act var result = await _controller.CloneTeams(); // Assert var viewResult = Assert.IsType(result); - Assert.Equal(mockProjects.Value, viewResult.Model); + Assert.Equal(nameof(TeamController.CloneTeams), viewResult.ViewName); + var model = Assert.IsType>(viewResult.Model); + Assert.Equal("Source", Assert.Single(model.Items).Name); + Assert.Equal("Team", model.Controller); + Assert.Equal(nameof(TeamController.CloneTeams), model.Action); + Assert.Null(model.FinishedMigration); } [Fact] - public async Task CloneTeams_NoProjects_ReturnsViewWithEmptyList() + public async Task CloneTeams_Get_NullItems_ReturnsEmptyCloneForm() { // Arrange - _mockProjectService.Setup(service => service.GetAllProjectsAsync()).ReturnsAsync((Projects)null!); + _mockProjectService.Setup(s => s.GetAllProjectsAsync()).ReturnsAsync((Projects?)null); // Act var result = await _controller.CloneTeams(); // Assert - var viewResult = Assert.IsType(result); - var viewModel = Assert.IsType(viewResult.Model); - Assert.Empty(viewModel); + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Empty(model.Items); } [Fact] - public async Task CloneTeams_InvalidModelState_ReturnsCloneTeamsView() + public async Task CloneTeams_Get_WithFinishedOperation_ShowsItOnce() { // Arrange + var operationId = Guid.NewGuid(); + _progressTracker.Fail(operationId, "Boom"); + + // Act + var result = await _controller.CloneTeams(operationId); + + // Assert + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Equal(MigrationStatus.Failed, model.FinishedMigration?.Status); + Assert.Null(_progressTracker.Get(operationId)); + } + + [Fact] + public async Task CloneTeams_Post_InvalidModelState_ReturnsCloneFormWithoutCloning() + { + // Arrange + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(); _controller.ModelState.AddModelError("Error", "Invalid model state"); // Act - var result = await _controller.CloneTeams(Guid.NewGuid(), Guid.NewGuid()); + var result = await _controller.CloneTeams(templateProjectId, projectId); // Assert var viewResult = Assert.IsType(result); - var viewModel = Assert.IsType(viewResult.Model); - Assert.Empty(viewModel); + Assert.Equal(nameof(TeamController.CloneTeams), viewResult.ViewName); + Assert.IsType>(viewResult.Model); + Assert.Empty(_mockCloneManager.Invocations); } [Fact] - public async Task CloneTeams_ValidModelState_ClonesTeamsAndReturnsCloneTeamsView() + public async Task CloneTeams_Post_Success_CompletesProgressAndRedirects() { // Arrange - var templateProjectId = Guid.NewGuid(); - var projectId = Guid.NewGuid(); + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + _mockCloneManager.Setup(m => m.CloneTeamsAsync(templateProjectId, projectId, It.IsAny?>())).ReturnsAsync(new CloneTeamsResult()); // Act - var result = await _controller.CloneTeams(templateProjectId, projectId); + var result = await _controller.CloneTeams(templateProjectId, projectId, operationId); // Assert - _mockCloneManager.Verify(manager => manager.CloneTeamsAsync(templateProjectId, projectId), Times.Once); - Assert.IsType(result); - Assert.Equal("Success", _controller.ViewBag.SuccessMessage); + var redirectResult = Assert.IsType(result); + Assert.Equal(nameof(TeamController.CloneTeams), redirectResult.ActionName); + Assert.Equal(operationId, redirectResult.RouteValues?["operationId"]); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Succeeded, progress?.Status); + Assert.Equal("Teams cloned successfully.", progress?.Message); + _mockCloneManager.Verify(m => m.CloneTeamsAsync(templateProjectId, projectId, It.IsAny?>()), Times.Once); } [Fact] - public async Task CloneTeamFieldValues_ReturnsTeamsView() + public async Task CloneTeams_Post_Failure_FailsProgressAndRedirects() { // Arrange - var mockTeams = new Teams - { - Value = - [ - new Team { Id = Guid.NewGuid(), Name = "Team A" } - ] - }; - _mockTeamsService.Setup(service => service.GetAllTeamsAsync()).ReturnsAsync(mockTeams); + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + var failure = new CloneTeamsResult(); + failure.AddError("Boom"); + _mockCloneManager.Setup(m => m.CloneTeamsAsync(templateProjectId, projectId, It.IsAny?>())).ReturnsAsync(failure); + + // Act + var result = await _controller.CloneTeams(templateProjectId, projectId, operationId); + + // Assert + Assert.IsType(result); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Failed, progress?.Status); + Assert.Equal("Cloning teams failed: Boom", progress?.Message); + Assert.Equal(0, _controller.ModelState.ErrorCount); + } + + [Fact] + public async Task CloneTeamFieldValues_Get_ReturnsCloneFormWithItems() + { + // Arrange + _mockTeamsService.Setup(s => s.GetAllTeamsAsync()).ReturnsAsync(new Teams { Value = [new Team { Name = "Source" }] }); // Act var result = await _controller.CloneTeamFieldValues(); // Assert var viewResult = Assert.IsType(result); - Assert.Equal(mockTeams.Value, viewResult.Model); + Assert.Equal(nameof(TeamController.CloneTeamFieldValues), viewResult.ViewName); + var model = Assert.IsType>(viewResult.Model); + Assert.Equal("Source", Assert.Single(model.Items).Name); + Assert.Equal("Team", model.Controller); + Assert.Equal(nameof(TeamController.CloneTeamFieldValues), model.Action); + Assert.Null(model.FinishedMigration); } [Fact] - public async Task CloneTeamFieldValues_InvalidModelState_ReturnsDefaultTeamsView() + public async Task CloneTeamFieldValues_Get_NullItems_ReturnsEmptyCloneForm() { // Arrange - _controller.ModelState.AddModelError("Error", "Invalid model state"); + _mockTeamsService.Setup(s => s.GetAllTeamsAsync()).ReturnsAsync((Teams?)null); // Act var result = await _controller.CloneTeamFieldValues(); // Assert - var viewResult = Assert.IsType(result); - Assert.IsType(viewResult.Model); + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Empty(model.Items); + } + + [Fact] + public async Task CloneTeamFieldValues_Get_WithFinishedOperation_ShowsItOnce() + { + // Arrange + var operationId = Guid.NewGuid(); + _progressTracker.Fail(operationId, "Boom"); + + // Act + var result = await _controller.CloneTeamFieldValues(operationId); + + // Assert + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Equal(MigrationStatus.Failed, model.FinishedMigration?.Status); + Assert.Null(_progressTracker.Get(operationId)); } [Fact] - public async Task CloneTeamFieldValues_InvalidModelState_ReturnsCloneTeamFieldValuesView() + public async Task CloneTeamFieldValues_Post_InvalidModelState_ReturnsCloneFormWithoutCloning() { // Arrange + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(), templateTeamId = Guid.NewGuid(), projectTeamId = Guid.NewGuid(); _controller.ModelState.AddModelError("Error", "Invalid model state"); // Act - var result = await _controller.CloneTeamFieldValues(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()); + var result = await _controller.CloneTeamFieldValues(templateProjectId, projectId, templateTeamId, projectTeamId); // Assert var viewResult = Assert.IsType(result); - Assert.IsType(viewResult.Model); + Assert.Equal(nameof(TeamController.CloneTeamFieldValues), viewResult.ViewName); + Assert.IsType>(viewResult.Model); + Assert.Empty(_mockCloneManager.Invocations); } [Fact] - public async Task CloneTeamFieldValues_ValidModelState_ClonesTeamFieldValuesAndReturnsCloneTeamFieldValuesView() + public async Task CloneTeamFieldValues_Post_Success_CompletesProgressAndRedirects() { // Arrange - var templateProjectId = Guid.NewGuid(); - var projectId = Guid.NewGuid(); - var templateTeamId = Guid.NewGuid(); - var projectTeamId = Guid.NewGuid(); + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(), templateTeamId = Guid.NewGuid(), projectTeamId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + _mockCloneManager.Setup(m => m.CloneTeamFieldValuesAsync(templateProjectId, projectId, templateTeamId, projectTeamId, It.IsAny?>())).ReturnsAsync(new CloneResult()); // Act - var result = await _controller.CloneTeamFieldValues(templateProjectId, projectId, templateTeamId, projectTeamId); + var result = await _controller.CloneTeamFieldValues(templateProjectId, projectId, templateTeamId, projectTeamId, operationId); + + // Assert + var redirectResult = Assert.IsType(result); + Assert.Equal(nameof(TeamController.CloneTeamFieldValues), redirectResult.ActionName); + Assert.Equal(operationId, redirectResult.RouteValues?["operationId"]); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Succeeded, progress?.Status); + Assert.Equal("Team field values cloned successfully.", progress?.Message); + _mockCloneManager.Verify(m => m.CloneTeamFieldValuesAsync(templateProjectId, projectId, templateTeamId, projectTeamId, It.IsAny?>()), Times.Once); + } + + [Fact] + public async Task CloneTeamFieldValues_Post_Failure_FailsProgressAndRedirects() + { + // Arrange + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(), templateTeamId = Guid.NewGuid(), projectTeamId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + var failure = new CloneResult(); + failure.AddError("Boom"); + _mockCloneManager.Setup(m => m.CloneTeamFieldValuesAsync(templateProjectId, projectId, templateTeamId, projectTeamId, It.IsAny?>())).ReturnsAsync(failure); + + // Act + var result = await _controller.CloneTeamFieldValues(templateProjectId, projectId, templateTeamId, projectTeamId, operationId); // Assert - _mockCloneManager.Verify(manager => manager.CloneTeamFieldValuesAsync(templateProjectId, projectId, templateTeamId, projectTeamId), Times.Once); - Assert.IsType(result); - Assert.Equal("Success", _controller.ViewBag.SuccessMessage); + Assert.IsType(result); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Failed, progress?.Status); + Assert.Equal("Cloning team field values failed: Boom", progress?.Message); + Assert.Equal(0, _controller.ModelState.ErrorCount); } -} \ No newline at end of file +} diff --git a/CloneDevOpsTemplateTest/Controllers/TeamSettingsControllerTest.cs b/CloneDevOpsTemplateTest/Controllers/TeamSettingsControllerTest.cs index 225914f..1cae0ba 100644 --- a/CloneDevOpsTemplateTest/Controllers/TeamSettingsControllerTest.cs +++ b/CloneDevOpsTemplateTest/Controllers/TeamSettingsControllerTest.cs @@ -12,6 +12,7 @@ public class TeamSettingsControllerTest private readonly Mock _mockTeamSettingsService; private readonly Mock _mockCloneManager; private readonly Mock _mockTeamsService; + private readonly MigrationProgressTracker _progressTracker = new(); private readonly TeamSettingsController _controller; public TeamSettingsControllerTest() @@ -19,7 +20,7 @@ public TeamSettingsControllerTest() _mockTeamSettingsService = new Mock(); _mockCloneManager = new Mock(); _mockTeamsService = new Mock(); - _controller = new TeamSettingsController(_mockTeamSettingsService.Object, _mockCloneManager.Object, _mockTeamsService.Object); + _controller = new TeamSettingsController(_mockTeamSettingsService.Object, _mockCloneManager.Object, _mockTeamsService.Object, _progressTracker); } [Fact] @@ -139,227 +140,283 @@ public async Task TeamFieldValues_ReturnsViewResult_WithNewTeamFieldValues_WhenM } [Fact] - public async Task CloneTeamSettings_ReturnsViewResult_WithTeams() + public async Task Iterations_ReturnsViewResult_WithIterations() { // Arrange - Team[] teams = - [ - new() { Id = Guid.NewGuid(), Name = "Team1" }, - new() { Id = Guid.NewGuid(), Name = "Team2" } - ]; - var teamsResponse = new Teams { Value = teams }; + var projectId = Guid.NewGuid(); + var teamId = Guid.NewGuid(); + var iterations = new TeamIterations + { + Value = + [ + new TeamIterationSettings { Name = "Iteration1" }, + new TeamIterationSettings { Name = "Iteration2" } + ] + }; - _mockTeamsService - .Setup(service => service.GetAllTeamsAsync()) - .ReturnsAsync(teamsResponse); + _mockTeamSettingsService + .Setup(service => service.GetIterations(projectId, teamId)) + .ReturnsAsync(iterations); // Act - var result = await _controller.CloneTeamSettings(); + var result = await _controller.Iterations(projectId, teamId); // Assert var viewResult = Assert.IsType(result); - var model = Assert.IsAssignableFrom>(viewResult.Model); - Assert.Equal(teams, model); + var model = Assert.IsAssignableFrom>(viewResult.Model); + Assert.Equal(iterations.Value, model); } [Fact] - public async Task CloneTeamSettings_ReturnsViewResult_WithEmptyTeams_WhenServiceReturnsNull() + public async Task Iterations_ReturnsViewResult_WithEmptyIterations_WhenServiceReturnsNull() { // Arrange - _mockTeamsService - .Setup(service => service.GetAllTeamsAsync()) - .ReturnsAsync((Teams?)null); + var projectId = Guid.NewGuid(); + var teamId = Guid.NewGuid(); + + _mockTeamSettingsService + .Setup(service => service.GetIterations(projectId, teamId)) + .ReturnsAsync((TeamIterations?)null); // Act - var result = await _controller.CloneTeamSettings(); + var result = await _controller.Iterations(projectId, teamId); // Assert var viewResult = Assert.IsType(result); - var model = Assert.IsAssignableFrom>(viewResult.Model); + var model = Assert.IsAssignableFrom>(viewResult.Model); Assert.Empty(model); } [Fact] - public async Task CloneTeamSettings_Post_ReturnsViewResult_WithSuccessMessage_WhenModelStateIsValid() + public async Task Iterations_ReturnsViewResult_WithEmptyIterations_WhenModelStateIsInvalid() { // Arrange - var templateProjectId = Guid.NewGuid(); var projectId = Guid.NewGuid(); - var templateTeamId = Guid.NewGuid(); - var projectTeamId = Guid.NewGuid(); + var teamId = Guid.NewGuid(); + _controller.ModelState.AddModelError("Error", "Invalid model state"); - _mockCloneManager - .Setup(manager => manager.CloneTeamSettingsAsync(templateProjectId, projectId, templateTeamId, projectTeamId)) - .Returns(Task.CompletedTask); + // Act + var result = await _controller.Iterations(projectId, teamId); + + // Assert + var viewResult = Assert.IsType(result); + var model = Assert.IsAssignableFrom>(viewResult.Model); + Assert.Empty(model); + } + + [Fact] + public async Task CloneTeamSettings_Get_ReturnsCloneFormWithItems() + { + // Arrange + _mockTeamsService.Setup(s => s.GetAllTeamsAsync()).ReturnsAsync(new Teams { Value = [new Team { Name = "Source" }] }); // Act - var result = await _controller.CloneTeamSettings(templateProjectId, projectId, templateTeamId, projectTeamId); + var result = await _controller.CloneTeamSettings(); // Assert - Assert.IsType(result); - Assert.Equal("Success", _controller.ViewBag.SuccessMessage); + var viewResult = Assert.IsType(result); + Assert.Equal(nameof(TeamSettingsController.CloneTeamSettings), viewResult.ViewName); + var model = Assert.IsType>(viewResult.Model); + Assert.Equal("Source", Assert.Single(model.Items).Name); + Assert.Equal("TeamSettings", model.Controller); + Assert.Equal(nameof(TeamSettingsController.CloneTeamSettings), model.Action); + Assert.Null(model.FinishedMigration); } [Fact] - public async Task CloneTeamSettings_Post_ReturnsViewResult_WhenModelStateIsInvalid() + public async Task CloneTeamSettings_Get_NullItems_ReturnsEmptyCloneForm() { // Arrange - var templateProjectId = Guid.NewGuid(); - var projectId = Guid.NewGuid(); - var templateTeamId = Guid.NewGuid(); - var projectTeamId = Guid.NewGuid(); + _mockTeamsService.Setup(s => s.GetAllTeamsAsync()).ReturnsAsync((Teams?)null); + + // Act + var result = await _controller.CloneTeamSettings(); + + // Assert + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Empty(model.Items); + } + + [Fact] + public async Task CloneTeamSettings_Get_WithFinishedOperation_ShowsItOnce() + { + // Arrange + var operationId = Guid.NewGuid(); + _progressTracker.Fail(operationId, "Boom"); + + // Act + var result = await _controller.CloneTeamSettings(operationId); + + // Assert + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Equal(MigrationStatus.Failed, model.FinishedMigration?.Status); + Assert.Null(_progressTracker.Get(operationId)); + } + + [Fact] + public async Task CloneTeamSettings_Post_InvalidModelState_ReturnsCloneFormWithoutCloning() + { + // Arrange + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(), templateTeamId = Guid.NewGuid(), projectTeamId = Guid.NewGuid(); _controller.ModelState.AddModelError("Error", "Invalid model state"); // Act var result = await _controller.CloneTeamSettings(templateProjectId, projectId, templateTeamId, projectTeamId); // Assert - Assert.IsType(result); - Assert.Null(_controller.ViewBag.SuccessMessage); + var viewResult = Assert.IsType(result); + Assert.Equal(nameof(TeamSettingsController.CloneTeamSettings), viewResult.ViewName); + Assert.IsType>(viewResult.Model); + Assert.Empty(_mockCloneManager.Invocations); } [Fact] - public async Task CloneTeamIterations_ReturnsViewResult_WithTeams() + public async Task CloneTeamSettings_Post_Success_CompletesProgressAndRedirects() { // Arrange - Team[] teams = - [ - new() { Id = Guid.NewGuid(), Name = "Team1" }, - new() { Id = Guid.NewGuid(), Name = "Team2" } - ]; - var teamsResponse = new Teams { Value = teams }; + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(), templateTeamId = Guid.NewGuid(), projectTeamId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + _mockCloneManager.Setup(m => m.CloneTeamSettingsAsync(templateProjectId, projectId, templateTeamId, projectTeamId, It.IsAny?>())).ReturnsAsync(new CloneResult()); + + // Act + var result = await _controller.CloneTeamSettings(templateProjectId, projectId, templateTeamId, projectTeamId, operationId); + + // Assert + var redirectResult = Assert.IsType(result); + Assert.Equal(nameof(TeamSettingsController.CloneTeamSettings), redirectResult.ActionName); + Assert.Equal(operationId, redirectResult.RouteValues?["operationId"]); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Succeeded, progress?.Status); + Assert.Equal("Team settings cloned successfully.", progress?.Message); + _mockCloneManager.Verify(m => m.CloneTeamSettingsAsync(templateProjectId, projectId, templateTeamId, projectTeamId, It.IsAny?>()), Times.Once); + } - _mockTeamsService - .Setup(service => service.GetAllTeamsAsync()) - .ReturnsAsync(teamsResponse); + [Fact] + public async Task CloneTeamSettings_Post_Failure_FailsProgressAndRedirects() + { + // Arrange + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(), templateTeamId = Guid.NewGuid(), projectTeamId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + var failure = new CloneResult(); + failure.AddError("Boom"); + _mockCloneManager.Setup(m => m.CloneTeamSettingsAsync(templateProjectId, projectId, templateTeamId, projectTeamId, It.IsAny?>())).ReturnsAsync(failure); // Act - var result = await _controller.CloneTeamIterations(); + var result = await _controller.CloneTeamSettings(templateProjectId, projectId, templateTeamId, projectTeamId, operationId); // Assert - var viewResult = Assert.IsType(result); - var model = Assert.IsAssignableFrom>(viewResult.Model); - Assert.Equal(teams, model); + Assert.IsType(result); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Failed, progress?.Status); + Assert.Equal("Cloning team settings failed: Boom", progress?.Message); + Assert.Equal(0, _controller.ModelState.ErrorCount); } [Fact] - public async Task CloneTeamIterations_ReturnsViewResult_WithEmptyTeams_WhenServiceReturnsNull() + public async Task CloneTeamIterations_Get_ReturnsCloneFormWithItems() { // Arrange - _mockTeamsService - .Setup(service => service.GetAllTeamsAsync()) - .ReturnsAsync((Teams?)null); + _mockTeamsService.Setup(s => s.GetAllTeamsAsync()).ReturnsAsync(new Teams { Value = [new Team { Name = "Source" }] }); // Act var result = await _controller.CloneTeamIterations(); // Assert var viewResult = Assert.IsType(result); - var model = Assert.IsAssignableFrom>(viewResult.Model); - Assert.Empty(model); + Assert.Equal(nameof(TeamSettingsController.CloneTeamIterations), viewResult.ViewName); + var model = Assert.IsType>(viewResult.Model); + Assert.Equal("Source", Assert.Single(model.Items).Name); + Assert.Equal("TeamSettings", model.Controller); + Assert.Equal(nameof(TeamSettingsController.CloneTeamIterations), model.Action); + Assert.Null(model.FinishedMigration); } [Fact] - public async Task CloneTeamIterations_Post_ReturnsViewResult_WithSuccessMessage_WhenModelStateIsValid() + public async Task CloneTeamIterations_Get_NullItems_ReturnsEmptyCloneForm() { // Arrange - var templateProjectId = Guid.NewGuid(); - var projectId = Guid.NewGuid(); - var templateTeamId = Guid.NewGuid(); - var projectTeamId = Guid.NewGuid(); - - _mockCloneManager - .Setup(manager => manager.CloneTeamIterationsAsync(templateProjectId, projectId, templateTeamId, projectTeamId)) - .Returns(Task.CompletedTask); + _mockTeamsService.Setup(s => s.GetAllTeamsAsync()).ReturnsAsync((Teams?)null); // Act - var result = await _controller.CloneTeamIterations(templateProjectId, projectId, templateTeamId, projectTeamId); + var result = await _controller.CloneTeamIterations(); // Assert - Assert.IsType(result); - Assert.Equal("Success", _controller.ViewBag.SuccessMessage); + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Empty(model.Items); } [Fact] - public async Task CloneTeamIterations_Post_ReturnsViewResult_WhenModelStateIsInvalid() + public async Task CloneTeamIterations_Get_WithFinishedOperation_ShowsItOnce() { // Arrange - var templateProjectId = Guid.NewGuid(); - var projectId = Guid.NewGuid(); - var templateTeamId = Guid.NewGuid(); - var projectTeamId = Guid.NewGuid(); - _controller.ModelState.AddModelError("Error", "Invalid model state"); + var operationId = Guid.NewGuid(); + _progressTracker.Fail(operationId, "Boom"); // Act - var result = await _controller.CloneTeamIterations(templateProjectId, projectId, templateTeamId, projectTeamId); + var result = await _controller.CloneTeamIterations(operationId); // Assert - Assert.IsType(result); - Assert.Null(_controller.ViewBag.SuccessMessage); + var model = Assert.IsType>(Assert.IsType(result).Model); + Assert.Equal(MigrationStatus.Failed, model.FinishedMigration?.Status); + Assert.Null(_progressTracker.Get(operationId)); } [Fact] - public async Task Iterations_ReturnsViewResult_WithIterations() + public async Task CloneTeamIterations_Post_InvalidModelState_ReturnsCloneFormWithoutCloning() { // Arrange - var projectId = Guid.NewGuid(); - var teamId = Guid.NewGuid(); - var iterations = new TeamIterations - { - Value = - [ - new TeamIterationSettings { Name = "Iteration1" }, - new TeamIterationSettings { Name = "Iteration2" } - ] - }; - - _mockTeamSettingsService - .Setup(service => service.GetIterations(projectId, teamId)) - .ReturnsAsync(iterations); + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(), templateTeamId = Guid.NewGuid(), projectTeamId = Guid.NewGuid(); + _controller.ModelState.AddModelError("Error", "Invalid model state"); // Act - var result = await _controller.Iterations(projectId, teamId); + var result = await _controller.CloneTeamIterations(templateProjectId, projectId, templateTeamId, projectTeamId); // Assert var viewResult = Assert.IsType(result); - var model = Assert.IsAssignableFrom>(viewResult.Model); - Assert.Equal(iterations.Value, model); + Assert.Equal(nameof(TeamSettingsController.CloneTeamIterations), viewResult.ViewName); + Assert.IsType>(viewResult.Model); + Assert.Empty(_mockCloneManager.Invocations); } [Fact] - public async Task Iterations_ReturnsViewResult_WithEmptyIterations_WhenServiceReturnsNull() + public async Task CloneTeamIterations_Post_Success_CompletesProgressAndRedirects() { // Arrange - var projectId = Guid.NewGuid(); - var teamId = Guid.NewGuid(); - - _mockTeamSettingsService - .Setup(service => service.GetIterations(projectId, teamId)) - .ReturnsAsync((TeamIterations?)null); + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(), templateTeamId = Guid.NewGuid(), projectTeamId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + _mockCloneManager.Setup(m => m.CloneTeamIterationsAsync(templateProjectId, projectId, templateTeamId, projectTeamId, It.IsAny?>())).ReturnsAsync(new CloneResult()); // Act - var result = await _controller.Iterations(projectId, teamId); + var result = await _controller.CloneTeamIterations(templateProjectId, projectId, templateTeamId, projectTeamId, operationId); // Assert - var viewResult = Assert.IsType(result); - var model = Assert.IsAssignableFrom>(viewResult.Model); - Assert.Empty(model); + var redirectResult = Assert.IsType(result); + Assert.Equal(nameof(TeamSettingsController.CloneTeamIterations), redirectResult.ActionName); + Assert.Equal(operationId, redirectResult.RouteValues?["operationId"]); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Succeeded, progress?.Status); + Assert.Equal("Team iterations cloned successfully.", progress?.Message); + _mockCloneManager.Verify(m => m.CloneTeamIterationsAsync(templateProjectId, projectId, templateTeamId, projectTeamId, It.IsAny?>()), Times.Once); } [Fact] - public async Task Iterations_ReturnsViewResult_WithEmptyIterations_WhenModelStateIsInvalid() + public async Task CloneTeamIterations_Post_Failure_FailsProgressAndRedirects() { // Arrange - var projectId = Guid.NewGuid(); - var teamId = Guid.NewGuid(); - _controller.ModelState.AddModelError("Error", "Invalid model state"); + Guid templateProjectId = Guid.NewGuid(), projectId = Guid.NewGuid(), templateTeamId = Guid.NewGuid(), projectTeamId = Guid.NewGuid(); + var operationId = Guid.NewGuid(); + var failure = new CloneResult(); + failure.AddError("Boom"); + _mockCloneManager.Setup(m => m.CloneTeamIterationsAsync(templateProjectId, projectId, templateTeamId, projectTeamId, It.IsAny?>())).ReturnsAsync(failure); // Act - var result = await _controller.Iterations(projectId, teamId); + var result = await _controller.CloneTeamIterations(templateProjectId, projectId, templateTeamId, projectTeamId, operationId); // Assert - var viewResult = Assert.IsType(result); - var model = Assert.IsAssignableFrom>(viewResult.Model); - Assert.Empty(model); + Assert.IsType(result); + var progress = _progressTracker.Get(operationId); + Assert.Equal(MigrationStatus.Failed, progress?.Status); + Assert.Equal("Cloning team iterations failed: Boom", progress?.Message); + Assert.Equal(0, _controller.ModelState.ErrorCount); } -} \ No newline at end of file +} diff --git a/CloneDevOpsTemplateTest/Managers/CloneManagerTest.cs b/CloneDevOpsTemplateTest/Managers/CloneManagerTest.cs index cb6558a..e433b95 100644 --- a/CloneDevOpsTemplateTest/Managers/CloneManagerTest.cs +++ b/CloneDevOpsTemplateTest/Managers/CloneManagerTest.cs @@ -1,3 +1,4 @@ +using System.Net.Http.Json; using CloneDevOpsTemplate.IServices; using CloneDevOpsTemplate.Managers; using CloneDevOpsTemplate.Models; @@ -26,6 +27,20 @@ public CloneManagerTest() _mockRepositoryService = new Mock(); _mockServiceService = new Mock(); + // Successful defaults for the bulk service operations; individual tests override them. + _mockIterationService.Setup(s => s.CreateAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(new CloneResult()); + _mockIterationService.Setup(s => s.DeleteAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(new CloneResult()); + _mockBoardService.Setup(s => s.MoveBoardColumnsAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(new CloneResult()); + _mockBoardService.Setup(s => s.MoveBoardRowsAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(new CloneResult()); + _mockBoardService.Setup(s => s.MoveCardSettingsAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(new CloneResult()); + _mockBoardService.Setup(s => s.MoveCardStylesAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(new CloneResult()); + _cloneManager = new CloneManager( _mockProjectService.Object, _mockIterationService.Object, @@ -136,6 +151,8 @@ public async Task CloneTeamsAndSettingsAndBoardsAsync_ShouldCloneTeamsSettingsAn var teamSettings = new TeamSettings(); + _mockTeamsService.Setup(s => s.GetTeamsAsync(templateProject.Id)).ReturnsAsync(new Teams()); + _mockBoardService.Setup(s => s.GetBoardsAsync(project.Id, It.IsAny())).ReturnsAsync(new Boards()); _mockTeamsService.Setup(s => s.CreateTeamFromTemplateAsync(project.Id, It.IsAny(), templateProject.DefaultTeam.Id, project.DefaultTeam.Id)) .ReturnsAsync(mapTeams); @@ -149,21 +166,22 @@ public async Task CloneTeamsAndSettingsAndBoardsAsync_ShouldCloneTeamsSettingsAn .Returns(Task.FromResult(new HttpResponseMessage())); _mockBoardService.Setup(s => s.MoveBoardColumnsAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .ReturnsAsync(new CloneResult()); _mockBoardService.Setup(s => s.MoveBoardRowsAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .ReturnsAsync(new CloneResult()); _mockBoardService.Setup(s => s.MoveCardSettingsAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .ReturnsAsync(new CloneResult()); _mockBoardService.Setup(s => s.MoveCardStylesAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(Task.CompletedTask); + .ReturnsAsync(new CloneResult()); // Act - await _cloneManager.CloneTeamsAndSettingsAndBoardsAsync(templateProject, project); + var result = await _cloneManager.CloneTeamsAndSettingsAndBoardsAsync(templateProject, project); // Assert + Assert.True(result.Succeeded, result.ErrorMessage); _mockTeamsService.Verify(s => s.CreateTeamFromTemplateAsync(project.Id, It.IsAny(), templateProject.DefaultTeam.Id, project.DefaultTeam.Id), Times.Once); foreach (var mappedTeam in mapTeams) @@ -523,4 +541,321 @@ public async Task CloneGitPullRequestsAsync_ShouldClonePullRequests() _mockRepositoryService.Verify(s => s.GetGitPullRequestAsync(templateProjectId), Times.Once); _mockRepositoryService.Verify(s => s.CreateGitPullRequestAsync(projectId, mappedRepositoryId, It.IsAny()), Times.Once); } -} \ No newline at end of file + [Fact] + public async Task CloneGitPullRequestsAsync_ReportsProgressDetails() + { + // Arrange + var templateProjectId = Guid.NewGuid(); + var projectId = Guid.NewGuid(); + var progress = new RecordingProgress(); + + _mockRepositoryService.Setup(s => s.GetGitPullRequestAsync(templateProjectId)) + .ReturnsAsync(new GitPullRequests { Value = [new GitPullRequest { Repository = new Repository(), Title = "PR1" }] }); + + // Act + await _cloneManager.CloneGitPullRequestsAsync(templateProjectId, projectId, progress); + + // Assert + Assert.Contains("Pull requests: 1 pull request(s) to clone.", progress.Messages); + Assert.Contains("Pull request 'PR1' (1/1): creating...", progress.Messages); + } + + [Fact] + public async Task CloneClassificationNodes_ReportsNodeCounts() + { + // Arrange + var templateProjectId = Guid.NewGuid(); + var projectId = Guid.NewGuid(); + var progress = new RecordingProgress(); + + _mockIterationService.Setup(s => s.GetAllAsync(projectId, TreeStructureGroup.Areas)) + .ReturnsAsync(new Iteration { Children = [new Iteration()] }); + _mockIterationService.Setup(s => s.GetAllAsync(templateProjectId, TreeStructureGroup.Areas)) + .ReturnsAsync(new Iteration { Children = [new Iteration { Children = [new Iteration(), new Iteration()] }] }); + + // Act + await _cloneManager.CloneClassificationNodes(templateProjectId, projectId, TreeStructureGroup.Areas, progress); + + // Assert + Assert.Equal( + ["Areas: removing 1 default node(s)...", "Areas: creating 3 node(s) from template...", "Areas: done."], + progress.Messages); + } + + [Fact] + public async Task CloneTeamsAndSettingsAndBoardsAsync_ReportsTeamNames() + { + // Arrange + var templateTeamId = Guid.NewGuid(); + var templateProject = new Project { Id = Guid.NewGuid(), Name = "Template", DefaultTeam = new Team { Id = Guid.NewGuid() } }; + var project = new Project { Id = Guid.NewGuid(), DefaultTeam = new Team { Id = Guid.NewGuid() } }; + var templateTeams = new Teams { Value = [new Team { Id = templateTeamId, Name = "Alpha" }] }; + var progress = new RecordingProgress(); + + _mockTeamsService.Setup(s => s.GetTeamsAsync(templateProject.Id)).ReturnsAsync(templateTeams); + _mockTeamsService.Setup(s => s.CreateTeamFromTemplateAsync(project.Id, templateTeams.Value, templateProject.DefaultTeam.Id, project.DefaultTeam.Id)) + .ReturnsAsync(new Dictionary { { templateTeamId, Guid.NewGuid() } }); + + // Act + await _cloneManager.CloneTeamsAndSettingsAndBoardsAsync(templateProject, project, progress); + + // Assert + Assert.Contains("Teams: 1 team(s) mapped.", progress.Messages); + Assert.Contains("Team 'Alpha' (1/1): cloning boards...", progress.Messages); + Assert.Contains("Team 'Alpha' (1/1): done.", progress.Messages); + } + + [Fact] + public async Task CloneClassificationNodes_TemplateNodesMissing_ReturnsErrorWithoutDeleting() + { + // Arrange + var templateProjectId = Guid.NewGuid(); + var projectId = Guid.NewGuid(); + _mockIterationService.Setup(s => s.GetAllAsync(projectId, TreeStructureGroup.Iterations)).ReturnsAsync(new Iteration()); + + // Act + var result = await _cloneManager.CloneClassificationNodes(templateProjectId, projectId, TreeStructureGroup.Iterations); + + // Assert + Assert.False(result.Succeeded); + Assert.Equal(["Iterations: could not read the template project's nodes."], result.Errors); + _mockIterationService.Verify(s => s.DeleteAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task CloneTeamsAndSettingsAndBoardsAsync_UpdateFails_ReturnsErrorWithDevOpsMessage() + { + // Arrange + var templateTeamId = Guid.NewGuid(); + var templateProject = new Project { Id = Guid.NewGuid(), Name = "Template", DefaultTeam = new Team { Id = Guid.NewGuid() } }; + var project = new Project { Id = Guid.NewGuid(), Name = "New", DefaultTeam = new Team { Id = Guid.NewGuid() } }; + var templateTeams = new Teams { Value = [new Team { Id = templateTeamId, Name = "Alpha" }] }; + var progress = new RecordingProgress(); + + _mockTeamsService.Setup(s => s.GetTeamsAsync(templateProject.Id)).ReturnsAsync(templateTeams); + _mockTeamsService.Setup(s => s.CreateTeamFromTemplateAsync(project.Id, templateTeams.Value, templateProject.DefaultTeam.Id, project.DefaultTeam.Id)) + .ReturnsAsync(new Dictionary { { templateTeamId, Guid.NewGuid() } }); + _mockTeamSettingsService.Setup(s => s.UpdateTeamSettings(It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest) + { + ReasonPhrase = "Bad Request", + Content = JsonContent.Create(new ErrorResponse { Message = "TF400898: Invalid iteration." }) + }); + _mockTeamSettingsService.Setup(s => s.UpdateTeamFieldValues(It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(new HttpResponseMessage()); + _mockBoardService.Setup(s => s.GetBoardsAsync(project.Id, It.IsAny())).ReturnsAsync(new Boards()); + + // Act + var result = await _cloneManager.CloneTeamsAndSettingsAndBoardsAsync(templateProject, project, progress); + + // Assert + var error = "Team 'Alpha': updating settings failed (400 Bad Request: TF400898: Invalid iteration.)."; + Assert.Equal([error], result.Errors); + Assert.Contains($"Error: {error}", progress.Messages); + } + + [Fact] + public async Task CloneRepositoriesAsync_ImportFails_ReturnsErrorWithoutWaitingForTimeout() + { + // Arrange + var templateProjectId = Guid.NewGuid(); + var projectId = Guid.NewGuid(); + var repositoryId = Guid.NewGuid(); + + _mockRepositoryService.Setup(s => s.GetRepositoriesAsync(templateProjectId)) + .ReturnsAsync(new Repositories { Value = [new Repository { Name = "Api", RemoteUrl = "http://example.com/api" }] }); + _mockRepositoryService.Setup(s => s.GetRepositoriesAsync(projectId)) + .ReturnsAsync(new Repositories { Value = [new Repository { Id = repositoryId, Name = "Api" }] }); + _mockServiceService.Setup(s => s.GetServicesAsync(projectId)) + .ReturnsAsync(new ServicesModel { Value = [new ServiceModel { Name = "Api" }] }); + _mockRepositoryService.Setup(s => s.CreateImportRequestAsync(projectId, repositoryId, It.IsAny(), It.IsAny())) + .ReturnsAsync(new GitImportRequest { ImportRequestId = 7 }); + _mockRepositoryService.Setup(s => s.GetImportRequestAsync(projectId, repositoryId, 7)) + .ReturnsAsync(new GitImportRequest { Status = GitAsyncOperationStatus.Failed }); + _mockRepositoryService.Setup(s => s.DeleteRepositoryAsync(It.IsAny(), It.IsAny())) + .ReturnsAsync(new HttpResponseMessage()); + + // Act + var result = await _cloneManager.CloneRepositoriesAsync(templateProjectId, projectId); + + // Assert + Assert.Equal(["Repository 'Api': import Failed."], result.Errors); + } + + [Fact] + public async Task CloneRepositoriesAsync_CreateRepositoryFails_ReturnsErrorAndSkipsImport() + { + // Arrange + var templateProjectId = Guid.NewGuid(); + var projectId = Guid.NewGuid(); + + _mockRepositoryService.Setup(s => s.GetRepositoriesAsync(templateProjectId)) + .ReturnsAsync(new Repositories { Value = [new Repository { Name = "Api" }] }); + _mockRepositoryService.Setup(s => s.GetRepositoriesAsync(projectId)) + .ReturnsAsync(new Repositories()); + + // Act + var result = await _cloneManager.CloneRepositoriesAsync(templateProjectId, projectId); + + // Assert + Assert.Equal(["Repository 'Api': could not be created."], result.Errors); + _mockRepositoryService.Verify(s => s.CreateImportRequestAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task CloneGitPullRequestsAsync_ReportsUnmappedRepositoryAndFailedCreation() + { + // Arrange + var templateProjectId = Guid.NewGuid(); + var projectId = Guid.NewGuid(); + var templateRepositoryId = Guid.NewGuid(); + + _mockRepositoryService.Setup(s => s.GetGitPullRequestAsync(templateProjectId)) + .ReturnsAsync(new GitPullRequests + { + Value = + [ + new GitPullRequest { Title = "Mapped", Repository = new Repository { Id = templateRepositoryId, Name = "Api" } }, + new GitPullRequest { Title = "Orphan", Repository = new Repository { Id = Guid.NewGuid(), Name = "Gone" } } + ] + }); + _mockRepositoryService.Setup(s => s.GetRepositoriesAsync(templateProjectId)) + .ReturnsAsync(new Repositories { Value = [new Repository { Id = templateRepositoryId, Name = "Api" }] }); + _mockRepositoryService.Setup(s => s.GetRepositoriesAsync(projectId)) + .ReturnsAsync(new Repositories { Value = [new Repository { Id = Guid.NewGuid(), Name = "Api" }] }); + _mockRepositoryService.Setup(s => s.CreateGitPullRequestAsync(projectId, It.IsAny(), It.IsAny())) + .ReturnsAsync(new HttpResponseMessage(System.Net.HttpStatusCode.Conflict) { ReasonPhrase = "Conflict" }); + + // Act + var result = await _cloneManager.CloneGitPullRequestsAsync(templateProjectId, projectId); + + // Assert + Assert.Equal( + ["Pull request 'Mapped': creating failed (409 Conflict).", "Pull request 'Orphan': repository 'Gone' not found in the target project."], + result.Errors); + _mockRepositoryService.Verify(s => s.CreateGitPullRequestAsync(projectId, It.IsAny(), It.IsAny()), Times.Once); + } + + [Fact] + public async Task CloneTeamsAsync_TeamNotCreated_ReturnsErrorAndDropsMapping() + { + // Arrange + var failedTeamId = Guid.NewGuid(); + var createdTeamId = Guid.NewGuid(); + var templateProject = new Project { Id = Guid.NewGuid(), DefaultTeam = new Team { Id = Guid.NewGuid() } }; + var project = new Project { Id = Guid.NewGuid(), DefaultTeam = new Team { Id = Guid.NewGuid() } }; + var templateTeams = new Teams { Value = [new Team { Id = failedTeamId, Name = "Broken" }, new Team { Id = createdTeamId, Name = "Fine" }] }; + + _mockTeamsService.Setup(s => s.GetTeamsAsync(templateProject.Id)).ReturnsAsync(templateTeams); + _mockTeamsService.Setup(s => s.CreateTeamFromTemplateAsync(project.Id, templateTeams.Value, templateProject.DefaultTeam.Id, project.DefaultTeam.Id)) + .ReturnsAsync(new Dictionary { { failedTeamId, Guid.Empty }, { createdTeamId, Guid.NewGuid() } }); + + // Act + var result = await _cloneManager.CloneTeamsAsync(templateProject, project); + + // Assert + Assert.Equal(["Team 'Broken': could not be created."], result.Errors); + Assert.Equal([createdTeamId], result.TeamMap.Keys); + } + + [Fact] + public async Task CloneTeamsAsync_ProjectNotFound_ReturnsError() + { + // Act + var result = await _cloneManager.CloneTeamsAsync(Guid.NewGuid(), Guid.NewGuid()); + + // Assert + Assert.Equal(["Could not read the template project."], result.Errors); + _mockTeamsService.Verify(s => s.CreateTeamFromTemplateAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task CloneTeamIterationsAsync_CreateIterationFails_ReturnsError() + { + // Arrange + var templateProjectId = Guid.NewGuid(); + var projectId = Guid.NewGuid(); + var templateTeamId = Guid.NewGuid(); + var projectTeamId = Guid.NewGuid(); + var templateIterationId = Guid.NewGuid(); + + _mockTeamSettingsService.Setup(s => s.GetIterations(templateProjectId, templateTeamId)) + .ReturnsAsync(new TeamIterations { Value = [new TeamIterationSettings { Id = templateIterationId, Name = "Sprint 1" }] }); + _mockIterationService.Setup(s => s.GetAllAsync(templateProjectId, TreeStructureGroup.Iterations)) + .ReturnsAsync(new Iteration { Identifier = Guid.NewGuid(), Children = [new Iteration { Name = "Sprint 1", Identifier = templateIterationId }] }); + _mockIterationService.Setup(s => s.GetAllAsync(projectId, TreeStructureGroup.Iterations)) + .ReturnsAsync(new Iteration { Identifier = Guid.NewGuid(), Children = [new Iteration { Name = "Sprint 1", Identifier = Guid.NewGuid() }] }); + _mockTeamSettingsService.Setup(s => s.CreateIteration(projectId, projectTeamId, It.IsAny())) + .ReturnsAsync(new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden) { ReasonPhrase = "Forbidden" }); + + // Act + var result = await _cloneManager.CloneTeamIterationsAsync(templateProjectId, projectId, templateTeamId, projectTeamId); + + // Assert + Assert.Equal(["Team: adding iteration 'Sprint 1' failed (403 Forbidden)."], result.Errors); + } + + [Fact] + public async Task CloneBoardsAsync_BoardsMissing_ReturnsErrorWithoutMoving() + { + // Act + var result = await _cloneManager.CloneBoardsAsync(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()); + + // Assert + Assert.Equal(["Team: could not read the target team's boards."], result.Errors); + _mockBoardService.Verify(s => s.MoveBoardColumnsAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task CloneClassificationNodes_ServiceErrors_ArePrefixedAndReported() + { + // Arrange + var templateProjectId = Guid.NewGuid(); + var projectId = Guid.NewGuid(); + var progress = new RecordingProgress(); + _mockIterationService.Setup(s => s.GetAllAsync(It.IsAny(), TreeStructureGroup.Areas)).ReturnsAsync(new Iteration()); + _mockIterationService.Setup(s => s.CreateAsync(projectId, It.IsAny(), TreeStructureGroup.Areas, "")) + .ReturnsAsync(CloneResult.FromError("Creating 'Web' failed (400 Bad Request).")); + + // Act + var result = await _cloneManager.CloneClassificationNodes(templateProjectId, projectId, TreeStructureGroup.Areas, progress); + + // Assert + Assert.Equal(["Areas: Creating 'Web' failed (400 Bad Request)."], result.Errors); + Assert.Contains("Error: Areas: Creating 'Web' failed (400 Bad Request).", progress.Messages); + } + + [Fact] + public async Task CloneBoardsAsync_MoveErrors_AreCollectedOnce() + { + // Arrange + var projectId = Guid.NewGuid(); + var projectTeamId = Guid.NewGuid(); + var readError = CloneResult.FromError("Could not read the template team's boards."); + _mockBoardService.Setup(s => s.GetBoardsAsync(projectId, projectTeamId)).ReturnsAsync(new Boards()); + _mockBoardService.Setup(s => s.MoveBoardColumnsAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(readError); + _mockBoardService.Setup(s => s.MoveBoardRowsAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(readError); + _mockBoardService.Setup(s => s.MoveCardStylesAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(CloneResult.FromError("Board 'Stories': updating card styles failed (403 Forbidden).")); + + // Act + var result = await _cloneManager.CloneBoardsAsync(Guid.NewGuid(), projectId, Guid.NewGuid(), projectTeamId); + + // Assert + Assert.Equal( + ["Team: Could not read the template team's boards.", "Team: Board 'Stories': updating card styles failed (403 Forbidden)."], + result.Errors); + } + + private sealed class RecordingProgress : IProgress + { + public List Messages { get; } = []; + public void Report(string value) + { + lock (Messages) + { + Messages.Add(value); + } + } + } +} diff --git a/CloneDevOpsTemplateTest/Managers/MigrationProgressTrackerExtensionsTest.cs b/CloneDevOpsTemplateTest/Managers/MigrationProgressTrackerExtensionsTest.cs new file mode 100644 index 0000000..011846c --- /dev/null +++ b/CloneDevOpsTemplateTest/Managers/MigrationProgressTrackerExtensionsTest.cs @@ -0,0 +1,59 @@ +using CloneDevOpsTemplate.Managers; +using CloneDevOpsTemplate.Models; + +namespace CloneDevOpsTemplateTest.Managers; + +public class MigrationProgressTrackerExtensionsTest +{ + private readonly MigrationProgressTracker _tracker = new(); + + [Fact] + public async Task RunAsync_Success_CompletesAndPassesDetailReporter() + { + var operationId = Guid.NewGuid(); + + var returnedId = await _tracker.RunAsync(operationId, "Cloning things...", "Done.", progress => + { + progress.Report("Working"); + return Task.FromResult(new CloneResult()); + }); + + Assert.Equal(operationId, returnedId); + var progress = _tracker.Get(operationId); + Assert.NotNull(progress); + Assert.Equal(MigrationStatus.Succeeded, progress.Status); + Assert.Equal("Done.", progress.Message); + Assert.Equal(["Step 1 of 1: Cloning things...", "Working", "Done."], progress.Details.Select(d => d.Message)); + } + + [Fact] + public async Task RunAsync_Errors_FailsWithStepPrefix() + { + var operationId = await _tracker.RunAsync(Guid.NewGuid(), "Cloning things...", "Done.", + _ => Task.FromResult(CloneResult.FromError("Boom"))); + + var progress = _tracker.Get(operationId); + Assert.Equal(MigrationStatus.Failed, progress?.Status); + Assert.Equal("Cloning things failed: Boom", progress?.Message); + } + + [Fact] + public async Task RunAsync_EmptyOperationId_GeneratesOne() + { + var operationId = await _tracker.RunAsync(Guid.Empty, "Step", "Done.", _ => Task.FromResult(new CloneResult())); + + Assert.NotEqual(Guid.Empty, operationId); + Assert.Equal(MigrationStatus.Succeeded, _tracker.Get(operationId)?.Status); + } + + [Fact] + public async Task RunAsync_Throws_RemovesProgressAndRethrows() + { + var operationId = Guid.NewGuid(); + + await Assert.ThrowsAsync(() => + _tracker.RunAsync(operationId, "Step", "Done.", _ => throw new TimeoutException())); + + Assert.Null(_tracker.Get(operationId)); + } +} diff --git a/CloneDevOpsTemplateTest/Managers/MigrationProgressTrackerTest.cs b/CloneDevOpsTemplateTest/Managers/MigrationProgressTrackerTest.cs new file mode 100644 index 0000000..40343b0 --- /dev/null +++ b/CloneDevOpsTemplateTest/Managers/MigrationProgressTrackerTest.cs @@ -0,0 +1,209 @@ +using CloneDevOpsTemplate.Managers; +using CloneDevOpsTemplate.Models; + +namespace CloneDevOpsTemplateTest.Managers; + +public class MigrationProgressTrackerTest +{ + private readonly MigrationProgressTracker _tracker = new(); + + [Fact] + public void Report_KeepsStepAndAppendsToDetailLog() + { + var operationId = Guid.NewGuid(); + + _tracker.Start(operationId, 4); + _tracker.Report(operationId, 1, "Creating project..."); + _tracker.CreateDetailReporter(operationId).Report("Waiting..."); + _tracker.Report(operationId, 2, "Cloning iterations..."); + + var progress = _tracker.Get(operationId); + Assert.NotNull(progress); + Assert.Equal(2, progress.Step); + Assert.Equal(4, progress.TotalSteps); + Assert.Equal("Cloning iterations...", progress.Message); + Assert.Null(progress.CurrentDetail); + Assert.Equal( + ["Step 1 of 4: Creating project...", "Waiting...", "Step 2 of 4: Cloning iterations..."], + progress.Details.Select(d => d.Message)); + Assert.Equal([1, 1, 2], progress.Details.Select(d => d.Step)); + } + + [Fact] + public void Start_ResetsPreviousProgress() + { + var operationId = Guid.NewGuid(); + _tracker.Start(operationId, 2); + _tracker.Report(operationId, 1, "Old"); + + _tracker.Start(operationId, 3); + + var progress = _tracker.Get(operationId); + Assert.NotNull(progress); + Assert.Equal(0, progress.Step); + Assert.Equal(3, progress.TotalSteps); + Assert.Empty(progress.Details); + } + + [Fact] + public void Report_WithoutStart_TotalStepsNeverLessThanStep() + { + var operationId = Guid.NewGuid(); + + _tracker.Report(operationId, 2, "Step two"); + + var progress = _tracker.Get(operationId); + Assert.NotNull(progress); + Assert.Equal(2, progress.TotalSteps); + Assert.Equal("Step 2 of 2: Step two", progress.Details[0].Message); + } + + [Fact] + public void Start_EmptyOperationId_IsIgnored() + { + _tracker.Start(Guid.Empty, 3); + + Assert.Null(_tracker.Get(Guid.Empty)); + } + + [Fact] + public void ReportDetail_SetsCurrentDetail() + { + var operationId = Guid.NewGuid(); + + _tracker.Report(operationId, 1, "Step"); + _tracker.ReportDetail(operationId, "Sub-step"); + + Assert.Equal("Sub-step", _tracker.Get(operationId)?.CurrentDetail); + } + + [Fact] + public void ReportDetail_EmptyOperationId_IsIgnored() + { + _tracker.ReportDetail(Guid.Empty, "Ignored"); + _tracker.CreateDetailReporter(Guid.Empty).Report("Ignored"); + + Assert.Null(_tracker.Get(Guid.Empty)); + } + + [Fact] + public void ReportDetail_TrimsLogToMaxDetails() + { + var operationId = Guid.NewGuid(); + + for (int i = 0; i < MigrationProgressTracker.MaxDetails + 10; i++) + { + _tracker.ReportDetail(operationId, $"Detail {i}"); + } + + var progress = _tracker.Get(operationId); + Assert.NotNull(progress); + Assert.Equal(MigrationProgressTracker.MaxDetails, progress.Details.Count); + Assert.Equal("Detail 10", progress.Details[0].Message); + } + + [Fact] + public void Get_ReturnsSnapshot() + { + var operationId = Guid.NewGuid(); + _tracker.ReportDetail(operationId, "First"); + + var snapshot = _tracker.Get(operationId); + _tracker.ReportDetail(operationId, "Second"); + + Assert.Single(snapshot!.Details); + } + + [Fact] + public void Remove_DeletesProgress() + { + var operationId = Guid.NewGuid(); + _tracker.ReportDetail(operationId, "Detail"); + + _tracker.Remove(operationId); + + Assert.Null(_tracker.Get(operationId)); + } + + [Fact] + public void Complete_MarksSucceededAndAppendsMessage() + { + var operationId = Guid.NewGuid(); + _tracker.Start(operationId, 3); + _tracker.Report(operationId, 1, "First"); + _tracker.ReportDetail(operationId, "Working"); + + _tracker.Complete(operationId, "All done"); + + var progress = _tracker.Get(operationId); + Assert.NotNull(progress); + Assert.Equal(MigrationStatus.Succeeded, progress.Status); + Assert.Equal(3, progress.Step); + Assert.Equal("All done", progress.Message); + Assert.Null(progress.CurrentDetail); + Assert.NotNull(progress.FinishedAt); + Assert.Equal("All done", progress.Details[^1].Message); + } + + [Fact] + public void TakeFinished_ReturnsAndRemovesSucceededRun() + { + var operationId = Guid.NewGuid(); + _tracker.Complete(operationId, "Done"); + + var progress = _tracker.TakeFinished(operationId); + + Assert.NotNull(progress); + Assert.Equal("Done", progress.Message); + Assert.Null(_tracker.Get(operationId)); + Assert.Null(_tracker.TakeFinished(operationId)); + } + + [Fact] + public void TakeFinished_RunningOperation_ReturnsNullAndKeepsIt() + { + var operationId = Guid.NewGuid(); + _tracker.Start(operationId, 2); + + Assert.Null(_tracker.TakeFinished(operationId)); + Assert.NotNull(_tracker.Get(operationId)); + } + + [Fact] + public void Fail_MarksFailedAndKeepsCurrentStep() + { + var operationId = Guid.NewGuid(); + _tracker.Start(operationId, 4); + _tracker.Report(operationId, 2, "Second"); + + _tracker.Fail(operationId, "Broken"); + + var progress = _tracker.Get(operationId); + Assert.NotNull(progress); + Assert.Equal(MigrationStatus.Failed, progress.Status); + Assert.Equal(2, progress.Step); + Assert.Equal("Broken", progress.Message); + Assert.NotNull(progress.FinishedAt); + Assert.Equal("Broken", progress.Details[^1].Message); + } + + [Fact] + public void TakeFinished_ReturnsAndRemovesFailedRun() + { + var operationId = Guid.NewGuid(); + _tracker.Fail(operationId, "Broken"); + + var progress = _tracker.TakeFinished(operationId); + + Assert.Equal(MigrationStatus.Failed, progress?.Status); + Assert.Null(_tracker.Get(operationId)); + } + + [Fact] + public void Complete_EmptyOperationId_IsIgnored() + { + _tracker.Complete(Guid.Empty, "Ignored"); + + Assert.Null(_tracker.Get(Guid.Empty)); + } +} diff --git a/CloneDevOpsTemplateTest/Services/BoardServiceTest.cs b/CloneDevOpsTemplateTest/Services/BoardServiceTest.cs index ce6e98f..24c56fd 100644 --- a/CloneDevOpsTemplateTest/Services/BoardServiceTest.cs +++ b/CloneDevOpsTemplateTest/Services/BoardServiceTest.cs @@ -759,7 +759,7 @@ public async Task MoveCardStylesAsync_ShouldMoveCardStyles() ItExpr.Is(req => req.RequestUri != null && req.RequestUri.ToString().Contains("/cardrulesettings")), ItExpr.IsAny() ) - .ReturnsAsync(new HttpResponseMessage + .ReturnsAsync(() => new HttpResponseMessage { StatusCode = System.Net.HttpStatusCode.OK, Content = JsonContent.Create(templateCardStyles) @@ -794,4 +794,54 @@ public async Task MoveCardStylesAsync_ShouldMoveCardStyles() ItExpr.IsAny() ); } + + [Fact] + public async Task MoveBoardRowsAsync_UpdateFails_ReturnsErrorWithBoardName() + { + // Arrange + var projectBoards = new Boards { Value = [new BoardValue { Id = Guid.NewGuid(), Name = "Stories" }] }; + var templateBoards = new Boards { Value = [new BoardValue { Id = Guid.NewGuid(), Name = "stories" }] }; + + _httpMessageHandlerMock.Protected() + .Setup>("SendAsync", ItExpr.IsAny(), ItExpr.IsAny()) + .ReturnsAsync((HttpRequestMessage req, CancellationToken _) => + { + if (req.Method == HttpMethod.Put) + { + return new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden) { ReasonPhrase = "Forbidden" }; + } + + return req.RequestUri!.AbsolutePath.EndsWith("/rows") + ? new HttpResponseMessage { Content = JsonContent.Create(new BoardRows()) } + : new HttpResponseMessage { Content = JsonContent.Create(templateBoards) }; + }); + + // Act + var result = await _boardService.MoveBoardRowsAsync(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), projectBoards); + + // Assert + Assert.Equal(["Board 'stories': updating rows failed (403 Forbidden)."], result.Errors); + } + + [Fact] + public async Task ForAllMatchingBoards_AwaitsEachMoveBeforeReturning() + { + // Arrange + var projectBoards = new Boards { Value = [new BoardValue { Id = Guid.NewGuid(), Name = "Board1" }] }; + _httpMessageHandlerMock.Protected() + .Setup>("SendAsync", ItExpr.IsAny(), ItExpr.IsAny()) + .ReturnsAsync(() => new HttpResponseMessage { Content = JsonContent.Create(new Boards { Value = [new BoardValue { Id = Guid.NewGuid(), Name = "Board1" }] }) }); + var finished = false; + + // Act + var result = await _boardService.ForAllMatchingBoards(Guid.NewGuid(), Guid.NewGuid(), projectBoards, async (_, _, _) => + { + await Task.Delay(20); + finished = true; + }); + + // Assert + Assert.True(result.Succeeded); + Assert.True(finished); + } } diff --git a/CloneDevOpsTemplateTest/Services/IterationServiceTest.cs b/CloneDevOpsTemplateTest/Services/IterationServiceTest.cs index e6ea262..53d2ac5 100644 --- a/CloneDevOpsTemplateTest/Services/IterationServiceTest.cs +++ b/CloneDevOpsTemplateTest/Services/IterationServiceTest.cs @@ -350,4 +350,91 @@ public async Task DeleteAsync_DeletesAllIterationsRecursively() ItExpr.IsAny() ); } -} \ No newline at end of file + + [Fact] + public async Task CreateAsync_Bulk_UsesFullPathForNestedNodes() + { + // Arrange + var projectId = Guid.NewGuid(); + var requestedUris = new List(); + var nodes = new Iteration + { + Children = + [ + new Iteration + { + Name = "A", + Children = [new Iteration { Name = "B", Children = [new Iteration { Name = "C" }] }] + } + ] + }; + + _httpMessageHandlerMock.Protected() + .Setup>("SendAsync", ItExpr.IsAny(), ItExpr.IsAny()) + .Callback((req, _) => requestedUris.Add(Uri.UnescapeDataString(req.RequestUri!.AbsolutePath))) + .ReturnsAsync(() => new HttpResponseMessage(HttpStatusCode.Created)); + + // Act + var result = await _iterationService.CreateAsync(projectId, nodes, TreeStructureGroup.Iterations, ""); + + // Assert + Assert.True(result.Succeeded); + Assert.Collection(requestedUris, + uri => Assert.EndsWith("/classificationNodes/Iterations/", uri), + uri => Assert.EndsWith("/classificationNodes/Iterations/A", uri), + uri => Assert.EndsWith("/classificationNodes/Iterations/A/B", uri)); + } + + [Fact] + public async Task CreateAsync_Bulk_ReportsFailureAndSkipsChildrenOfFailedNode() + { + // Arrange + var projectId = Guid.NewGuid(); + var nodes = new Iteration + { + Children = + [ + new Iteration { Name = "Broken", Children = [new Iteration { Name = "Child" }] }, + new Iteration { Name = "Fine" } + ] + }; + + _httpMessageHandlerMock.Protected() + .Setup>("SendAsync", ItExpr.IsAny(), ItExpr.IsAny()) + .ReturnsAsync((HttpRequestMessage req, CancellationToken _) => + { + var body = req.Content!.ReadAsStringAsync().Result; + return body.Contains("Broken") + ? new HttpResponseMessage(HttpStatusCode.BadRequest) { ReasonPhrase = "Bad Request", Content = JsonContent.Create(new ErrorResponse { Message = "TF1: Invalid name." }) } + : new HttpResponseMessage(HttpStatusCode.Created); + }); + + // Act + var result = await _iterationService.CreateAsync(projectId, nodes, TreeStructureGroup.Areas, ""); + + // Assert + Assert.Equal(["Creating 'Broken' failed (400 Bad Request: TF1: Invalid name.)."], result.Errors); + _httpMessageHandlerMock.Protected().Verify("SendAsync", Times.Exactly(2), ItExpr.IsAny(), ItExpr.IsAny()); + } + + [Fact] + public async Task DeleteAsync_Bulk_ReportsFailedDeletes() + { + // Arrange + var projectId = Guid.NewGuid(); + var nodes = new Iteration { Children = [new Iteration { Name = "Sprint 1" }, new Iteration { Name = "Sprint 2" }] }; + + _httpMessageHandlerMock.Protected() + .Setup>("SendAsync", ItExpr.IsAny(), ItExpr.IsAny()) + .ReturnsAsync((HttpRequestMessage req, CancellationToken _) => + Uri.UnescapeDataString(req.RequestUri!.AbsolutePath).EndsWith("Sprint 2") + ? new HttpResponseMessage(HttpStatusCode.NotFound) { ReasonPhrase = "Not Found" } + : new HttpResponseMessage(HttpStatusCode.NoContent)); + + // Act + var result = await _iterationService.DeleteAsync(projectId, TreeStructureGroup.Iterations, nodes); + + // Assert + Assert.Equal(["Removing 'Sprint 2' failed (404 Not Found)."], result.Errors); + } +}