public IntegrationTestEnvironment(ICacheContainer cacheContainer, NPath repoPath, NPath solutionDirectory, NPath environmentPath = null, bool enableTrace = false, bool initializeRepository = true) { defaultEnvironment = new DefaultEnvironment(cacheContainer); defaultEnvironment.FileSystem.SetCurrentDirectory(repoPath); environmentPath = environmentPath ?? defaultEnvironment.GetSpecialFolder(Environment.SpecialFolder.LocalApplicationData) .ToNPath() .EnsureDirectoryExists(ApplicationInfo.ApplicationName + "-IntegrationTests"); integrationTestEnvironmentPath = environmentPath; UserCachePath = integrationTestEnvironmentPath.Combine("User"); SystemCachePath = integrationTestEnvironmentPath.Combine("System"); var installPath = solutionDirectory.Parent.Parent.Combine("src", "GitHub.Api"); Initialize(UnityVersion, installPath, solutionDirectory, repoPath.Combine("Assets")); if (initializeRepository) { InitializeRepository(); } this.enableTrace = enableTrace; if (enableTrace) { logger.Trace("EnvironmentPath: \"{0}\" SolutionDirectory: \"{1}\" ExtensionInstallPath: \"{2}\"", environmentPath, solutionDirectory, ExtensionInstallPath); } }
/// <summary> /// 根据指定键获取或添加指定值。 /// </summary> /// <typeparam name="TResult">缓存容器值的强类型表示。</typeparam> /// <param name="container">一个缓存容器接口的实例对象。</param> /// <param name="key">缓存项的键。</param> /// <param name="newValueFunc">获取失败后待添加的新值委托。</param> /// <returns>获取得到的缓存项的值。</returns> /// <exception cref="System.ArgumentNullException">container or key or /// newValueFunc</exception> public static TResult GetOrAddXWithFunc <TResult>(this ICacheContainer container, string key, Func <Tuple <TResult, Expiration> > newValueFunc) { if (ReferenceEquals(container, null)) { throw new ArgumentNullException(string.Format("[ICacheContainerExtensions].[GetOrAddXWithFunc<{0}>].container", typeof(TResult).FullName)); } if (key == null) { throw new ArgumentNullException(string.Format("[ICacheContainerExtensions].[GetOrAddXWithFunc<{0}>].key", typeof(TResult).FullName)); } if (newValueFunc == null) { throw new ArgumentNullException(string.Format("[ICacheContainerExtensions].[GetOrAddXWithFunc<{0}>].newValueFunc", typeof(TResult).FullName)); } object value = null; if (container.TryGetValue(key, out value)) { return((TResult)value); } var newValue = newValueFunc(); container.Update(key, newValue.Item1, newValue.Item2); return(newValue.Item1); }
public User(ICacheContainer cacheContainer) { this.cacheContainer = cacheContainer; cacheContainer.GitUserCache.CacheInvalidated += GitUserCacheOnCacheInvalidated; cacheContainer.GitUserCache.CacheUpdated += GitUserCacheOnCacheUpdated; }
public IntegrationTestEnvironment(ICacheContainer cacheContainer, NPath repoPath, NPath solutionDirectory, NPath?environmentPath = null, bool enableTrace = false, bool initializeRepository = true) { defaultEnvironment = new DefaultEnvironment(cacheContainer); defaultEnvironment.FileSystem.SetCurrentDirectory(repoPath); environmentPath = environmentPath ?? defaultEnvironment.UserCachePath.EnsureDirectoryExists("IntegrationTests"); UserCachePath = environmentPath.Value.Combine("User"); SystemCachePath = environmentPath.Value.Combine("System"); var installPath = solutionDirectory.Parent.Parent.Combine("src", "GitHub.Api"); Initialize(UnityVersion, installPath, solutionDirectory, NPath.Default, repoPath.Combine("Assets")); InitializeRepository(initializeRepository ? (NPath?)repoPath : null); this.enableTrace = enableTrace; if (enableTrace) { logger.Trace("EnvironmentPath: \"{0}\" SolutionDirectory: \"{1}\" ExtensionInstallPath: \"{2}\"", environmentPath, solutionDirectory, ExtensionInstallPath); } }
/// <summary> /// 根据指定键获取或添加指定值。 /// </summary> /// <param name="container">一个缓存容器接口的实例对象。</param> /// <param name="key">缓存项的键。</param> /// <param name="newValueFunc">获取失败后待添加的新值委托。</param> /// <returns>获取得到的缓存项的值。</returns> /// <exception cref="System.ArgumentNullException">container or key or /// newValueFunc</exception> public static object GetOrAddWithFunc(this ICacheContainer container, string key, Func <Tuple <object, Expiration> > newValueFunc) { if (ReferenceEquals(container, null)) { throw new ArgumentNullException("[ICacheContainerExtensions].[GetOrAddWithFunc].container"); } if (key == null) { throw new ArgumentNullException("[ICacheContainerExtensions].[GetOrAddWithFunc].key"); } if (newValueFunc == null) { throw new ArgumentNullException("[ICacheContainerExtensions].[GetOrAddWithFunc].newValueFunc"); } object value = null; if (container.TryGetValue(key, out value)) { return(value); } var newValue = newValueFunc(); container.Update(key, newValue.Item1, newValue.Item2); return(newValue.Item1); }
/// <summary> /// Initializes a new instance of the <see cref="Repository"/> class. /// </summary> /// <param name="localPath"></param> /// <param name="container"></param> public Repository(NPath localPath, ICacheContainer container) { Guard.ArgumentNotNull(localPath, nameof(localPath)); LocalPath = localPath; cacheUpdateEvents = new Dictionary <CacheType, Action <CacheUpdateEvent> > { { CacheType.Branches, cacheUpdateEvent => { LocalBranchListChanged?.Invoke(cacheUpdateEvent); RemoteBranchListChanged?.Invoke(cacheUpdateEvent); LocalAndRemoteBranchListChanged?.Invoke(cacheUpdateEvent); } }, { CacheType.GitAheadBehind, c => TrackingStatusChanged?.Invoke(c) }, { CacheType.GitLocks, c => LocksChanged?.Invoke(c) }, { CacheType.GitLog, c => LogChanged?.Invoke(c) }, { CacheType.GitStatus, c => StatusEntriesChanged?.Invoke(c) }, { CacheType.GitUser, cacheUpdateEvent => { } }, { CacheType.RepositoryInfo, cacheUpdateEvent => { CurrentBranchChanged?.Invoke(cacheUpdateEvent); CurrentRemoteChanged?.Invoke(cacheUpdateEvent); CurrentBranchAndRemoteChanged?.Invoke(cacheUpdateEvent); } }, }; cacheContainer = container; cacheContainer.CacheInvalidated += CacheHasBeenInvalidated; cacheContainer.CacheUpdated += (cacheType, offset) => { cacheUpdateEvents[cacheType](new CacheUpdateEvent(cacheType, offset)); }; }
/// <summary> /// 根据指定键获取或添加指定值。 /// </summary> /// <typeparam name="TResult">缓存容器值的强类型表示。</typeparam> /// <param name="container">一个缓存容器接口的实例对象。</param> /// <param name="key">缓存项的键。</param> /// <param name="newValue">获取失败后待添加的新值。</param> /// <param name="expiration">缓存项的过期设置信息:<c>null</c> 表示使用缺省的过期设置。</param> /// <returns>获取得到的缓存项的值。</returns> /// <exception cref="System.ArgumentNullException">container or key or newValue</exception> public static TResult GetOrAddX <TResult>(this ICacheContainer container, string key, TResult newValue, Expiration expiration = null) { if (ReferenceEquals(container, null)) { throw new ArgumentNullException(string.Format("[ICacheContainerExtensions].[GetOrAddX<{0}>].container", typeof(TResult).FullName)); } if (key == null) { throw new ArgumentNullException(string.Format("[ICacheContainerExtensions].[GetOrAddX<{0}>].key", typeof(TResult).FullName)); } if (newValue == null) { throw new ArgumentNullException(string.Format("[ICacheContainerExtensions].[GetOrAddX<{0}>].newValue", typeof(TResult).FullName)); } object value = null; if (container.TryGetValue(key, out value)) { return((TResult)value); } container.Update(key, newValue, expiration); return(newValue); }
/// <summary> /// Registers the cache container. /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="cacheContainer">The cache container.</param> internal static void RegisterCacheContainer <TEntity>(ICacheContainer cacheContainer) { if (cacheContainer != null) { containers.Add(typeof(TEntity), cacheContainer); } }
public IntegrationTestEnvironment(ICacheContainer cacheContainer, NPath repoPath, NPath solutionDirectory, CreateEnvironmentOptions options = null, bool enableTrace = false, bool initializeRepository = true) { this.enableTrace = enableTrace; options = options ?? new CreateEnvironmentOptions(NPath.SystemTemp.Combine(ApplicationInfo.ApplicationName, "IntegrationTests")); defaultEnvironment = new DefaultEnvironment(cacheContainer); defaultEnvironment.FileSystem.SetCurrentDirectory(repoPath); var environmentPath = options.UserProfilePath; LocalAppData = environmentPath.Combine("User"); UserCachePath = LocalAppData.Combine("Cache"); CommonAppData = environmentPath.Combine("System"); SystemCachePath = CommonAppData.Combine("Cache"); var installPath = solutionDirectory.Parent.Parent.Parent.Combine("src", "com.unity.git.api", "Api"); Initialize(UnityVersion, installPath, solutionDirectory, NPath.Default, repoPath.Combine("Assets")); InitializeRepository(initializeRepository ? (NPath?)repoPath : null); GitDefaultInstallation = new GitInstaller.GitInstallDetails(UserCachePath, this); if (enableTrace) { logger.Trace("EnvironmentPath: \"{0}\" SolutionDirectory: \"{1}\" ExtensionInstallPath: \"{2}\"", environmentPath, solutionDirectory, ExtensionInstallPath); } }
/// <summary> /// 安全地获取缓存容器中的值。 /// </summary> /// <typeparam name="TResult">缓存容器值的强类型表示。</typeparam> /// <param name="container">一个缓存容器接口的实例对象。</param> /// <param name="key">缓存项的键。</param> /// <param name="defaultValue">获取失败后,要返回的缺省值。</param> /// <param name="throwIfException">如果设置为 <c>true</c> 表示错误后抛出异常。</param> /// <returns>获取得到的缓存项的值。</returns> /// <exception cref="System.ArgumentNullException">container or key</exception> public static TResult GetValueX <TResult>(this ICacheContainer container, string key, TResult defaultValue = default(TResult), bool throwIfException = true) { if (ReferenceEquals(container, null)) { throw new ArgumentNullException(string.Format("[ICacheContainerExtensions].[GetValueX<{0}>].container", typeof(TResult).FullName)); } if (key == null) { throw new ArgumentNullException(string.Format("[ICacheContainerExtensions].[GetValueX<{0}>].key", typeof(TResult).FullName)); } try { object value = null; if (container.TryGetValue(key, out value)) { return((TResult)value); } return(defaultValue); } catch { if (throwIfException) { throw; } else { return(defaultValue); } } }
protected async Task <IEnvironment> Initialize(NPath repoPath, NPath environmentPath = null, bool enableEnvironmentTrace = false, bool initializeRepository = true, Action <RepositoryManager> onRepositoryManagerCreated = null) { TaskManager = new TaskManager(); SyncContext = new ThreadSynchronizationContext(TaskManager.Token); TaskManager.UIScheduler = new SynchronizationContextTaskScheduler(SyncContext); //TODO: Mock CacheContainer ICacheContainer cacheContainer = Substitute.For <ICacheContainer>(); Environment = new IntegrationTestEnvironment(cacheContainer, repoPath, SolutionDirectory, environmentPath, enableEnvironmentTrace); var gitSetup = new GitInstaller(Environment, TaskManager.Token); await gitSetup.SetupIfNeeded(); Environment.GitExecutablePath = gitSetup.GitExecutablePath; Platform = new Platform(Environment); GitEnvironment = Platform.GitEnvironment; ProcessManager = new ProcessManager(Environment, GitEnvironment, TaskManager.Token); Platform.Initialize(ProcessManager, TaskManager); GitClient = new GitClient(Environment, ProcessManager, TaskManager); var repositoryManager = GitHub.Unity.RepositoryManager.CreateInstance(Platform, TaskManager, GitClient, repoPath); onRepositoryManagerCreated?.Invoke(repositoryManager); RepositoryManager = repositoryManager; RepositoryManager.Initialize(); if (initializeRepository) { Environment.Repository = new Repository(repoPath, cacheContainer); Environment.Repository.Initialize(RepositoryManager); } RepositoryManager.Start(); DotGitPath = repoPath.Combine(".git"); if (DotGitPath.FileExists()) { DotGitPath = DotGitPath.ReadAllLines() .Where(x => x.StartsWith("gitdir:")) .Select(x => x.Substring(7).Trim().ToNPath()) .First(); } BranchesPath = DotGitPath.Combine("refs", "heads"); RemotesPath = DotGitPath.Combine("refs", "remotes"); DotGitIndex = DotGitPath.Combine("index"); DotGitHead = DotGitPath.Combine("HEAD"); DotGitConfig = DotGitPath.Combine("config"); return(Environment); }
public TestData(string testName, ILogging logger, string testRepoName = null, bool withHttpServer = false, ICacheContainer cacheContainer = null, IFileSystem fileSystem = null) { TestName = testName; Logger = logger; Watch = new Stopwatch(); SourceDirectory = TestContext.CurrentContext.TestDirectory.ToSPath(); TestPath = SPath.CreateTempDirectory(testName); SPath.FileSystem = fileSystem ?? new FileSystem(TestPath); if (cacheContainer == null) { var container = new CacheContainer(); container.SetCacheInitializer(CacheType.Branches, () => BranchesCache.Instance); container.SetCacheInitializer(CacheType.GitAheadBehind, () => GitAheadBehindCache.Instance); container.SetCacheInitializer(CacheType.GitLocks, () => GitLocksCache.Instance); container.SetCacheInitializer(CacheType.GitLog, () => GitLogCache.Instance); container.SetCacheInitializer(CacheType.GitStatus, () => GitStatusCache.Instance); container.SetCacheInitializer(CacheType.GitUser, () => GitUserCache.Instance); container.SetCacheInitializer(CacheType.RepositoryInfo, () => RepositoryInfoCache.Instance); cacheContainer = container; } Environment = new IntegrationTestEnvironment(cacheContainer, TestPath, TestPath.Parent, testName); InitializeEnvironment(testRepoName); ApplicationManager = new ApplicationManagerBase(new MainThreadSynchronizationContext(), Environment); if (testRepoName != null) { var testZipFilePath = SourceDirectory.Combine("IOTestsRepo.zip"); ZipHelper.Instance.Extract(testZipFilePath, TestPath, (_, __) => { }, (value, total, name) => true, token: TaskManager.Token); TestRepo = new TestRepoData(this, testRepoName); InstallTestGit(); InitializeRepository(); } #if NUNIT if (withHttpServer) { var filesToServePath = SourceDirectory.Combine("files"); HttpServer = new HttpServer(filesToServePath, 0); var started = new ManualResetEventSlim(); var task = TaskManager.With(HttpServer.Start, TaskAffinity.None); task.OnStart += _ => started.Set(); task.Start(); started.Wait(); } #endif ((ApplicationManagerBase)ApplicationManager).Initialize(); Logger.Trace($"START {testName}"); Watch.Start(); }
protected IntegrationTestEnvironment CreateCleanEnvironment(ICacheContainer container, NPath repoPath, bool enableEnvironmentTrace = false) { return(new IntegrationTestEnvironment(container, repoPath, SolutionDirectory, new CreateEnvironmentOptions(NPath.CreateTempDirectory("gfu")), enableEnvironmentTrace, false)); }
/// <summary> /// Initializes a new instance of the <see cref="Repository"/> class. /// </summary> /// <param name="localPath"></param> /// <param name="container"></param> public Repository(NPath localPath, ICacheContainer container) { Guard.ArgumentNotNull(localPath, nameof(localPath)); LocalPath = localPath; cacheContainer = container; cacheContainer.CacheInvalidated += CacheContainer_OnCacheInvalidated; cacheContainer.CacheUpdated += CacheContainer_OnCacheUpdated; }
public DWGitshCommonArgs(IStaticAbstraction diskManager, IDWGitshConfig config, IRepositoryPaths repoPaths, IGitUtils utils, ICacheContainer cache) { this.DiskManager = diskManager ?? new StAbWrapper(); this.Config = config ?? new DWGitshConfig(DiskManager); this.Cache = cache ?? new CacheContainer(DiskManager); this.Utils = utils ?? new GitUtils(DiskManager, Cache); this.RepoPaths = repoPaths; }
// needed for unit testing internal GitUtils(IStaticAbstraction diskManager, ICacheContainer repoCache) : this() { if (diskManager != null) { _diskManager = diskManager; } if (repoCache != null) { RepoCache = repoCache; } Current = this; }
public void Setup() { _diskManager = Substitute.For <IStaticAbstraction>(); _pathManager = Substitute.For <IPath>(); _pathManager.Combine(Arg.Any <string>(), Arg.Any <string>()).Returns(x => { var data = x.Arg <string[]>(); return(data[0].TrimEnd('\\') + "\\" + data[1].TrimStart('\\')); }); _diskManager.Path.Returns(_pathManager); _cacheManager = Substitute.For <ICacheContainer>(); _gitUtils = new GitUtils(_diskManager, _cacheManager); }
public User(ICacheContainer cacheContainer) { this.cacheContainer = cacheContainer; cacheContainer.CacheInvalidated += (type) => { if (type == CacheType.GitUser) { GitUserCacheOnCacheInvalidated(); } }; cacheContainer.CacheUpdated += (type, dt) => { if (type == CacheType.GitUser) { CacheHasBeenUpdated(dt); } }; }
public ServiceConstructor(ICacheContainer cacheContainer, ICustomContext context, string username, Expression <Func <T, bool> > cacheLoadFilter = null, Func <IQueryable <T>, IIncludableQueryable <T, object> > includeInCache = null, int cacheTimeoutInMinutes = 10, bool isSharedContext = true) { CacheContainer = cacheContainer; Context = context; IsSharedContext = isSharedContext; CacheLoadFilter = cacheLoadFilter; CacheTimoutInMinutes = cacheTimeoutInMinutes; Username = username; IncludePropertiesInCache = includeInCache; }
/// <summary> /// 安全地获取缓存容器中的值。 /// </summary> /// <param name="container">一个缓存容器接口的实例对象。</param> /// <param name="key">缓存项的键。</param> /// <param name="defaultValue">获取失败后,要返回的缺省值。</param> /// <returns>获取得到的缓存项的值。</returns> /// <exception cref="System.ArgumentNullException">container or key</exception> public static object GetValue(this ICacheContainer container, string key, object defaultValue = null) { if (ReferenceEquals(container, null)) { throw new ArgumentNullException("[ICacheContainerExtensions].[GetValue].container"); } if (key == null) { throw new ArgumentNullException("[ICacheContainerExtensions].[GetValue].key"); } object value = null; if (container.TryGetValue(key, out value)) { return(value); } return(defaultValue); }
protected BaseService(IServiceConstructor <T> constructor) { CurrentUsername = constructor.Username; Context = constructor.Context; IsSharedContext = constructor.IsSharedContext; Repo = new GenericRepository <T, SqlParameter, int>(this.Context, CurrentUsername); CacheContainer = constructor.CacheContainer; cacheLoadFilter = constructor.CacheLoadFilter; cacheTimeoutInMinutes = constructor.CacheTimoutInMinutes; includePropertiesInCache = constructor.IncludePropertiesInCache; reloadMethod = async(context) => { IGenericRepository <T, int> repo = new GenericRepository <T, SqlParameter, int>(context, "System"); var data = await repo.GetAsync(cacheLoadFilter, includePropertiesInCache); var detachedData = data.Select(t => repo.CreateDetachedEntity(t)).ToList(); return(detachedData); }; }
/// <summary> /// 租借一个新的本地缓存容器 /// </summary> /// <typeparam name="K">缓存key类型</typeparam> /// <typeparam name="V">缓存对象类型</typeparam> /// <param name="category">分类名称</param> /// <param name="comparer">比较器 </param> /// <returns>返回本地缓存容器</returns> /// <exception cref="ArgumentNullException">参数不能为空</exception> public ICacheContainer <K, V> Rent <K, V>(string category, IEqualityComparer <K> comparer) { if (string.IsNullOrEmpty(category)) { throw new ArgumentNullException(nameof(category)); } lock (_lockObj) { //already has this container. if (_containers.ContainsKey(category)) { return(null); } ICacheContainer <K, V> container = comparer == null ? new CacheContainer <K, V>(category) : new CacheContainer <K, V>(category, comparer); _containers.Add(category, container); return(container); } }
/// <summary> /// 根据指定键获取或添加指定值。 /// </summary> /// <param name="container">一个缓存容器接口的实例对象。</param> /// <param name="key">缓存项的键。</param> /// <param name="newValue">获取失败后待添加的新值。</param> /// <param name="expiration">缓存项的过期设置信息:<c>null</c> 表示使用缺省的过期设置。</param> /// <returns>获取得到的缓存项的值。</returns> /// <exception cref="System.ArgumentNullException">container or key or newValue</exception> public static object GetOrAdd(this ICacheContainer container, string key, object newValue, Expiration expiration = null) { if (ReferenceEquals(container, null)) { throw new ArgumentNullException("[ICacheContainerExtensions].[GetOrAdd].container"); } if (key == null) { throw new ArgumentNullException("[ICacheContainerExtensions].[GetOrAdd].key"); } object value = null; if (container.TryGetValue(key, out value)) { return(value); } container.Update(key, newValue, expiration); return(newValue); }
protected async Task InitializePlatform(NPath repoPath, NPath environmentPath, bool enableEnvironmentTrace) { InitializeTaskManager(); CacheContainer = Substitute.For <ICacheContainer>(); Environment = new IntegrationTestEnvironment(CacheContainer, repoPath, SolutionDirectory, environmentPath, enableEnvironmentTrace); var gitSetup = new GitInstaller(Environment, TaskManager.Token); await gitSetup.SetupIfNeeded(); Environment.GitExecutablePath = gitSetup.GitExecutablePath; Platform = new Platform(Environment); GitEnvironment = Platform.GitEnvironment; ProcessManager = new ProcessManager(Environment, GitEnvironment, TaskManager.Token); Platform.Initialize(ProcessManager, TaskManager); GitClient = new GitClient(Environment, ProcessManager, TaskManager); }
protected ResourceBase(ResourceVolatility volatility) { Volatility = volatility; Subresources = new Dictionary <string, IResource>(); CacheContainer = new CacheContainer(); }
/// <summary> /// 初始化新建一个 <see cref="DefaultAuthenticationTokenValidator" /> 类的实例对象。 /// </summary> public DefaultAuthenticationTokenValidator() { _cache = ServiceLocator.Current.GetInstance <ICacheContainer>(); }
public ReportManager(ICacheContainer cache, UserContext userContext, GeminiContext geminiContext) : base(cache, userContext, geminiContext) { }
internal TestData StartTest(string testRepoName = null, bool withHttpServer = false, ICacheContainer cacheContainer = null, IFileSystem fileSystem = null, [CallerMemberName] string testName = "test") => new TestData(testName, new LogFacade(testName, new NUnitLogAdapter(), false), testRepoName, withHttpServer, cacheContainer, fileSystem);
public DefaultEnvironment(ICacheContainer cacheContainer) : this() { this.CacheContainer = cacheContainer; }
public IntegrationTestEnvironment(ICacheContainer cacheContainer, SPath testPath, SPath sharedTestPath, string applicationName) : this(testPath, sharedTestPath, applicationName) { this.CacheContainer = cacheContainer; }