示例#1
0
        public static SessionResults GetSessionResults(string apiKey, TestResults testResults)
        {
            string apiSessionUrl = testResults?.ApiUrls?.Session;

            if (string.IsNullOrWhiteSpace(apiSessionUrl))
            {
                return(null);
            }
            UriBuilder          uriBuilder = new UriBuilder(apiSessionUrl);
            NameValueCollection query      = UrlUtility.ParseQueryString(uriBuilder.Query);

            query["format"]      = "json";
            query["AccessToken"] = testResults.SecretToken;
            query["apiKey"]      = apiKey;
            uriBuilder.Query     = query.ToString();
            HttpRestClient client         = new HttpRestClient(uriBuilder.Uri);
            SessionResults sessionResults = null;
            Stopwatch      stopwatch      = Stopwatch.StartNew();
            TimeSpan       timeout        = TimeSpan.FromSeconds(40);

            while (sessionResults == null && stopwatch.Elapsed < timeout)
            {
                using (HttpResponseMessage metaResults = client.Get(uriBuilder.ToString()))
                {
                    sessionResults = metaResults.DeserializeBody <SessionResults>(false);
                }
                if (sessionResults != null && sessionResults.ActualAppOutput.Length > 0)
                {
                    break;
                }
                System.Threading.Thread.Sleep(500);
            }
            return(sessionResults);
        }
示例#2
0
        /// <summary>
        ///
        /// </summary>
        protected virtual void HandleResponseMessage(TransportMessage message)
        {
            SessionResults respondedSession = null;

            // First - check if this is a responce to a currently pending session.
            lock (_communicationSessions)
            {
                string requestMessageInfo = string.Empty;
                if (message is ResponseMessage)
                {
                    requestMessageInfo = ((ResponseMessage)message).RequestMessageTypeName;
                }

                if (_communicationSessions.ContainsKey(message.TransportInfo.CurrentTransportInfo.Value.Id) == false)
                {
                    TracerHelper.TraceError("Response received to a session that is not pending [from " + message.TransportInfo.OriginalSenderId.Value.Id.Print() + " to " + this.SubscriptionClientID.Id.Print() + "]. Message [" + message.GetType().Name + " responding to " + requestMessageInfo + "] dumped.");
                    return;
                }

                respondedSession = _communicationSessions[message.TransportInfo.CurrentTransportInfo.Value.Id];
            }

            // Clear off the sessioning Transport Info that just brough it back as well.
            message.TransportInfo.PopTransportInfo();

            respondedSession.ReceiveResponse(message);
        }
示例#3
0
        private static async Task <SessionResults> GetSessions(string scheduleID)
        {
            APIService   srv              = new APIService();
            SessionModel model            = new SessionModel();
            Dictionary <string, string> p = new Dictionary <string, string>();

            p.Add("scheduleId", string.Format("'{0}'", scheduleID));

            model.CommandModel.SessionToken = await App.GetUsersSession();

            model.CommandModel.ServiceName = "Session";
            model.CommandModel.Action      = "GetSessionsForSchedule";
            model.CommandModel.Parameters  = p;

            SessionResults result = null;
            var            cache  = BlobCache.UserAccount;
            var            cachedSessionPromise = cache.GetAndFetchLatest(
                scheduleID,
                () => srv.GetSessionsForSchedule(model.CommandModel),
                offset =>
            {
                TimeSpan elapsed = DateTimeOffset.Now - offset;
                return(elapsed > new TimeSpan(hours: 0, minutes: 10, seconds: 0));
            });

            cachedSessionPromise.Subscribe(subscribedSchedules =>
            {
                result = subscribedSchedules;
            });

            result = await cachedSessionPromise.FirstOrDefaultAsync();

            return(result);
        }
示例#4
0
        private static void DoTestConfig_MatchLevel_(Eyes eyes, [CallerMemberName] string testName = null)
        {
            IWebDriver webDriver = new ChromeDriver();

            try
            {
                webDriver.Url = "https://applitools.github.io/demo/TestPages/FramesTestPage/";

                eyes.MatchLevel = MatchLevel.Layout;
                eyes.Open(webDriver, "test", testName, new System.Drawing.Size(1000, 700));
                eyes.Check(Target.Window());

                eyes.MatchLevel = MatchLevel.Content;
                eyes.Check(Target.Window());
            }
            finally
            {
                webDriver.Quit();
            }

            TestResults    results        = eyes.Close();
            SessionResults sessionResults = GetSessionResults_(eyes, results);

            Assert.NotNull(sessionResults);
            Assert.NotNull(sessionResults.ActualAppOutput);
            Assert.AreEqual(2, sessionResults.ActualAppOutput.Length);
            Assert.AreEqual(MatchLevel.Layout2, sessionResults.ActualAppOutput[0].ImageMatchSettings.MatchLevel);
            Assert.AreEqual(MatchLevel.Content, sessionResults.ActualAppOutput[1].ImageMatchSettings.MatchLevel);
        }
示例#5
0
 public Session(long id)
 {
     sessionResults = new SessionResults();
     tasks          = new List <Task>();
     m_isStarted    = false;
     m_id           = id;
 }
示例#6
0
        private static void CompareDomJsons(DomInterceptingEyes eyes, string actualDomJsonString, string expectedContentFilename)
        {
            string expectedDomJsonString = CommonUtils.ReadResourceFile(expectedContentFilename);
            string expectedDomJson       = JsonUtility.NormalizeJsonString(expectedDomJsonString);

            TestResults results = eyes.Close(false);
            bool        hasDom  = GetHasDom_(eyes, results);

            Assert.IsTrue(hasDom);

            string actualDomJson = JsonUtility.NormalizeJsonString(actualDomJsonString);

            if (actualDomJson != expectedDomJson && !TestUtils.RUNS_ON_CI)
            {
                string path = TestUtils.InitLogPath();
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                File.WriteAllText(Path.Combine(path, "actualDom.json"), actualDomJson);
            }
            Assert.AreEqual(expectedDomJson, actualDomJson);

            SessionResults sessionResults = TestUtils.GetSessionResults(eyes.ApiKey, results);

            ActualAppOutput[] actualAppOutput         = sessionResults.ActualAppOutput;
            string            downloadedDomJsonString = TestUtils.GetStepDom(eyes, actualAppOutput[0]);
            string            downloadedDomJson       = JsonUtility.NormalizeJsonString(downloadedDomJsonString);

            Assert.AreEqual(expectedDomJson, downloadedDomJson);
        }
示例#7
0
        private static object GetMSpecRunListener(SessionResults sessionResults)
        {
            var specificationRunListenerType = MSpecTypes.Types.First(x => x.Name == "ISpecificationRunListener");

            return(Impromptu.DynamicActLike(GilesMSpecRunListener.GetAnonymousListener(sessionResults, new List <TestResult>(), new ResultFormatterFactory()),
                                            specificationRunListenerType));
        }
示例#8
0
        private dynamic GetRunner(SessionResults sessionResults)
        {
            dynamic dynamicRunListener = GetMSpecRunListener(sessionResults);

            var appDomainRunnerType = MSpecTypes.Types.First(x => x.Name == "AppDomainRunner");

            return(Activator.CreateInstance(appDomainRunnerType, dynamicRunListener, GetRunOptions()));
        }
        public void Teardown()
        {
            try
            {
                testDataByTestId_.TryGetValue(TestContext.CurrentContext.Test.ID, out SpecificTestContextRequirements testData);
                TestResults results = testData?.Eyes.Close();
                if (results != null)
                {
                    SessionResults sessionResults = TestUtils.GetSessionResults(GetEyes().ApiKey, results);

                    if (sessionResults != null)
                    {
                        ActualAppOutput[] actualAppOutput = sessionResults.ActualAppOutput;
                        for (int i = 0; i < actualAppOutput.Length; i++)
                        {
                            Metadata.ImageMatchSettings ims = actualAppOutput[i].ImageMatchSettings;
                            CompareRegions_(ims, i);
                            CompareProperties_(ims, i);
                        }
                    }
                    testData.Eyes.Logger.Log("Mismatches: " + results.Mismatches);
                }
                if (testData?.Eyes.activeEyes_ is VisualGridEyes visualGridEyes && visualGridEyes.eyesConnector_ is Mock.MockEyesConnector mockEyesConnector)
                {
                    RenderRequest[] lastRequests       = mockEyesConnector.LastRenderRequests;
                    string          serializedRequests = JsonUtils.Serialize(lastRequests);
                    if (!TestUtils.RUNS_ON_CI)
                    {
                        string dateString = DateTime.Now.ToString("yyyy_MM_dd__HH_mm");
                        string directory  = Path.Combine(TestUtils.LOGS_PATH, "DotNet", "VGResults", dateString);
                        Directory.CreateDirectory(directory);
                        File.WriteAllText(Path.Combine(directory, testData.TestNameAsFilename + ".json"), serializedRequests);
                    }
                    Assert.AreEqual(testData.ExpectedVGOutput, serializedRequests, "VG Request DOM JSON");
                }
            }
            catch (Exception ex)
            {
                GetEyes()?.Logger?.GetILogHandler()?.Open();
                GetEyes()?.Logger?.Log("Exception: " + ex);
                throw;
            }
            finally
            {
                Logger logger = GetEyes()?.Logger;
                if (logger != null)
                {
                    logger.GetILogHandler()?.Open();
                    logger.Log("Test finished.");
                    logger.GetILogHandler()?.Close();
                    Thread.Sleep(1000);
                }
                GetEyes()?.Abort();
                GetWebDriver()?.Quit();
            }
        }
示例#10
0
        private static bool GetHasDom_(IEyesBase eyes, TestResults results)
        {
            SessionResults sessionResults = TestUtils.GetSessionResults(eyes.ApiKey, results);

            ActualAppOutput[] actualAppOutputs = sessionResults.ActualAppOutput;
            Assert.AreEqual(1, actualAppOutputs.Length);
            bool hasDom = actualAppOutputs[0].Image.HasDom;

            return(hasDom);
        }
示例#11
0
        public SessionResults RunAssembly(Assembly assembly)
        {
            var sessionResults = new SessionResults();
            var logger         = new GilesXunitLogger();

            using (var exWrapper = new XunitFx.ExecutorWrapper(new Uri(assembly.CodeBase).LocalPath, null, false)) {
                var runner = new XunitFx.TestRunner(exWrapper, logger);
                var result = runner.RunAssembly();
            }
            return(logger.SessionResults);
        }
示例#12
0
        private static dynamic GetRunner(SessionResults sessionResults)
        {
            dynamic dynamicRunListener = GetMSpecRunListener(sessionResults);

            var runOptionsType = MSpecTypes.Types.First(x => x.Name == "RunOptions");
            var runOptions     = Activator.CreateInstance(runOptionsType, new string[] { }, new string[] { }, new string[] { });

            var appDomainRunnerType = MSpecTypes.Types.First(x => x.Name == "AppDomainRunner");

            return(Activator.CreateInstance(appDomainRunnerType, dynamicRunListener, runOptions));
        }
示例#13
0
        public SessionResults RunAssembly(Assembly assembly)
        {
            var mspecAssembly = LoadMSpec(assembly);

            MSpecTypes.Types = mspecAssembly.GetExportedTypes();

            var sessionResults = new SessionResults();
            var runner         = GetRunner(sessionResults);

            runner.RunAssembly(assembly);
            return(sessionResults);
        }
示例#14
0
        public SessionResults RunAssembly(Assembly assembly, IEnumerable <string> filters)
        {
            this.filters = filters;
            var mspecAssembly = LoadMSpec(assembly);

            MSpecTypes.Types = mspecAssembly.GetExportedTypes();

            var sessionResults = new SessionResults();
            var runner         = GetRunner(sessionResults);

            runner.RunAssembly(assembly);
            return(sessionResults);
        }
示例#15
0
 public ApiFriendController(
     IProfileRepository profileRepo,
     IFriendRepository friendRepo,
     IImageRepository imageRepo,
     SessionResults sessionResults,
     CurrentProfile currentProfile)
 {
     this.profileRepo    = profileRepo;
     this.friendRepo     = friendRepo;
     this.imageRepo      = imageRepo;
     this.sessionResults = sessionResults;
     this.currentProfile = currentProfile;
 }
示例#16
0
        public SessionResults RunAssembly(Assembly assembly, IEnumerable <string> filters)
        {
            var sessionResults = new SessionResults();
            var tags           = string.Empty;

            if (filters.Any())
            {
                tags = filters.Aggregate((working, next) => working + "," + next);
            }
            var runner = new RunnerInvocation(assembly.Location, tags, new GilesSessionResultsFormatter(sessionResults), false);

            runner.Run();
            return(sessionResults);
        }
示例#17
0
    /// <summary>
    /// Display result menu
    /// </summary>
    /// <param name="name">Student name</param>
    /// <param name="studentNumber">Student number</param>
    /// <param name="results">Session results</param>
    /// <param name="isPause">Whether this menu is displayed for pause</param>
    public void DisplayResults(string name, string studentNumber, SessionResults results, bool isPause = false)
    {
        m_gamepadHints.SetActive(false);
        m_keyboardHints.SetActive(false);
        m_assessmentModePanel.SetActive(false);
        m_tutorialToggle.GetComponent <Toggle>().isOn = GameManager.Instance.WillShowTutorials;
        m_results.SetActive(true);

        m_nameText.text          = name;
        m_studentNumberText.text = studentNumber;
        m_dateText.text          = "Date: " + results.date.ToShortDateString();
        m_startText.text         = "Start Time: " + results.startTime.ToShortTimeString();

        m_logsText.text     = "";
        m_logsText.richText = true;
        foreach (string log in results.logs)
        {
            if (log.Contains("Failed"))
            {
                m_logsText.text += "<color=red>" + log + "</color>\n";
            }
        }

        if (m_logsText.text.Equals(""))
        {
            m_logsText.text = "No errors made.";
        }

        if (isPause && GameManager.Instance.IsAssessmentMode())
        {
            m_logsText.text = "Not available while the session is running.";
        }

        m_linkText.text = "See the full report at: http://vegas.murdoch.edu.au/vinst/";

        // Add seleceted object for GamePad navigation
        if (m_resumeButton.activeInHierarchy)
        {
            GameObject.Find("EventSystem").GetComponent <EventSystem>().SetSelectedGameObject(m_resumeButton);
        }
        else if (m_exitButton.activeInHierarchy)
        {
            GameObject.Find("EventSystem").GetComponent <EventSystem>().SetSelectedGameObject(m_exitButton);
        }
        else if (m_nextSessionButton.activeInHierarchy)
        {
            GameObject.Find("EventSystem").GetComponent <EventSystem>().SetSelectedGameObject(m_nextSessionButton);
        }
    }
示例#18
0
        public static object GetAnonymousListener(SessionResults sessionResults, List <TestResult> testResults, ResultFormatterFactory resultFormatterFactory)
        {
            return(new
            {
                OnAssemblyStart = ReturnVoid.Arguments <dynamic>(assembly => { }),

                OnAssemblyEnd = ReturnVoid.Arguments <dynamic>(assembly => { }),

                OnRunStart = ReturnVoid.Arguments(() => { }),

                OnRunEnd = ReturnVoid.Arguments(() => testResults.ForEach(x => sessionResults.TestResults.Add(x))),

                OnContextStart = ReturnVoid.Arguments <dynamic>(context =>
                {
                    string r = string.Format("\n{0}", context.FullName);
                    sessionResults.Messages.Add(r);
                }),

                OnContextEnd = ReturnVoid.Arguments <dynamic>(context => { }),

                OnSpecificationStart = ReturnVoid.Arguments <Object>(specification => { }),

                OnSpecificationEnd = ReturnVoid.Arguments <dynamic, dynamic>((specification, result) =>
                {
                    var formatter = ResultFormatterFactory.GetResultFormatterFor(result: result.Status.ToString());

                    string formatResult = formatter.FormatResult(specification, result);
                    sessionResults.Messages.Add(formatResult);

                    var testResult =
                        new TestResult {
                        Name = specification.Name, TestRunner = "MSPEC"
                    };

                    ProcessTestResult((object)result, testResult, testResults);
                }),

                OnFatalError = ReturnVoid.Arguments <dynamic>(exception => sessionResults.Messages.Add("Fatal error: " + exception)),

                sessionResults,

                testResults,

                resultFormatterFactory
            });
        }
        internal override void ValidateResults(Eyes eyes, TestResults results)
        {
            SessionResults sessionResults = TestUtils.GetSessionResults(eyes.ApiKey, results);

            ActualAppOutput[] actualAppOutputs = sessionResults.ActualAppOutput;
            Assert.AreEqual(2, actualAppOutputs.Length);

            ImageIdentifier image1 = actualAppOutputs[0].Image;

            Assert.IsTrue(image1.HasDom);
            Assert.AreEqual(1024, image1.Size.Width);
            Assert.AreEqual(768, image1.Size.Height);

            ImageIdentifier image2 = actualAppOutputs[1].Image;

            Assert.IsTrue(image2.HasDom);
        }
示例#20
0
 public ApiCommentController(
     ICommentRepository commentRepo,
     IProfileRepository profileRepo,
     IImageRepository imageRepo,
     IFriendRepository friendRepo,
     ILikeRepository likeRepo,
     IPostRepository postRepo,
     SessionResults sessionResults,
     CurrentProfile currentProfile)
 {
     this.commentRepo    = commentRepo;
     this.profileRepo    = profileRepo;
     this.imageRepo      = imageRepo;
     this.friendRepo     = friendRepo;
     this.likeRepo       = likeRepo;
     this.postRepo       = postRepo;
     this.sessionResults = sessionResults;
     this.currentProfile = currentProfile;
 }
示例#21
0
        public void TestUFGVisualViewport()
        {
            JsonSerializer serializer = JsonUtils.CreateSerializer();
            IWebDriver     driver     = SeleniumUtils.CreateChromeDriver();
            EyesRunner     runner     = new VisualGridRunner(10);
            Eyes           eyes       = new Eyes(runner);

            TestUtils.SetupLogging(eyes);
            Configuration config        = eyes.GetConfiguration();
            IosDeviceInfo iosDeviceInfo = new IosDeviceInfo(IosDeviceName.iPhone_11_Pro);

            config.AddBrowser(iosDeviceInfo);
            eyes.SetConfiguration(config);
            try
            {
                eyes.Open(driver, "Eyes Selenium SDK", "Eyes Selenium SDK - UFG Visual Viewport Test");

                string inputJson = CommonUtils.ReadResourceFile("Test.Eyes.Selenium.DotNet.Resources.Misc.TestUFGVisualViewport_Input.json");
                RenderStatusResults renderStatusResults = serializer.Deserialize <RenderStatusResults>(inputJson);

                driver.Url = "https://applitools.github.io/demo/TestPages/DynamicResolution/desktop.html";
                eyes.Check(Target.Window().Fully());
                eyes.Close(false);

                TestResultsSummary resultsSummary = runner.GetAllTestResults(false);
                Assert.AreEqual(1, resultsSummary.Count);
                TestResults    results        = resultsSummary[0].TestResults;
                SessionResults sessionResults = TestUtils.GetSessionResults(eyes.ApiKey, results);

                Assert.AreEqual(1, sessionResults.ActualAppOutput.Length);
                ActualAppOutput appOutput = sessionResults.ActualAppOutput[0];
                Assert.AreEqual(980, appOutput.Image.Viewport.Width);
                Assert.AreEqual(1659, appOutput.Image.Viewport.Height);

                Assert.AreEqual(375, sessionResults.Env.DisplaySize.Width);
                Assert.AreEqual(812, sessionResults.Env.DisplaySize.Height);
            }
            finally
            {
                eyes.AbortIfNotClosed();
                driver.Quit();
            }
        }
示例#22
0
        /*
         *  Configure services.
         */
        public void ConfigureServices(IServiceCollection services)
        {
            // Add MVC services.
            services.AddMvc();

            // Add Db context service for Application and provide connection string.
            services.AddDbContext <ApplicationDbContext>
                (options => options.UseSqlServer(Configuration["Data:Profile:ConnectionString"]));

            // Add Db context service for Identity and provide connection string.
            services.AddDbContext <AppIdentityDbContext>
                (options => options.UseSqlServer(Configuration["Data:Identity:ConnectionString"]));

            // Add Identity service, configure options, and add EF stores for user storage.
            // This is another layer of validation.
            services.AddIdentity <IdentityUser, IdentityRole>(
                opts =>
            {
                opts.Password.RequiredLength         = 4;
                opts.Password.RequireDigit           = false;
                opts.Password.RequireUppercase       = false;
                opts.Password.RequireNonAlphanumeric = false;
            })
            .AddEntityFrameworkStores <AppIdentityDbContext>();

            // Dependency injection for repositories.
            services.AddTransient <IProfileRepository, EFProfileRepository>();
            services.AddTransient <IPostRepository, EFPostRepository>();
            services.AddTransient <IImageRepository, EFImageRepository>();
            services.AddTransient <IFriendRepository, EFFriendRepository>();
            services.AddTransient <ICommentRepository, EFCommentRepository>();
            services.AddTransient <ILikeRepository, EFLikeRepository>();

            // This service is used in most controllers to verify the user.
            services.AddScoped <CurrentProfile>(sp => SessionProfile.GetCurrentProfile(sp));
            services.AddScoped <SessionResults>(sp => SessionResults.GetSessionResults(sp));
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddMemoryCache();
            services.AddSession();
        }
示例#23
0
        private static SessionResults GetSessionResults_(Eyes eyes, TestResults results)
        {
            string apiSessionUrl = results.ApiUrls?.Session;

            SessionResults sessionResults = null;

            if (apiSessionUrl != null)
            {
                var uriBuilder = new UriBuilder(apiSessionUrl);
                var query      = HttpUtility.ParseQueryString(uriBuilder.Query);
                query["format"]      = "json";
                query["AccessToken"] = results.SecretToken;
                query["apiKey"]      = eyes.ApiKey;
                uriBuilder.Query     = query.ToString();

                HttpRestClient client      = new HttpRestClient(uriBuilder.Uri);
                var            metaResults = client.Get(uriBuilder.ToString());
                sessionResults = metaResults.DeserializeBody <SessionResults>(false);
            }
            return(sessionResults);
        }
示例#24
0
 // Called after processing a script, ok=normal termination
 // Local will save if update true
 // Sql will commit if update true, else abort
 public void EndSession(SessionResults result)
 {
     if (_sessionstate == SessionState.None)
     {
         return;
     }
     if (_sessionstate == SessionState.Ended)
     {
         return;
     }
     Logger.WriteLine(3, $"End session {result}");
     if (SqlFlag)
     {
         SqlTarget.Current.EndSession(result == SessionResults.Ok && SaveFlag);
     }
     else if (result == SessionResults.Ok && SaveFlag)
     {
         StoreToTable();
     }
     _sessionstate = SessionState.Ended;
 }
示例#25
0
        private readonly IHostingEnvironment env; // Used to deal with server files.

        public ApiImageController(
            IImageRepository imageRepo,
            IPostRepository postRepo,
            ICommentRepository commentRepo,
            IProfileRepository profileRepo,
            ILikeRepository likeRepo,
            IFriendRepository friendRepo,
            SessionResults sessionResults,
            CurrentProfile currentProfile,
            IHostingEnvironment env)
        {
            this.imageRepo      = imageRepo;
            this.postRepo       = postRepo;
            this.commentRepo    = commentRepo;
            this.profileRepo    = profileRepo;
            this.likeRepo       = likeRepo;
            this.friendRepo     = friendRepo;
            this.sessionResults = sessionResults;
            this.currentProfile = currentProfile;
            this.env            = env;
        }
        public static SessionResults GetSessionResults(Eyes eyes, TestResults testResults)
        {
            string apiSessionUrl = testResults?.ApiUrls?.Session;

            if (string.IsNullOrWhiteSpace(apiSessionUrl))
            {
                return(null);
            }
            UriBuilder          uriBuilder = new UriBuilder(apiSessionUrl);
            NameValueCollection query      = HttpUtility.ParseQueryString(uriBuilder.Query);

            query["format"]      = "json";
            query["AccessToken"] = testResults.SecretToken;
            query["apiKey"]      = eyes.ApiKey;
            uriBuilder.Query     = query.ToString();

            HttpRestClient  client         = new HttpRestClient(uriBuilder.Uri);
            HttpWebResponse metaResults    = client.Get(uriBuilder.ToString());
            SessionResults  sessionResults = metaResults.DeserializeBody <SessionResults>(false);

            return(sessionResults);
        }
示例#27
0
        public void TestSendDOM_FullWindow()
        {
            IWebDriver webDriver = SeleniumUtils.CreateChromeDriver();

            webDriver.Url = "https://applitools.github.io/demo/TestPages/FramesTestPage/";
            DomInterceptingEyes eyes = new DomInterceptingEyes();

            eyes.Batch = TestDataProvider.BatchInfo;

            EyesWebDriver eyesWebDriver = (EyesWebDriver)eyes.Open(webDriver, "Test Send DOM", "Full Window", new Size(1024, 768));

            try
            {
                eyes.Check(Target.Window().Fully().WithName("Window"));
                string actualDomJsonString = eyes.DomJson;

                string expectedDomJsonString = CommonUtils.ReadResourceFile("Test.Eyes.Selenium.DotNet.Resources.expected_dom1.json");
                string expectedDomJson       = JsonUtility.NormalizeJsonString(expectedDomJsonString);

                TestResults results = eyes.Close(false);
                bool        hasDom  = GetHasDom_(eyes, results);
                Assert.IsTrue(hasDom);

                string actualDomJson = JsonUtility.NormalizeJsonString(actualDomJsonString);
                Assert.AreEqual(expectedDomJson, actualDomJson);

                SessionResults    sessionResults          = TestUtils.GetSessionResults(eyes.ApiKey, results);
                ActualAppOutput[] actualAppOutput         = sessionResults.ActualAppOutput;
                string            downloadedDomJsonString = TestUtils.GetStepDom(eyes, actualAppOutput[0]);
                string            downloadedDomJson       = JsonUtility.NormalizeJsonString(downloadedDomJsonString);
                Assert.AreEqual(expectedDomJson, downloadedDomJson);
            }
            finally
            {
                eyes.Abort();
                webDriver.Quit();
            }
        }
示例#28
0
        /// <summary>
        /// Central sending function.
        /// </summary>
        /// <param name="receiverID">The ID of the receiver module. Can be <b>null</b> and this sends to all in the Arbiter.</param>
        protected TransportMessage[] DoSendCustom(bool isRequest, Guid sessionGuid,
                                                  Type expectedResponseMessageClassType, int responsesRequired,
                                                  ArbiterClientId?receiverId, ArbiterClientId?senderId, TransportMessage message, TimeSpan timeOut)
        {
            //TracerHelper.TraceEntry();

            SessionResults session = null;

            if (receiverId.HasValue && receiverId.Value.IsEmpty /*receiverId.Value.CompareTo(ArbiterClientId.Empty) == 0*/)
            {
                SystemMonitor.Error("Can not send an item to empty receiver. Use null to specify broadcast.");
                return(null);
            }

            // Preliminary verification.
            if (Arbiter == null)
            {
                SystemMonitor.OperationWarning("Using a client [" + this.GetType().Name + ":" + senderId.Value.ClientName + " to " + (receiverId.HasValue ? receiverId.Value.Id.Name : string.Empty) + " , " + message.GetType().Name + "] with no Arbiter assigned.");
                return(null);
            }

            message.IsRequest = isRequest;

            TransportInfoUnit infoUnit = new TransportInfoUnit(sessionGuid, senderId, receiverId);

            message.TransportInfo.AddTransportInfoUnit(infoUnit);

            bool sessionEventResult = false;

            if (expectedResponseMessageClassType != null)
            {// Responce waiting session.
                session = new SessionResults(responsesRequired, expectedResponseMessageClassType);
                lock (_communicationSessions)
                {// Register the session.
                    _communicationSessions.Add(sessionGuid, session);
                }
            }

            SystemMonitor.CheckError(message.TransportInfo.CurrentTransportInfo != null);
            Conversation conversation;

            if (receiverId == null)
            {
                // We shall not use the next level time out mechanism.
                conversation = Arbiter.CreateConversation(senderId.Value, message, TimeSpan.Zero);
            }
            else
            {// Addressed conversation.
                // We shall not use the next level time out mechanism.
                conversation = Arbiter.CreateConversation(senderId.Value, receiverId.Value, message, TimeSpan.Zero);
            }

            if (conversation != null && expectedResponseMessageClassType != null)
            {     // Responce waiting session (only if conversation was properly created).
                if (timeOut == TimeSpan.Zero)
                { // Wait forever.
                    sessionEventResult = session.SessionEndEvent.WaitOne();
                }
                else
                {// Wait given period.
                    sessionEventResult = session.SessionEndEvent.WaitOne(timeOut, false);
                }

                lock (_communicationSessions)
                {// Remote the session.
                    _communicationSessions.Remove(sessionGuid);
                }
            }

            message.TransportInfo.PopTransportInfo();

            if (expectedResponseMessageClassType == null)
            {// No responce waiting, just return.
                //TracerHelper.TraceExit();
                return(null);
            }

            // Responce waiting session.
            if (sessionEventResult == false)
            {// Timed out - only send and receives can time out, as the other ones do not have sessions!!
                TracerHelper.TraceError("Session has timed out [" + message.GetType().Name + "].");
                return(null);
            }

            //TracerHelper.TraceExit();
            return(session.Responses.ToArray());
        }
示例#29
0
        public void TestAccessibility(bool useVisualGrid)
        {
            string      suffix     = useVisualGrid ? "_VG" : "";
            ILogHandler logHandler = TestUtils.InitLogHandler(nameof(TestAccessibility) + suffix);
            EyesRunner  runner     = useVisualGrid ? (EyesRunner) new VisualGridRunner(10, logHandler) : new ClassicRunner(logHandler);
            Eyes        eyes       = new Eyes(runner);

            eyes.Batch = TestDataProvider.BatchInfo;
            AccessibilitySettings settings      = new AccessibilitySettings(AccessibilityLevel.AA, AccessibilityGuidelinesVersion.WCAG_2_0);
            Configuration         configuration = eyes.GetConfiguration();

            configuration.SetAccessibilityValidation(settings);
            eyes.SetConfiguration(configuration);
            IWebDriver driver = SeleniumUtils.CreateChromeDriver();

            try
            {
                driver.Url = "https://applitools.github.io/demo/TestPages/FramesTestPage/";
                eyes.Open(driver, "Applitools Eyes SDK", "TestAccessibility_Sanity" + suffix, new Size(700, 460));
                eyes.Check("Sanity", Target.Window().Accessibility(By.ClassName("ignore"), AccessibilityRegionType.LargeText));
                eyes.CloseAsync();
                configuration.SetAccessibilityValidation(null);
                eyes.SetConfiguration(configuration);
                eyes.Open(driver, "Applitools Eyes SDK", "TestAccessibility_No_Accessibility" + suffix, new Size(1200, 800));
                eyes.CheckWindow("No accessibility");
                eyes.CloseAsync();
            }
            finally
            {
                driver.Quit();
                eyes.AbortAsync();
                TestResultsSummary allTestResults = runner.GetAllTestResults(false);

                Assert.AreEqual(2, allTestResults.Count);
                TestResults resultSanity          = allTestResults[0].TestResults;
                TestResults resultNoAccessibility = allTestResults[1].TestResults;
                // Visual grid runner doesn't guarantee the order of the results
                if (resultNoAccessibility.Name.StartsWith("TestAccessibility_Sanity"))
                {
                    TestResults temp = resultSanity;
                    resultSanity          = resultNoAccessibility;
                    resultNoAccessibility = temp;
                }

                // Testing the accessibility status returned in the results
                SessionAccessibilityStatus accessibilityStatus = resultSanity.AccessibilityStatus;
                Assert.AreEqual(AccessibilityLevel.AA, accessibilityStatus.Level);
                Assert.AreEqual(AccessibilityGuidelinesVersion.WCAG_2_0, accessibilityStatus.Version);

                Assert.IsNull(resultNoAccessibility.AccessibilityStatus);

                // Testing the accessibility settings sent in the start info
                SessionResults sessionResults = TestUtils.GetSessionResults(eyes.ApiKey, resultSanity);
                Metadata.ImageMatchSettings defaultMatchSettings = sessionResults.StartInfo.DefaultMatchSettings;
                Assert.AreEqual(AccessibilityGuidelinesVersion.WCAG_2_0, defaultMatchSettings.AccessibilitySettings.GuidelinesVersion);
                Assert.AreEqual(AccessibilityLevel.AA, defaultMatchSettings.AccessibilitySettings.Level);

                // Testing the accessibility regions sent in the session
                var matchSettings = sessionResults.ActualAppOutput[0].ImageMatchSettings;
                var actualRegions = matchSettings.Accessibility;
                HashSet <AccessibilityRegionByRectangle> expectedRegions = new HashSet <AccessibilityRegionByRectangle>();
                expectedRegions.Add(new AccessibilityRegionByRectangle(122, 933, 456, 306, AccessibilityRegionType.LargeText));
                expectedRegions.Add(new AccessibilityRegionByRectangle(8, 1277, 690, 206, AccessibilityRegionType.LargeText));
                if (useVisualGrid)
                {
                    expectedRegions.Add(new AccessibilityRegionByRectangle(10, 286, 800, 500, AccessibilityRegionType.LargeText));
                }
                else
                {
                    expectedRegions.Add(new AccessibilityRegionByRectangle(10, 286, 285, 165, AccessibilityRegionType.LargeText));
                }
                TestSetup.CompareAccessibilityRegionsList_(actualRegions, expectedRegions, "Accessibility");
            }
        }
示例#30
0
        static void Main(string[] args)
        {
            //Set ctrl-c handler
            SetConsoleCtrlHandler(ConsoleCtrlCheck, true);


            if (args.Contains("--verbose") || args.Contains("-v"))
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.Verbose()
                             .WriteTo.Console()
                             .CreateLogger();
            }
            else
            {
                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.Information()
                             .WriteTo.Console()
                             .CreateLogger();
            }

            LoadConfig();

            _saltyBetConsole = new SaltyConsole();
            ForbiddingManse  = new ForbiddingManse();

            _sessionResults    = new SessionResults();
            _tournamentResults = new SessionResults();

            _bettingEngine           = new ExpectedProfitBet();
            _tournamentBettingEngine = new TournamentBet(ForbiddingManse);
            _exibhitionBettingEngine = new ExpectedProfitBet(exhibitionMatches: true);
            _bettingEngineBackup     = new RandomBet();

            try
            {
                Log.Information("Database contains {CharacterCount} Characters.",
                                +ForbiddingManse.Characters.Count());
            }
            catch (System.Data.Entity.ModelConfiguration.ModelValidationException e)
            {
                Log.Warning(e, "Database is empty.");
            }
            catch (Exception e)
            {
                Log.Error(e, "Problem with the database.");
            }


            _saltyBetConsole.LoginSuccess += SaltyBetConsoleOnLoginSuccess;
            _saltyBetConsole.MatchStart   += ConsoleOnMatchStart;
            _saltyBetConsole.MatchEnded   += ConsoleOnMatchEnded;

            _saltyBetConsole.TournamentMatchStart += ConsoleOnTournamentMatchStart;
            _saltyBetConsole.TournamentMatchEnded += ConsoleOnTournamentMatchEnded;
            _saltyBetConsole.TournamentEnded      += SaltyBetConsoleOnTournamentEnded;

            _saltyBetConsole.ExhibitionMatchStart += SaltyBetConsoleOnExhibitionMatchStart;
            _saltyBetConsole.ExhibitionMatchEnded += SaltyBetConsoleOnExhibitionMatchEnded;

            _saltyBetConsole.TwitchLoginSuccess += SaltyBetConsoleOnTwitchLoginSuccess;

            _saltyBetConsole.Start(_saltyConfiguration.SaltyAccount, _saltyConfiguration.SaltyAccountPassword, _saltyConfiguration.TwitchAccount, _saltyConfiguration.TwitchToken);
        }