private bool EvalTestPartPredicate(IDeclaredElement element, Predicate <TestPart> predicate) { if (!element.IsValid()) { return(false); } try { #if RESHARPER_60 var reflectionPolicy = new PsiReflectionPolicy(element.GetPsiServices().PsiManager); #else var reflectionPolicy = new PsiReflectionPolicy(element.GetPsiServices().PsiManager, provider.CacheManager); #endif var elementInfo = reflectionPolicy.Wrap(element); if (elementInfo == null) { return(false); } var driver = CreateTestDriver(); var testParts = driver.GetTestParts(reflectionPolicy, elementInfo); return(GenericCollectionUtils.Exists(testParts, predicate)); } catch (Exception ex) { HandleEmbeddedProcessCancelledException(ex); throw; } }
protected override IList <TestPart> GetTestPartsImpl(IReflectionPolicy reflectionPolicy, ICodeElementInfo codeElement) { bool copied = false; IList <TestPart> combinedTestParts = null; ForEachDriver(testFrameworkManager.SelectTestFrameworksForCodeElementsImpl( testFrameworkHandles, testFrameworkFallbackMode, testFrameworkOptions, new[] { codeElement }), (driver, items, driverCount) => { IList <TestPart> testParts = driver.GetTestParts(reflectionPolicy, codeElement); if (testParts.Count != 0) { if (combinedTestParts == null) { combinedTestParts = testParts; } else { if (!copied) { combinedTestParts = new List <TestPart>(combinedTestParts); copied = true; } GenericCollectionUtils.AddAll(testParts, combinedTestParts); } } return(false); }); return(combinedTestParts ?? EmptyArray <TestPart> .Instance); }
/// <summary> /// Constructs an assertion failure. /// </summary> /// <param name="native">The native unmanged object describing the failure.</param> /// <param name="stringResolver">A service to resolve unmanaged unicode strings.</param> public MbUnitCppAssertionFailure(NativeAssertionFailure native, IStringResolver stringResolver) { description = stringResolver.GetString(native.DescriptionId); message = stringResolver.GetString(native.MessageId); hasActualValue = native.ActualValue.IsValid; hasExpectedValue = native.ExpectedValue.IsValid; hasUnexpectedValue = native.UnexpectedValue.IsValid; line = native.Line; if (hasActualValue) { actualValue = NativeValueParser.Parse(stringResolver.GetString(native.ActualValue.ValueId), native.ActualValue.ValueType); } if (hasExpectedValue) { expectedValue = NativeValueParser.Parse(stringResolver.GetString(native.ExpectedValue.ValueId), native.ExpectedValue.ValueType); } if (hasUnexpectedValue) { unexpectedValue = NativeValueParser.Parse(stringResolver.GetString(native.UnexpectedValue.ValueId), native.UnexpectedValue.ValueType); } diffing = hasActualValue && (native.ActualValue.ValueType == NativeValueType.String) && ((hasExpectedValue && (native.ExpectedValue.ValueType == NativeValueType.String)) || (hasUnexpectedValue && (native.UnexpectedValue.ValueType == NativeValueType.String))); extraLabeledValues = GenericCollectionUtils.ToArray(GetExtraLabeledValues(native, stringResolver)); }
public ProjectController(IProjectTreeModel projectTreeModel, IEventAggregator eventAggregator, IFileSystem fileSystem, IFileWatcher fileWatcher, IUnhandledExceptionPolicy unhandledExceptionPolicy, ITestProjectManager testProjectManager) { this.projectTreeModel = projectTreeModel; this.eventAggregator = eventAggregator; this.fileSystem = fileSystem; this.fileWatcher = fileWatcher; this.unhandledExceptionPolicy = unhandledExceptionPolicy; this.testProjectManager = testProjectManager; TestFilters = new Observable <IList <FilterInfo> >(new List <FilterInfo>()); TestFilters.PropertyChanged += (s, e) => { if (updating) { return; } projectTreeModel.TestProject.ClearTestFilters(); GenericCollectionUtils.ForEach(TestFilters.Value, x => projectTreeModel.TestProject.AddTestFilter(x)); }; fileWatcher.FileChangedEvent += delegate(string fullPath) { string fileName = Path.GetFileName(fullPath); EventHandlerPolicy.SafeInvoke(FileChanged, this, new FileChangedEventArgs(fileName)); }; }
/// <inheritdoc /> public bool Equals(BinaryAttachment other) { return(other != null && Name == other.Name && ContentType == other.ContentType && GenericCollectionUtils.ElementsEqual(bytes, other.bytes)); }
private bool EvalTestPartPredicate(IDeclaredElement element, Predicate <TestPart> predicate) { #if RESHARPER_45_OR_NEWER using (ReadLockCookie.Create()) #endif { if (!element.IsValid()) { return(false); } try { PsiReflectionPolicy reflectionPolicy = new PsiReflectionPolicy(element.GetManager()); ICodeElementInfo elementInfo = reflectionPolicy.Wrap(element); if (elementInfo == null) { return(false); } ITestDriver driver = CreateTestDriver(); IList <TestPart> testParts = driver.GetTestParts(reflectionPolicy, elementInfo); return(GenericCollectionUtils.Exists(testParts, predicate)); } catch (Exception ex) { HandleEmbeddedProcessCancelledException(ex); throw; } } }
public void BindValues(string document, char fieldDelimiter, char commentPrefix, bool hasHeader, int?bindingIndex, string bindingPath, string[] expectedValues) { Gallio.Common.GallioFunc <TextReader> documentReaderProvider = delegate { return(new StringReader(document)); }; CsvDataSet dataSet = new CsvDataSet(documentReaderProvider, false); dataSet.FieldDelimiter = fieldDelimiter; Assert.AreEqual(fieldDelimiter, dataSet.FieldDelimiter); dataSet.CommentPrefix = commentPrefix; Assert.AreEqual(commentPrefix, dataSet.CommentPrefix); dataSet.HasHeader = hasHeader; Assert.AreEqual(hasHeader, dataSet.HasHeader); DataBinding binding = new DataBinding(bindingIndex, bindingPath); List <IDataItem> items = new List <IDataItem>(dataSet.GetItems(new DataBinding[] { binding }, true)); string[] actualValues = GenericCollectionUtils.ConvertAllToArray <IDataItem, string>(items, delegate(IDataItem item) { return((string)item.GetValue(binding)); }); Assert.AreEqual(expectedValues, actualValues); }
private static Type[] ResolveParameterTypes(ICollection <IParameterInfo> parameters) { return(GenericCollectionUtils.ConvertAllToArray <IParameterInfo, Type>(parameters, delegate(IParameterInfo parameter) { return parameter.ValueType.Resolve(true); })); }
/// <inheritdoc /> protected override int RunImpl(string[] args) { if (!ParseArguments(args)) { ShowHelp(); return(1); } if (Arguments.Help) { ShowHelp(); return(0); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var runtimeSetup = new RuntimeSetup(); GenericCollectionUtils.ForEach(Arguments.PluginDirectories, x => runtimeSetup.AddPluginDirectory(x)); ILogger logger = new FilteredLogger(new RichConsoleLogger(Console), Verbosity.Normal); using (RuntimeBootstrap.Initialize(runtimeSetup, logger)) { IControlPanelPresenter presenter = RuntimeAccessor.Instance.ServiceLocator.Resolve <IControlPanelPresenter>(); presenter.Show(null); } return(0); }
/// <inheritdoc /> public string ResolveResourcePath(Uri resourceUri) { if (resourceUri == null) { throw new ArgumentNullException("resourceUri"); } if (resourceUri.IsFile) { return(Path.GetFullPath(resourceUri.LocalPath)); } if (resourceUri.Scheme == @"plugin") { string pluginId = resourceUri.Host; string relativePath = resourceUri.PathAndQuery; IPluginDescriptor plugin = GenericCollectionUtils.Find(registry.Plugins, p => string.Compare(pluginId, p.PluginId, true) == 0); if (plugin == null) { throw new RuntimeException(String.Format("Could not resolve resource uri '{0}' because no plugin appears to be registered with the requested id.", resourceUri)); } string pluginPath = plugin.BaseDirectory.FullName; if (relativePath.Length == 0 || relativePath == @"/") { return(pluginPath); } string relativeLocalPath = relativePath.Substring(1).Replace('/', Path.DirectorySeparatorChar); return(Path.Combine(pluginPath, relativeLocalPath)); } throw new RuntimeException(String.Format("Could not resolve resource uri '{0}' because the scheme was not recognized. The uri scheme must be 'file' or 'plugin'.", resourceUri)); }
/// <inheritdoc /> protected override IEnumerable <IDataItem> GetItemsImpl(ICollection <DataBinding> bindings, bool includeDynamicItems) { IDataProvider[] providers = GenericCollectionUtils.ToArray(DataSets); int providerCount = providers.Length; var bindingsPerProvider = new List <DataBinding> [providerCount]; for (int i = 0; i < providerCount; i++) { bindingsPerProvider[i] = new List <DataBinding>(); } foreach (DataBinding binding in bindings) { ResolvedBinding resolvedBinding = ResolveBinding(binding); if (resolvedBinding != null) { bindingsPerProvider[resolvedBinding.DataSetInfo.DataSetIndex].Add(resolvedBinding.Inner); } } foreach (IList <IDataItem> itemList in strategy.Join(providers, bindingsPerProvider, includeDynamicItems)) { yield return(new JoinedDataItem(this, itemList)); } }
/// <inheritdoc /> public IEnumerable <IDataItem> Merge(IList <IDataProvider> providers, ICollection <DataBinding> bindings, bool includeDynamicItems) { var previousValues = new GallioHashSet <object[]>(new ArrayEqualityComparer <object>()); foreach (IDataProvider provider in providers) { foreach (IDataItem item in provider.GetItems(bindings, includeDynamicItems)) { try { object[] values = GenericCollectionUtils.ConvertAllToArray <DataBinding, object>(bindings, delegate(DataBinding binding) { return(item.GetValue(binding)); }); if (previousValues.Contains(values)) { continue; } previousValues.Add(values); } catch { // Always consider items whose bindings cannot be evaluated correctly as distinct. } yield return(item); } } }
private void DoRegisterExtensions(ITestRunner runner, TestProject consolidatedTestProject) { if (EchoResults) { runner.RegisterExtension(new LogExtension()); } foreach (ITestRunnerExtension extension in consolidatedTestProject.TestRunnerExtensions) { runner.RegisterExtension(extension); } // de-dupe extension specs List <string> uniqueExtensionSpecifications = new List <string>(); GenericCollectionUtils.AddAllIfNotAlreadyPresent(consolidatedTestProject.TestRunnerExtensionSpecifications, uniqueExtensionSpecifications); foreach (string extensionSpecification in uniqueExtensionSpecifications) { var testRunnerExtension = TestRunnerExtensionUtils.CreateExtensionFromSpecification(extensionSpecification); runner.RegisterExtension(testRunnerExtension); } }
protected override void ShowHelp() { // Show argument only help first because what we do next might take a little while // and we want to make the program appear responsive. base.ShowHelp(); // Print out options related to the currently available set of plugins. var setup = new RuntimeSetup(); if (Arguments != null && Arguments.PluginDirectories != null) { GenericCollectionUtils.ForEach(Arguments.PluginDirectories, x => setup.AddPluginDirectory(x)); } using (RuntimeBootstrap.Initialize(setup, CreateLogger())) { IReportManager reportManager = RuntimeAccessor.ServiceLocator.Resolve <IReportManager>(); ShowRegisteredComponents("Supported report types:", reportManager.FormatterHandles, h => h.GetTraits().Name, h => h.GetTraits().Description); ITestRunnerManager runnerManager = RuntimeAccessor.ServiceLocator.Resolve <ITestRunnerManager>(); ShowRegisteredComponents("Supported runner types:", runnerManager.TestRunnerFactoryHandles, h => h.GetTraits().Name, h => h.GetTraits().Description); } }
private static Type[] ResolveTypesWithMethodContext(ICollection <ITypeInfo> types, MethodInfo methodContext) { return(GenericCollectionUtils.ConvertAllToArray <ITypeInfo, Type>(types, delegate(ITypeInfo argument) { return ResolveTypeWithMethodContext(argument, methodContext); })); }
public void RunFixtureRepeatedly() { TestStepRun fixtureRun = Runner.GetPrimaryTestStepRun(CodeReference.CreateFromType(typeof(ThreadedRepeatFixtureSample))); AssertLogContains(fixtureRun, "9 of 10 threaded repetitions passed."); Assert.AreEqual(TestOutcome.Failed, fixtureRun.Result.Outcome); IList <TestStepRun> fixtureSteps = fixtureRun.Children; Assert.Count(10, fixtureSteps, "Expected 10 repetitions represented as steps."); for (int i = 0; i < 10; i++) { string name = "Threaded Repetition #" + (i + 1); TestStepRun fixtureStep = GenericCollectionUtils.Find(fixtureSteps, candidate => candidate.Step.Name == name); Assert.Count(1, fixtureStep.Children); TestStepRun testRun = fixtureStep.Children[0]; AssertLogContains(testRun, "Run: " + name); if (i == 1) { Assert.AreEqual(TestOutcome.Failed, fixtureStep.Result.Outcome); Assert.AreEqual(TestOutcome.Failed, testRun.Result.Outcome); AssertLogContains(testRun, "Boom", MarkupStreamNames.Failures); } else { Assert.AreEqual(TestOutcome.Passed, fixtureStep.Result.Outcome); Assert.AreEqual(TestOutcome.Passed, testRun.Result.Outcome); } } }
public void Selects_ok() { var input = new[] { "1", "2", "3" }; var output = GenericCollectionUtils.Select(input, x => Int32.Parse(x)); Assert.AreElementsEqual(new[] { 1, 2, 3 }, output); }
private static bool ParseImpl(string value, out ReportArchive reportArchive, bool throwOnFailure) { if (String.IsNullOrEmpty(value)) { reportArchive = Normal; return(true); } foreach (ReportArchive item in All) { if (item.Value.ToString().Equals(value, StringComparison.OrdinalIgnoreCase)) { reportArchive = item; return(true); } } if (throwOnFailure) { string[] names = GenericCollectionUtils.ToArray(GenericCollectionUtils.Select(All, x => x.Value.ToString())); throw new ArgumentException(String.Format("Invalid report archive mode '{0}'. It must be one of the following values: {1}.", value, String.Join(", ", names))); } reportArchive = Normal; return(false); }
private RuntimeSetup CreateRuntimeSetup() { var runtimeSetup = new RuntimeSetup(); GenericCollectionUtils.ForEach(Arguments.PluginDirectories, runtimeSetup.AddPluginDirectory); return(runtimeSetup); }
private static Attribute[] HasAttributesImpl(Type attributeType, int expectedCount, MemberInfo target, string messageFormat, params object[] messageArgs) { Attribute[] result = GenericCollectionUtils.ToArray(GetAttributes(attributeType, target)); AssertionHelper.Verify(() => { string message = null; if (result.Length == 0) { message = "Expected the searched attribute to decorate the target object; but none was found."; } else if (expectedCount > 0 && result.Length != expectedCount) { message = String.Format("Expected to find {0} attribute instance{1} but found {2}.", expectedCount, expectedCount > 1 ? "s" : String.Empty, result.Length); } if (message == null) { return(null); } return(new AssertionFailureBuilder(message) .AddRawLabeledValue("Target Object", target) .AddRawLabeledValue("Attribute Type", attributeType) .SetMessage(messageFormat, messageArgs) .ToAssertionFailure()); }); return(result); }
private void AssertContainsStaticVersionsOfDeclaredMethods(Type sourceType, params string[] excludedMethodNames) { foreach (MethodInfo sourceMethod in sourceType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)) { if (Array.IndexOf(excludedMethodNames, sourceMethod.Name) >= 0) { continue; } Type[] parameterTypes = GenericCollectionUtils.ConvertAllToArray <ParameterInfo, Type>(sourceMethod.GetParameters(), delegate(ParameterInfo parameter) { return(parameter.ParameterType); }); MethodInfo targetMethod = typeof(TestLog).GetMethod(sourceMethod.Name, BindingFlags.Static | BindingFlags.Public, null, parameterTypes, null); Assert.IsNotNull(targetMethod, "Log is missing a static method '{0}({1})' corresponding to those defined by type {2}", sourceMethod.Name, string.Join(", ", Array.ConvertAll <Type, string>(parameterTypes, delegate(Type type) { return(type.Name); })), sourceType.FullName); Assert.AreEqual(sourceMethod.ReturnType, targetMethod.ReturnType); TestLog.WriteLine("Found method '{0}'", sourceMethod.Name); } }
private void InitializeAvailableReportTypes() { IReportManager reportManager = RuntimeAccessor.ServiceLocator.Resolve <IReportManager>(); types = new List <ReportFormatterTraits>(GenericCollectionUtils.Select(reportManager.FormatterHandles, x => x.GetTraits())); typeNames = new List <string>(GenericCollectionUtils.Select(types, x => x.Name)); comboBoxOutputReportType.Items.AddRange(GenericCollectionUtils.ToArray(types)); }
public void ConvertAndCopyAll(int[] input, int outputLength, string[] expectedOutput) { string[] output = new string[outputLength]; GenericCollectionUtils.ConvertAndCopyAll(input, output, value => value.ToString()); Assert.AreEqual(expectedOutput, output); }
private static ComponentHandle <IFileTypeRecognizer, FileTypeRecognizerTraits>[] CreateRecognizerHandles( params RecognizerInfo[] recognizerInfos) { return(GenericCollectionUtils.ConvertAllToArray(recognizerInfos, recognizerInfo => ComponentHandle.CreateStub("component", recognizerInfo.Recognizer ?? MockRepository.GenerateStub <IFileTypeRecognizer>(), recognizerInfo.Traits ?? new FileTypeRecognizerTraits("Dummy", "Dummy")))); }
private static T FindByName <T>(IEnumerable <T> elements, string name) where T : ICodeElementInfo { return(GenericCollectionUtils.Find(elements, delegate(T element) { return element.Name == name; })); }
/// <inheritdoc /> protected override int RunImpl(string[] args) { if (!ParseArguments(args)) { ShowHelp(); return(1); } if (Arguments.Help) { ShowHelp(); return(0); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); UnhandledErrorPolicy(); var runtimeSetup = new RuntimeSetup { RuntimePath = Path.GetDirectoryName(AssemblyUtils.GetFriendlyAssemblyLocation( typeof(IcarusProgram).Assembly)) }; var runtimeLogger = new RuntimeLogger(); GenericCollectionUtils.ForEach(Arguments.PluginDirectories, runtimeSetup.AddPluginDirectory); using (RuntimeBootstrap.Initialize(runtimeSetup, runtimeLogger)) { // wire up services & components var scanner = new DefaultConventionScanner(RuntimeAccessor.Registry); scanner.Scan("Gallio.Icarus", Assembly.GetExecutingAssembly()); LoadPackages(); var optionsController = RuntimeAccessor.ServiceLocator.Resolve <IOptionsController>(); // create & initialize a test runner whenever the test runner factory is changed optionsController.TestRunnerFactory.PropertyChanged += (s, e) => ConfigureTestRunnerFactory(optionsController.TestRunnerFactory); ConfigureTestRunnerFactory(optionsController.TestRunnerFactory); var runtimeLogController = RuntimeAccessor.ServiceLocator.Resolve <IRuntimeLogController>(); runtimeLogController.SetLogger(runtimeLogger); var applicationController = RuntimeAccessor.ServiceLocator.Resolve <IApplicationController>(); applicationController.Arguments = Arguments; ErrorDialogUnhandledExceptionHandler.RunApplicationWithHandler(new Main(applicationController)); UnloadPackages(); } return(ResultCode.Success); }
public IList <IComponentDescriptor> GetComponents() { if (components == null) { components = new ReadOnlyCollection <IComponentDescriptor>(GenericCollectionUtils.ToArray(componentsByComponentId.Values)); } return(components); }
public IList <IServiceDescriptor> GetServices() { if (services == null) { services = new ReadOnlyCollection <IServiceDescriptor>(GenericCollectionUtils.ToArray(servicesByServiceId.Values)); } return(services); }
public IList <IPluginDescriptor> GetPlugins() { if (plugins == null) { plugins = new ReadOnlyCollection <IPluginDescriptor>(GenericCollectionUtils.ToArray(pluginsByPluginId.Values)); } return(plugins); }
/// <summary> /// Creates an AND-filter. /// </summary> /// <param name="filters">The filters that must all jointly be matched. /// If the list is empty, the filter matches everything.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="filters"/> is null.</exception> public AndFilter(ICollection <Filter <T> > filters) { if (filters == null || filters.Contains(null)) { throw new ArgumentNullException("filters"); } this.filters = GenericCollectionUtils.ToArray(filters); }