public void GuardAgainstReentry_WithoutReentryTwice_WorksOk() { var session = new TestSession(); WorkWithoutReentry(session); WorkWithoutReentry(session); Assert.AreEqual(2, session.WorkCount); }
private void WorkWithoutReentry(TestSession session) { using (_sentry = Guard.AgainstReEntry(_sentry)) { session.DoWork(); } }
private void WorkWithReentry(TestSession session, int count) { using (_sentry = Guard.AgainstReEntry(_sentry)) { session.DoWork(); if (count == 0) { WorkWithReentry(session, count + 1); } } }
public void AllowsSettingSession_WithoutSettingUpSessionFeature_Upfront() { // Arrange var session = new TestSession(); var context = new DefaultHttpContext(); // Act context.Session = session; // Assert Assert.Same(session, context.Session); }
public void ShouldProvideTheEntityInstanceByItsId() { var entity = new Entity(); // We don't want to set up an ORM, // so we'll just fake ISession var session = new TestSession(); session.Stub<ISession>("Get").Return(entity); // Now let's execute a Web request var response = session.Get("/Sample/Get?entityId=1"); // Check the result Assert.AreEqual(entity, response.ActionMethodParameters["entity"]); }
private static void SaveTestReport(Core.Base.Arkade arkade, TestSession testSession, CommandLineOptions options) { var packageTestReport = new FileInfo(Path.Combine( testSession.GetReportDirectory().FullName, "report.html" )); arkade.SaveReport(testSession, packageTestReport); var standaloneTestReport = new FileInfo(Path.Combine( options.OutputDirectory, string.Format(OutputStrings.TestReportFileName, testSession.Archive.Uuid) )); arkade.SaveReport(testSession, standaloneTestReport); }
internal bool UpdateConfiguration(TestSession session) { var config = session.Configuration; var modified = ModifyConfiguration(config); bool done = false; if (ShowCategories) { Program.WriteLine("Test Categories:"); foreach (var category in session.ConfigurationProvider.Categories) { var builtinText = category.IsBuiltin ? " (builtin)" : string.Empty; var explicitText = category.IsExplicit ? " (explicit)" : string.Empty; var currentText = config.CurrentCategory != null && config.CurrentCategory.Name.Equals(category.Name) ? " (current)" : string.Empty; Program.WriteLine(" {0}{1}{2}{3}", category.Name, builtinText, explicitText, currentText); } Program.WriteLine(); done = true; } if (ShowFeatures) { Program.WriteLine("Test Features:"); foreach (var feature in session.ConfigurationProvider.Features) { var constText = feature.Constant != null?string.Format(" (const = {0})", feature.Constant.Value? "enabled" : "disabled") : string.Empty; var defaultText = feature.DefaultValue != null?string.Format(" (default = {0})", feature.DefaultValue.Value? "enabled" : "disabled") : string.Empty; var currentText = feature.CanModify ? string.Format(" ({0})", config.IsEnabled(feature) ? "enabled" : "disabled") : string.Empty; Program.WriteLine(" {0,-30} {1}{2}{3}{4}", feature.Name, feature.Description, constText, defaultText, currentText); } Program.WriteLine(); done = true; } if (done) { Environment.Exit(0); } if (modified && (saveSettings ?? false)) { SaveSettings(Settings, settingsFile); } return(modified); }
public ProviderPaymentModelMatcher(Provider provider, IPaymentsDataContext dataContext, TestSession testSession, CollectionPeriod currentCollectionPeriod, List <ProviderPayment> expectedPaymentInfo = null, ContractType contractType = default(ContractType)) { this.provider = provider; this.dataContext = dataContext; this.testSession = testSession; this.currentCollectionPeriod = currentCollectionPeriod; this.expectedPaymentInfo = expectedPaymentInfo; this.contractType = contractType; }
private async Task AddEmployerAccount(TestSession session) { var dataContext = Container.Resolve <IPaymentsDataContext>(); dataContext.LevyAccount.Add(new LevyAccountModel { AccountId = session.Ukprn, Balance = 1000000, TransferAllowance = 0, IsLevyPayer = true, AccountName = $"Test Account: {session.Ukprn}" }); await dataContext.SaveChangesAsync().ConfigureAwait(false); }
public void throw_error_if_traying_to_set_certificateOfAttendence_to_non_assigned_student() { var context = TestSession.Create(); var studentId = Guid.NewGuid(); var documentId = Guid.NewGuid(); context.Builder.AddEvent(new SessionSeatBooked(Guid.Empty, 5, studentId)); var session = context.Builder.Create(); Action action = () => session.SendCertificateOfAttendance(Guid.NewGuid(), documentId); action.ShouldThrow <StudentNotInSessionException>(); }
public void send_certificateOfAttendenceSent() { var context = TestSession.Create(); var studentId = Guid.NewGuid(); var documentId = Guid.NewGuid(); context.Builder.AddEvent(new SessionSeatBooked(Guid.Empty, 5, studentId)); var session = context.Builder.Create(); session.SendCertificateOfAttendance(studentId, documentId); session.UncommitedEvents.GetStream().Should().Contain(new CertificateOfAttendanceSent(Guid.Empty, 1, studentId, documentId)); }
public async Task TheSameLearnerIsSubmittedButWithADifferentUkprn() { var command = Context.Get <ProcessLearnerCommand>(ProcessLearnerCommand); command.Ukprn = TestSession.GenerateId(); command.JobId = TestSession.GenerateId(100000); var currentJobIds = Context.Get <List <long> >(JobIds); currentJobIds.Add(command.JobId); Context.Set <List <long> >(currentJobIds, JobIds); await MessageSession.Send(command); }
public void TestAuthorizeAnnotationActionRoleAuthorizedClass() { MethodInfo actionMethod = FindMethod(typeof (Customer13), "Action1"); facetFactory.Process(Reflector, actionMethod, MethodRemover, Specification); var facet = Specification.GetFacet<IDisableForSessionFacet>(); Assert.IsNotNull(facet); var testSession = new TestSession("aRole", ""); Assert.IsNull(facet.DisabledReason(testSession, null, lifecycleManager, Metamodel)); var facet1 = Specification.GetFacet<IHideForSessionFacet>(); Assert.IsNotNull(facet); Assert.IsNull(facet1.HiddenReason(testSession, null, lifecycleManager, Metamodel)); }
public void throw_error_if_update_nbrSeats_lower_than_seats_already_reserved() { var context = TestSession.Create(); var session = context.Builder.Create(); session.BookSeat(Guid.NewGuid(), Guid.NewGuid()); session.BookSeat(Guid.NewGuid(), Guid.NewGuid()); session.BookSeat(Guid.NewGuid(), Guid.NewGuid()); session.BookSeat(Guid.NewGuid(), Guid.NewGuid()); Action action = () => session.Update(context.TrainingId, DateTime.Now, 0, 3, context.LocationId, context.TrainerId); action.ShouldThrow <TooManySeatsAlreadyReservedException>(); }
public void ShouldReadSmallVersionOfJegerregisteret98() { ArkadeProcessingArea.Establish(Path.Combine(Environment.CurrentDirectory, "TestData")); ArchiveFile archive = ArchiveFile.Read("..\\..\\TestData\\tar\\jegerregisteret98-small\\20b5f34c-4411-47c3-a0f9-0a8bca631603.tar", ArchiveType.Fagsystem); Arkade.Core.Arkade arkade = new Arkade.Core.Arkade(); TestSession testSesson = arkade.RunTests(archive); testSesson.Should().NotBeNull(); TestSuite testSuite = testSesson.TestSuite; testSuite.Should().NotBeNull(); }
public static ITestSession GetSuperAdmin(this ITestSession session) { return(Web.Configuration.Settings.GetString(EastFive.Api.AppSettings.SiteAdminAuthorization, (siteAdminAuthToken) => { var superAdminSession = new TestSession(siteAdminAuthToken); return superAdminSession; }, (why) => { Assert.Fail(why); throw new Exception(why); })); }
public void Setup() { QueryHelper = new QueryHelper(); Data = new TestData(QueryHelper); Session = new TestSession(); SetComparer = new SetComparer(); Session.BeginUpdate(); Data.AddEventTypesPersisted(1, Session); Data.AddNewslettersPersisted(1, Session); Data.AddSeriesPersisted(1, Session); Data.AddActsPersisted(1, Session); Data.AddGenresPersisted(1, Session); Session.Commit(); }
//Не является операцией сервиса private short GetScore(TestSession session, DataClassesTestorCoreDataContext dataContext) { Debug.Assert(session != null); //dataContext.Log = new DebuggerWriter(); var score = (from c in session.TestSessionQuestions where c.IsRightAnswer == true select new { QuestionMark = c.CoreQuestion.QuestionMark }).Sum(c => c.QuestionMark); return((short)score); }
public void GenerateXmlAndSaveToFile(TestSession testSession) { string pathToLogFile = testSession.Archive.WorkingDirectory.RepositoryOperations() .WithFile(ArkadeConstants.ArkadeXmlLogFileName) .FullName; testSessionLog log = GetTestSessionLog(testSession); FileStream fs = new FileStream(pathToLogFile, FileMode.Create); XmlSerializer xmls = new XmlSerializer(typeof(testSessionLog)); xmls.Serialize(fs, log); fs.Close(); }
public void ResetJob() { if (!Context.ContainsKey("new_feature")) { NewFeature = true; } TestSession.Providers.ForEach(p => { var newJobId = TestSession.GenerateId(); Console.WriteLine( $"Using new job. Previous job id: {p.JobId}, new job id: {newJobId} for ukprn: {p.Ukprn}"); p.JobId = newJobId; }); }
public void Run(CommandLineOptions options) { try { var arkade = new Core.Base.Arkade(); var fileInfo = new FileInfo(options.Archive); Log.Information($"Processing archive: {fileInfo.FullName}"); if (!Enum.TryParse(options.ArchiveType, true, out ArchiveType archiveType)) { Log.Error("Unknown archive type"); throw new ArgumentException("unknown archive type"); } if (archiveType == ArchiveType.Noark4) { Log.Error("Archive type Noark 4 is currently not supported"); throw new ArgumentException("unsupported archive type"); } TestSession testSession = CreateTestSession(options, arkade, archiveType); if (!TestingIsSkipped(options)) { arkade.RunTests(testSession); SaveTestReport(arkade, testSession, options); } if (!PackingIsSkipped(options)) { ArchiveMetadata archiveMetadata = MetadataLoader.Load(options.MetadataFile); archiveMetadata.PackageType = options.InformationPackageType != null && options.InformationPackageType.Equals("AIP") ? PackageType.ArchivalInformationPackage : PackageType.SubmissionInformationPackage; testSession.ArchiveMetadata = archiveMetadata; testSession.ArchiveMetadata.Id = $"UUID:{testSession.Archive.Uuid}"; arkade.CreatePackage(testSession, options.OutputDirectory); } } finally { ArkadeProcessingArea.CleanUp(); } }
private static testSessionLog GetTestSessionLog(TestSession testSession) { testSessionLog log = new testSessionLog(); log.timestamp = DateTime.Now; log.arkadeVersion = ArkadeVersion.Current; log.archiveType = testSession?.Archive?.ArchiveType.ToString(); log.archiveUuid = testSession?.Archive?.Uuid?.GetValue(); log.logEntries = GetLogEntries(testSession); log.testResults = GetTestResults(testSession); return(log); }
public void SaveResults(User currentUser, TestResult model) { var session = new TestSession { IsValid = model.ResultEmotion == model.SelectedEmotion, ResultType = EmotionUtil.GetEmotionType(model.ResultEmotion), Type = EmotionUtil.GetEmotionType(model.SelectedEmotion), StartDate = DateTime.Now, User = currentUser, TestLogs = new List <TestLog>(), Source = model.Source }; testRepository.Add(session); }
public async Task <TestSession> Update(TestSession session) { if (session.State != TestSessionState.Pending) { throw new InvalidOperationException("Can't update not pending test session"); } session.StudentTestSessions.ForEach(e => e.State = StudentTestSessionState.Pending); await _unitOfWork.Update(session); await _unitOfWork.Commit(); return(session); }
public void New_SetsAllValues() { //Given Test test = new Test(); string name = "WIDA Spring Test Session"; DateTime date = DateTime.Now; //When TestSession session = new TestSession(name, date, test); //Then Assert.NotEqual(Guid.Empty, session.Id); Assert.Equal(name, session.Name); Assert.Equal(date, session.Date); Assert.Equal(test, session.Test); }
public void GivenThePreviouslySubmittedTheFollowingLearnerDetails(string providerIdentifier, Table table) { var provider = TestSession.GetProviderByIdentifier(providerIdentifier); var newIlrSubmission = table.CreateSet <Training>().ToList(); AddTestLearners(newIlrSubmission, provider.Ukprn); if (PreviousIlr == null) { PreviousIlr = new List <Training>(); } PreviousIlr.AddRange(newIlrSubmission); }
public void CreatePageModel_KeywordModelExpansion_Success() { Page testPage = (Page)TestSession.GetObject(TestFixture.Tsi2316PageWebDavUrl); RenderedItem testRenderedItem; PageModelData pageModel = CreatePageModel(testPage, out testRenderedItem); RegionModelData mainRegion = GetMainRegion(pageModel); EntityModelData testEntity = mainRegion.Entities[0]; KeywordModelData notPublishedKeyword = (KeywordModelData)testEntity.Content["notPublishedKeyword"]; KeywordModelData publishedKeyword = (KeywordModelData)testEntity.Content["publishedKeyword"]; AssertExpanded(notPublishedKeyword, false, "notPublishedKeyword"); AssertNotExpanded(publishedKeyword, true, "publishedKeyword"); }
/// <summary> /// A method to call just before opening the test window. /// </summary> public void PrepareToTest(TestSession session) { Session = session; InitilizeTestStartEndEvents(); // get the threads rolling, so values update on the screen. InitializeThreads(); // default behavior. TestBench.Singleton.LoadDefaultBenchParameters(); // ready to start testing. TestBench.Singleton.InformReady(); }
public async Task AfterPeriodEndRunPaymentsAreGenerated(Table table) { await EmployerMonthEndHelper.SendLevyMonthEndForEmployers( TestSession.GenerateId(), TestSession.Employers.Select(x => x.AccountId), TestSession.CollectionPeriod.AcademicYear, TestSession.CollectionPeriod.Period, MessageSession); var expectedPayments = table.CreateSet <ProviderPayment>().ToList(); expectedPayments.ForEach(ep => ep.Uln = learnerB.Uln); await WaitForIt(() => AssertExpectedPayments(expectedPayments), "Failed to wait for expected number of payments"); }
public void throw_exception_if_trying_to_reserve_a_seat_when_no_seats_are_available() { var context = TestSession.Create(); var session = context.Builder.Create(); session.BookSeat(Guid.NewGuid(), Guid.NewGuid()); session.BookSeat(Guid.NewGuid(), Guid.NewGuid()); session.BookSeat(Guid.NewGuid(), Guid.NewGuid()); session.BookSeat(Guid.NewGuid(), Guid.NewGuid()); session.BookSeat(Guid.NewGuid(), Guid.NewGuid()); Action action = () => session.BookSeat(Guid.NewGuid(), Guid.NewGuid()); action.ShouldThrow <NoMoreSeatAvailableException>(); }
public FinderSystem(NaUrokClient client, string testSessionUuId, int threadsCount, int finderIterationsCount) { if (client is null) { throw new ArgumentNullException(nameof(client)); } testDocumentFinders = new List <TestDocumentFinder>(); this.client = client; ThreadsCount = threadsCount; FinderIterationsCount = finderIterationsCount; TestSessionUuId = testSessionUuId; testSession = client.GetTestSession(testSessionUuId); }
public async Task ThereAreLessThan6MonthsRemainingOfPlannedLearning() { ImportR07Fm36ToMakeLearnerRedundant(); await SetUpMatchingCommitment(); TestSession.RegenerateJobId(); var dcHelper = Scope.Resolve <IDcHelper>(); await dcHelper.SendIlrSubmission(TestSession.FM36Global.Learners, TestSession.Provider.Ukprn, TestSession.CollectionPeriod.AcademicYear, TestSession.CollectionPeriod.Period, TestSession.Provider.JobId); }
private void WorkWithReentryExpected(TestSession session, int count) { using (_sentry = Guard.AgainstReEntryExpected(_sentry)) { if (_sentry.HasEntered) { return; } session.DoWork(); if (count == 0) { WorkWithReentryExpected(session, count + 1); } } }
public void ShouldProvideTheEntityInstanceByItsId() { var entity = new Entity(); // We don't want to set up an ORM, // so we'll just fake ISession var session = new TestSession(); session.Stub <ISession>("Get").Return(entity); // Now let's execute a Web request var response = session.Get("/Sample/Get?entityId=1"); // Check the result Assert.AreEqual(entity, response.ActionMethodParameters["entity"]); }
public void Shutdown() { ExecuteTest((session, host) => { ManualResetEvent restartHandle = new ManualResetEvent(false); ManualResetEvent inModule = new ManualResetEvent(false); var textVariableService = _serviceResolver.GetService <ITextVariableService>(); // wait until the session is in the module session.OnSessionStateChanged += (sender, state) => { if (state == EnumSessionState.InModule) { inModule.Set(); } }; Assert.True(session.SessionState == EnumSessionState.InModule || inModule.WaitOne(TimeSpan.FromSeconds(5))); host.ScheduleNightlyShutdown(restartHandle); // now wait for restart to have completed Assert.True(restartHandle.WaitOne(TimeSpan.FromSeconds(5))); // verify first session was disconnected Assert.Equal(EnumSessionState.Disconnected, session.SessionState); // create new Session and reattach to host _session = session = new TestSession(host, textVariableService); Assert.NotNull(session.CurrentModule); host.AddSession(session); // and interact with the module again WaitUntil(':', "Make your selection"); session.SendToModule(Encoding.ASCII.GetBytes("E\r\n")); WaitUntil(':', "Type something"); session.SendToModule(Encoding.ASCII.GetBytes("This is really cool!\r\n")); WaitUntil(':', "You entered"); WaitUntil('\n', "This is really cool!"); session.SendToModule(Encoding.ASCII.GetBytes("x\r\nx\r\nx\r\nY\r\n")); WaitUntil('.', "Have a nice day"); }); }
public void GetOnSessionProperty_ReturnsAvailableSession() { // Arrange var context = new DefaultHttpContext(); var session = new TestSession(); session.Set("key1", null); session.Set("key2", null); var feature = new BlahSessionFeature(); feature.Session = session; context.Features.Set<ISessionFeature>(feature); // Act & Assert Assert.Same(session, context.Session); context.Session.Set("key3", null); Assert.Equal(3, context.Session.Keys.Count()); }
private static testResultsTestResult[] GetTestResults(TestSession testSession) { var xmlTestResults = new List<testResultsTestResult>(); foreach (TestRun testRun in testSession.TestSuite.TestRuns) { var testResult = new testResultsTestResult(); testResult.testName = testRun.TestName; testResult.testCategory = testRun.TestType.ToString(); testResult.durationMillis = testRun.TestDuration.ToString(); testResult.testDescription = testRun.TestDescription; testResult.status = testRun.IsSuccess() ? "SUCCESS" : "ERROR"; testResult.message = ConcatMessages(testRun.Results); xmlTestResults.Add(testResult); } return xmlTestResults.Count == 0 ? null : xmlTestResults.ToArray(); }
public void SettingSession_OverridesAvailableSession() { // Arrange var context = new DefaultHttpContext(); var session = new TestSession(); session.Set("key1", null); session.Set("key2", null); var feature = new BlahSessionFeature(); feature.Session = session; context.Features.Set<ISessionFeature>(feature); // Act context.Session = new TestSession(); // Assert Assert.NotSame(session, context.Session); Assert.Empty(context.Session.Keys); }
public void TestAuthorizeAnnotationEditUserAuthorizedClass() { PropertyInfo property = FindProperty(typeof (Customer8), "Property1"); facetFactory.Process(Reflector, property, MethodRemover, Specification); var facet = Specification.GetFacet<IDisableForSessionFacet>(); Assert.IsNotNull(facet); var testSession = new TestSession("", "aUser"); Assert.IsNull(facet.DisabledReason(testSession, null, lifecycleManager, Metamodel)); }
public void TestAuthorizeAnnotationEditRoleNotAuthorized() { PropertyInfo property = FindProperty(typeof (Customer), "Property8"); facetFactory.Process(Reflector, property, MethodRemover, Specification); var facet = Specification.GetFacet<IDisableForSessionFacet>(); Assert.IsNotNull(facet); var testSession = new TestSession("anotherRole", ""); Assert.AreEqual("Not authorized to edit", facet.DisabledReason(testSession, null, lifecycleManager, Metamodel)); }
public void TestAuthorizeAnnotationViewRoleAuthorized() { PropertyInfo property = FindProperty(typeof (Customer), "Property7"); facetFactory.Process(Reflector, property, MethodRemover, Specification); var facet = Specification.GetFacet<IHideForSessionFacet>(); Assert.IsNotNull(facet); var testSession = new TestSession("aRole", ""); Assert.IsNull(facet.HiddenReason(testSession, null, lifecycleManager, Metamodel)); }
public int Run(string[] args) { // This is used by ExecServer to retrieve the logs directly without using the console redirect (which is not working well // in a multi-domain scenario) var redirectLogToAppDomainAction = AppDomain.CurrentDomain.GetData("AppDomainLogToAction") as Action<string, ConsoleColor>; clock = Stopwatch.StartNew(); // TODO this is hardcoded. Check how to make this dynamic instead. RuntimeHelpers.RunModuleConstructor(typeof(IProceduralModel).Module.ModuleHandle); RuntimeHelpers.RunModuleConstructor(typeof(MaterialKeys).Module.ModuleHandle); RuntimeHelpers.RunModuleConstructor(typeof(SpriteFontAsset).Module.ModuleHandle); RuntimeHelpers.RunModuleConstructor(typeof(ModelAsset).Module.ModuleHandle); RuntimeHelpers.RunModuleConstructor(typeof(SpriteStudioAnimationAsset).Module.ModuleHandle); //var project = new Package(); //project.Save("test.pdxpkg"); //Thread.Sleep(10000); //var spriteFontAsset = StaticFontAsset.New(); //Asset.Save("test.pdxfnt", spriteFontAsset); //project.Refresh(); //args = new string[] { "test.pdxpkg", "-o:app_data", "-b:tmp", "-t:1" }; var exeName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); var showHelp = false; var options = new PackageBuilderOptions(new ForwardingLoggerResult(GlobalLogger.GetLogger("BuildEngine"))); var p = new OptionSet { "Copyright (C) 2011-2014 Silicon Studio Corporation. All Rights Reserved", "Paradox Build Tool - Version: " + String.Format( "{0}.{1}.{2}", typeof(Program).Assembly.GetName().Version.Major, typeof(Program).Assembly.GetName().Version.Minor, typeof(Program).Assembly.GetName().Version.Build) + string.Empty, string.Format("Usage: {0} inputPackageFile [options]* -b buildPath", exeName), string.Empty, "=== Options ===", string.Empty, { "h|help", "Show this message and exit", v => showHelp = v != null }, { "v|verbose", "Show more verbose progress logs", v => options.Verbose = v != null }, { "d|debug", "Show debug logs (imply verbose)", v => options.Debug = v != null }, { "log", "Enable file logging", v => options.EnableFileLogging = v != null }, { "disable-auto-compile", "Disable auto-compile of projects", v => options.DisableAutoCompileProjects = v != null}, { "p|profile=", "Profile name", v => options.BuildProfile = v }, { "project-configuration=", "Project configuration", v => options.ProjectConfiguration = v }, { "platform=", "Platform name", v => options.Platform = (PlatformType)Enum.Parse(typeof(PlatformType), v) }, { "graphics-platform=", "Graphics Platform name", v => options.GraphicsPlatform = (GraphicsPlatform)Enum.Parse(typeof(GraphicsPlatform), v) }, { "get-graphics-platform", "Get Graphics Platform name (needs a pdxpkg and a profile)", v => options.GetGraphicsPlatform = v != null }, { "solution-file=", "Solution File Name", v => options.SolutionFile = v }, { "package-id=", "Package Id from the solution file", v => options.PackageId = Guid.Parse(v) }, { "package-file=", "Input Package File Name", v => options.PackageFile = v }, { "o|output-path=", "Output path", v => options.OutputDirectory = v }, { "b|build-path=", "Build path", v => options.BuildDirectory = v }, { "log-file=", "Log build in a custom file.", v => { options.EnableFileLogging = v != null; options.CustomLogFileName = v; } }, { "log-pipe=", "Log pipe.", v => { if (!string.IsNullOrEmpty(v)) options.LogPipeNames.Add(v); } }, { "monitor-pipe=", "Monitor pipe.", v => { if (!string.IsNullOrEmpty(v)) options.MonitorPipeNames.Add(v); } }, { "slave=", "Slave pipe", v => options.SlavePipe = v }, // Benlitz: I don't think this should be documented { "server=", "This Compiler is launched as a server", v => { } }, { "t|threads=", "Number of threads to create. Default value is the number of hardware threads available.", v => options.ThreadCount = int.Parse(v) }, { "test=", "Run a test session.", v => options.TestName = v }, { "property:", "Properties. Format is name1=value1;name2=value2", v => { if (!string.IsNullOrEmpty(v)) { foreach (var nameValue in v.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { var equalIndex = nameValue.IndexOf('='); if (equalIndex == -1) throw new OptionException("Expect name1=value1;name2=value2 format.", "property"); options.Properties.Add(nameValue.Substring(0, equalIndex), nameValue.Substring(equalIndex + 1)); } } } }, { "compile-property:", "Compile properties. Format is name1=value1;name2=value2", v => { if (!string.IsNullOrEmpty(v)) { if (options.ExtraCompileProperties == null) options.ExtraCompileProperties = new Dictionary<string, string>(); foreach (var nameValue in v.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { var equalIndex = nameValue.IndexOf('='); if (equalIndex == -1) throw new OptionException("Expect name1=value1;name2=value2 format.", "property"); options.ExtraCompileProperties.Add(nameValue.Substring(0, equalIndex), nameValue.Substring(equalIndex + 1)); } } } }, }; TextWriterLogListener fileLogListener = null; // Output logs to the console with colored messages if (options.SlavePipe == null) { if (redirectLogToAppDomainAction != null) { globalLoggerOnGlobalMessageLogged = new LogListenerRedirectToAction(redirectLogToAppDomainAction); } else { globalLoggerOnGlobalMessageLogged = new ConsoleLogListener { LogMode = ConsoleLogMode.Always }; } globalLoggerOnGlobalMessageLogged.TextFormatter = FormatLog; GlobalLogger.GlobalMessageLogged += globalLoggerOnGlobalMessageLogged; } BuildResultCode exitCode; try { var unexpectedArgs = p.Parse(args); if (unexpectedArgs.Any()) { throw new OptionException("Unexpected arguments [{0}]".ToFormat(string.Join(", ", unexpectedArgs)), "args"); } try { options.ValidateOptions(); } catch (ArgumentException ex) { throw new OptionException(ex.Message, ex.ParamName); } // Also write logs from master process into a file if (options.SlavePipe == null) { if (options.EnableFileLogging) { string logFileName = options.CustomLogFileName; if (string.IsNullOrEmpty(logFileName)) { string inputName = Path.GetFileNameWithoutExtension(options.PackageFile); logFileName = "Logs/Build-" + inputName + "-" + DateTime.Now.ToString("yy-MM-dd-HH-mm") + ".txt"; } string dirName = Path.GetDirectoryName(logFileName); if (dirName != null) Directory.CreateDirectory(dirName); fileLogListener = new TextWriterLogListener(new FileStream(logFileName, FileMode.Create)) { TextFormatter = FormatLog }; GlobalLogger.GlobalMessageLogged += fileLogListener; } if (!options.GetGraphicsPlatform) { options.Logger.Info("BuildEngine arguments: " + string.Join(" ", args)); options.Logger.Info("Starting builder."); } } else { IsSlave = true; } if (showHelp) { p.WriteOptionDescriptions(Console.Out); exitCode = BuildResultCode.Successful; } else if (!string.IsNullOrEmpty(options.TestName)) { var test = new TestSession(); test.RunTest(options.TestName, options.Logger); exitCode = BuildResultCode.Successful; } else { builder = new PackageBuilder(options); if (!IsSlave && redirectLogToAppDomainAction == null) { Console.CancelKeyPress += OnConsoleOnCancelKeyPress; } exitCode = builder.Build(); } } catch (OptionException e) { options.Logger.Error("Command option '{0}': {1}", e.OptionName, e.Message); exitCode = BuildResultCode.CommandLineError; } catch (Exception e) { options.Logger.Error("Unhandled exception: {0}", e, e.Message); exitCode = BuildResultCode.BuildError; } finally { if (fileLogListener != null) { GlobalLogger.GlobalMessageLogged -= fileLogListener; fileLogListener.LogWriter.Close(); } // Output logs to the console with colored messages if (globalLoggerOnGlobalMessageLogged != null) { GlobalLogger.GlobalMessageLogged -= globalLoggerOnGlobalMessageLogged; } if (builder != null && !IsSlave && redirectLogToAppDomainAction == null) { Console.CancelKeyPress -= OnConsoleOnCancelKeyPress; } // Make sure that MSBuild doesn't hold anything else VSProjectHelper.Reset(); // Reset cache hold by YamlSerializer YamlSerializer.ResetCache(); } return (int)exitCode; }
public void GuardAgainstReentry_Expected_Detected() { var session = new TestSession(); WorkWithReentryExpected(session, 0); Assert.AreEqual(1, session.WorkCount); }
public void TestAuthorizeAnnotationViewUserNotAuthorizedClass() { PropertyInfo property = FindProperty(typeof (Customer7), "Property1"); facetFactory.Process(Reflector, property, MethodRemover, Specification); var facet = Specification.GetFacet<IHideForSessionFacet>(); Assert.IsNotNull(facet); var testSession = new TestSession("", "anotherUser"); Assert.AreEqual("Not authorized to view", facet.HiddenReason(testSession, null, lifecycleManager, Metamodel)); }
public void GuardAgainstReentry_WithReentry_Throws() { var session = new TestSession(); Assert.Throws<ApplicationException>( () => WorkWithReentry(session, 0)); }
public void TestAuthorizeAnnotationEditUserNotAuthorized() { PropertyInfo property = FindProperty(typeof (Customer), "Property8"); facetFactory.Process(property, methodRemover, facetHolder); var facet = facetHolder.GetFacet<IDisableForSessionFacet>(); Assert.IsNotNull(facet); var testSession = new TestSession("", "anotherUser"); Assert.AreEqual("Not authorized to edit", facet.DisabledReason(testSession, null)); }
public void TestAuthorizeAnnotationActionUserOnlyAuthorized() { MethodInfo actionMethod = FindMethod(typeof (Customer), "Action4"); facetFactory.Process(actionMethod, methodRemover, facetHolder); var facet = facetHolder.GetFacet<IDisableForSessionFacet>(); Assert.IsNotNull(facet); var testSession = new TestSession("", "aUser"); Assert.IsNull(facet.DisabledReason(testSession, null)); var facet1 = facetHolder.GetFacet<IHideForSessionFacet>(); Assert.IsNotNull(facet); Assert.IsNull(facet1.HiddenReason(testSession, null)); }
public void TestAuthorizeAnnotationActionRoleAuthorizedClassPriorityOverMethod() { MethodInfo actionMethod = FindMethod(typeof(Customer14), "Action1"); facetFactory.Process(actionMethod, methodRemover, facetHolder); var facet = facetHolder.GetFacet<IDisableForSessionFacet>(); Assert.IsNotNull(facet); var testSession = new TestSession("aRole", ""); Assert.IsNull(facet.DisabledReason(testSession, null)); var facet1 = facetHolder.GetFacet<IHideForSessionFacet>(); Assert.IsNotNull(facet); Assert.IsNull(facet1.HiddenReason(testSession, null)); testSession = new TestSession("anotherRole", ""); Assert.IsNotNull(facet.DisabledReason(testSession, null)); facet1 = facetHolder.GetFacet<IHideForSessionFacet>(); Assert.IsNotNull(facet); Assert.IsNotNull(facet1.HiddenReason(testSession, null)); }
public void TestAuthorizeAnnotationActionUserOnlyNotAuthorizedClass() { MethodInfo actionMethod = FindMethod(typeof(Customer12), "Action1"); facetFactory.Process(actionMethod, methodRemover, facetHolder); var facet = facetHolder.GetFacet<IDisableForSessionFacet>(); Assert.IsNotNull(facet); var testSession = new TestSession("", "anotherUser"); Assert.AreEqual("Not authorized to edit", facet.DisabledReason(testSession, null)); var facet1 = facetHolder.GetFacet<IHideForSessionFacet>(); Assert.IsNotNull(facet); Assert.AreEqual("Not authorized to view", facet1.HiddenReason(testSession, null)); }
public void TestAuthorizeAnnotationViewUserNotAuthorizedClass() { PropertyInfo property = FindProperty(typeof(Customer7), "Property1"); facetFactory.Process(property, methodRemover, facetHolder); var facet = facetHolder.GetFacet<IHideForSessionFacet>(); Assert.IsNotNull(facet); var testSession = new TestSession("", "anotherUser"); Assert.AreEqual("Not authorized to view", facet.HiddenReason(testSession, null)); }
public void TestAuthorizeAnnotationViewRoleAuthorized() { PropertyInfo property = FindProperty(typeof (Customer), "Property7"); facetFactory.Process(property, methodRemover, facetHolder); var facet = facetHolder.GetFacet<IHideForSessionFacet>(); Assert.IsNotNull(facet); var testSession = new TestSession("aRole", ""); Assert.IsNull(facet.HiddenReason(testSession, null)); }
public void TestAuthorizeAnnotationActionUserOnlyNotAuthorizedClass() { MethodInfo actionMethod = FindMethod(typeof (Customer12), "Action1"); facetFactory.Process(Reflector, actionMethod, MethodRemover, Specification); var facet = Specification.GetFacet<IDisableForSessionFacet>(); Assert.IsNotNull(facet); var testSession = new TestSession("", "anotherUser"); Assert.AreEqual("Not authorized to edit", facet.DisabledReason(testSession, null, lifecycleManager, Metamodel)); var facet1 = Specification.GetFacet<IHideForSessionFacet>(); Assert.IsNotNull(facet); Assert.AreEqual("Not authorized to view", facet1.HiddenReason(testSession, null, lifecycleManager, Metamodel)); }
void m_Server_NewSessionConnected(TestSession obj) { m_NewSessionConnectedEvent.Set(); }
private void WorkWithReentryExpected(TestSession session, int count) { using (_sentry = Guard.AgainstReEntryExpected(_sentry)) { if (_sentry.HasEntered) return; session.DoWork(); if (count == 0) { WorkWithReentryExpected(session, count + 1); } } }
public void TestAuthorizeAnnotationEditRoleAuthorizedClass() { PropertyInfo property = FindProperty(typeof(Customer8), "Property1"); facetFactory.Process(property, methodRemover, facetHolder); var facet = facetHolder.GetFacet<IDisableForSessionFacet>(); Assert.IsNotNull(facet); var testSession = new TestSession("aRole", ""); Assert.IsNull(facet.DisabledReason(testSession, null)); }