PageRenderTime 8ms CodeModel.GetById 1ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 1ms

/Mercurial.Net.Tests/RepositoryTestsBase.cs

#
C# | 74 lines | 68 code | 6 blank | 0 comment | 4 complexity | 9c29be96b8dd17001ca839a1ea20c102 MD5 | raw file
 1using System;
 2using System.Collections.Generic;
 3using System.Diagnostics;
 4using System.IO;
 5using System.Linq;
 6using System.Threading;
 7using NUnit.Framework;
 8
 9namespace Mercurial.Tests
10{
11    public class RepositoryTestsBase
12    {
13        private readonly List<string> _Repositories = new List<string>();
14        private readonly List<string> _TempFiles = new List<string>();
15
16        protected Repository GetRepository()
17        {
18            string repoPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString().Replace("-", string.Empty).ToLowerInvariant());
19            Directory.CreateDirectory(repoPath);
20            _Repositories.Add(repoPath);
21            if (Environment.GetEnvironmentVariable("PERSISTENTCLIENT") == "1")
22                return new Repository(repoPath, new AutoSwitchingClientFactory());
23            return new Repository(repoPath, new NonPersistentClientFactory());
24        }
25
26        protected string GetTempFileName()
27        {
28            string result = Path.GetTempFileName();
29            _TempFiles.Add(result);
30            return result;
31        }
32
33        [TearDown]
34        public virtual void TearDown()
35        {
36            foreach (string repo in _Repositories)
37                DeleteTempDirectory(repo);
38            foreach (string path in _TempFiles.Where(File.Exists))
39                File.Delete(path);
40        }
41
42        private static void DeleteTempDirectory(string path)
43        {
44            for (int index = 1; index < 5; index++)
45            {
46                try
47                {
48                    if (Directory.Exists(path))
49                        Directory.Delete(path, true);
50                    break;
51                }
52                catch (DirectoryNotFoundException)
53                {
54                }
55                catch (Exception ex)
56                {
57                    Debug.WriteLine("exception while cleaning up repository directory: " + ex.GetType().Name + ": " + ex.Message);
58                    Thread.Sleep(1000);
59                }
60            }
61        }
62
63        protected static void WriteTextFileAndCommit(Repository repo, string fileName, string contents, string commitMessage, bool addRemove)
64        {
65            File.WriteAllText(Path.Combine(repo.Path, fileName), contents);
66            repo.Commit(
67                new CommitCommand
68                {
69                    Message = commitMessage,
70                    AddRemove = addRemove,
71                });
72        }
73    }
74}