Esempio n. 1
0
        public void IsValidMutableString(TestPair p)
        {
            MutableString ms = null != p.StringValue ? new MutableString(p.StringValue) : null;

            Assert.IsTrue(AlphanumericUtils.IsValidAlphanumeric(ms));
            Assert.IsTrue(AlphanumericUtils.IsValidAlphanumeric((IReadOnlyString)(new MutableString().Assign(ms))));
        }
Esempio n. 2
0
        public void MutableStringToInt64AndBack(TestPair p)
        {
            MutableString ms = null != p.StringValue ? new MutableString(p.StringValue) : null;

            Assert.AreEqual(ms, AlphanumericUtils.ToMutableString(AlphanumericUtils.ToAlphanumericInt64(ms)));
            Assert.AreEqual(ms, AlphanumericUtils.ToMutableString(AlphanumericUtils.ToAlphanumericUInt64(ms)));
        }
Esempio n. 3
0
 public float this[TestPair pair]
 {
     get
     {
         Entry entry = Table[pair.Probe.Finger][pair.Probe.View];
         if (pair.IsMatching)
         {
             return(entry.Matching[GetMatchingOffset(pair)]);
         }
         else
         {
             return(entry.NonMatching[GetNonMatchingOffset(pair)]);
         }
     }
     set
     {
         Entry entry = Table[pair.Probe.Finger][pair.Probe.View];
         if (pair.IsMatching)
         {
             entry.Matching[GetMatchingOffset(pair)] = value;
         }
         else
         {
             entry.NonMatching[GetNonMatchingOffset(pair)] = value;
         }
     }
 }
Esempio n. 4
0
        public void Tests()
        {
            var testPairs = new TestPair[]
            {
                new TestPair
                {
                    OldList = new List <int> {
                        6, 2, 4, 0
                    },
                    NewList = new List <int> {
                        0, 2, 3, 4, 1
                    }
                },
                new TestPair
                {
                    OldList = new List <int> {
                        1, 2, 3, 4, 1
                    },
                    NewList = new List <int> {
                        3, 4, 1, 2, 1, 3
                    }
                },
                new TestPair
                {
                    OldList = new List <int> {
                        9, 8, 7
                    },
                    NewList = new List <int> {
                        9, 1, 2, 6
                    }
                },
                new TestPair
                {
                    OldList = new List <int> {
                        3, 9, 8, 3, 9, 7, 9, 7, 0
                    },
                    NewList = new List <int> {
                        3, 3, 9, 9, 9, 1, 7, 2, 0, 6
                    }
                },
                new TestPair
                {
                    OldList = new List <int> {
                        1, 2
                    },
                    NewList = new List <int> {
                        3, 4, 5
                    }
                }
            };

            foreach (var test in testPairs)
            {
                var changeList = new ChangeList <int>(test.OldList, test.NewList);
                AssertValidChange(test.OldList, test.NewList, changeList);
            }
        }
Esempio n. 5
0
        public void ToStringOverrideWorksCorrectlyWithStrings()
        {
            var stringRepresentation = new TestPair <int, string>(0, "0").ToString();

            Assert.AreEqual(stringRepresentation, "(0,0)");

            var stringRepresentation2 = new TestPair <string, string>(@"(*,", @"(()").ToString();

            Assert.AreEqual(stringRepresentation2, "((*,,(())");
        }
Esempio n. 6
0
        public void ToStringOverrideWorksCorrectlyWithNulls()
        {
            var stringRepresentation = new TestPair <int, string>().ToString();

            Assert.AreEqual(stringRepresentation, "(0,)");

            var stringRepresentation2 = new TestPair <int, XYPoint>(0, null).ToString();

            //right hand type needs to be reference-type and implement IEquatable.
            Assert.AreEqual(stringRepresentation2, "(0,)");
        }
Esempio n. 7
0
        public void Int64ToMutableStringAndBack(TestPair p)
        {
            Assert.AreEqual(p.IntValue, AlphanumericUtils.ToAlphanumericInt64(AlphanumericUtils.ToMutableString(p.IntValue)));
            Assert.AreEqual(p.IntValue, AlphanumericUtils.ToAlphanumericInt64(AlphanumericUtils.ToMutableString((UInt64)p.IntValue)));
            Assert.AreEqual(p.IntValue, (Int64)AlphanumericUtils.ToAlphanumericUInt64(AlphanumericUtils.ToMutableString(p.IntValue)));
            Assert.AreEqual(p.IntValue, (Int64)AlphanumericUtils.ToAlphanumericUInt64(AlphanumericUtils.ToMutableString((UInt64)p.IntValue)));

            Assert.AreEqual((UInt64)p.IntValue, AlphanumericUtils.ToAlphanumericUInt64(AlphanumericUtils.ToMutableString(p.IntValue)));
            Assert.AreEqual((UInt64)p.IntValue, AlphanumericUtils.ToAlphanumericUInt64(AlphanumericUtils.ToMutableString((UInt64)p.IntValue)));
            Assert.AreEqual((UInt64)p.IntValue, (UInt64)AlphanumericUtils.ToAlphanumericInt64(AlphanumericUtils.ToMutableString(p.IntValue)));
            Assert.AreEqual((UInt64)p.IntValue, (UInt64)AlphanumericUtils.ToAlphanumericInt64(AlphanumericUtils.ToMutableString((UInt64)p.IntValue)));
        }
Esempio n. 8
0
        public void ReadValuesBackFromObject()
        {
            var createdObject = new TestPair <int, int>(1, 2);

            Assert.AreEqual(1, createdObject.X);
            Assert.AreEqual(2, createdObject.Y);

            var createdObject2 = new TestPair <string, int>("A", 3);

            Assert.AreEqual("A", createdObject2.X);
            Assert.AreEqual(3, createdObject2.Y);
        }
Esempio n. 9
0
        public ActionResult GetDynamicFormJson(string studyId, int periodId, string formGroupId, string subjectId, int entryType)
        {
            var list  = new List <TestPair <FormConfig, FormField, FieldValue> >();
            var forms = Entities.FormConfigs.Where(x => x.FormGroupId == formGroupId && !x.Disabled && x.Display).ToList();

            foreach (var oneform in forms)
            {
                var formName = oneform.FormId;
                var fields   = Entities.FormFields.Where(x => x.FormId == formName).Select(x => x).OrderBy(x => x.Order).ToList();
                var item     = new TestPair <FormConfig, FormField, FieldValue>()
                {
                    Form = oneform, FieldList = fields, ValueList = new List <List <FieldValue> >()
                };
                list.Add(item);

                var rows = oneform.Rows;
                for (int i = 0; i <= rows; i++)
                {
                    var valueList = new List <FieldValue>();
                    var values    = Entities.FieldValues
                                    .Where(x => x.FormId == formName && x.RowIndex == i && x.SubjectId == subjectId && x.EntryType == entryType)
                                    .Select(x => x).ToDictionary(x => x.FieldId);
                    var prefills = Entities.PrefilledFields.Where(x => x.FormId == formName && x.RowIndex == i).Select(x => x).ToDictionary(x => x.FieldId);
                    foreach (FormField field in fields)
                    {
                        if (prefills.ContainsKey(field.FieldId))
                        {
                            valueList.Add(new FieldValue()
                            {
                                FieldValue1 = prefills[field.FieldId].FieldValue
                            });
                        }
                        else if (values.ContainsKey(field.FieldId))
                        {
                            valueList.Add(values[field.FieldId]);
                        }
                        else
                        {
                            valueList.Add(new FieldValue());
                        }
                    }
                    item.ValueList.Add(valueList);
                } // for
            }

            return(CamelJson(new { success = 0 }));
        }
Esempio n. 10
0
        public void Player_registration_fails_when_username_already_exists()
        {
            const string userName = "******";
            var          brand139 = new Core.Brand.Interface.Data.Brand {
                Id = Guid.NewGuid(), Name = "139"
            };

            FakePlayerRepository.Players.Add(new Core.Common.Data.Player.Player {
                Username = userName, BrandId = brand139.Id
            });

            var testCase = new TestPair(r => r.Username, userName);

            ValidateTestCase(testCase, true);

            FakeBrandRepository.Brands.Add(brand139);
            ValidateTestCase(testCase);
        }
Esempio n. 11
0
        public void Int64AssignToMString(TestPair p)
        {
            MutableString ms1 = new MutableString(), ms2 = new MutableString("ewrfvewrtfcr\tmewfxlqwoexhfsm3egzfsqewir\r \nqfaGFEWFW");

            AlphanumericUtils.AssignAlphanumeric(ms1, p.IntValue);
            AlphanumericUtils.AssignAlphanumeric(ms2, p.IntValue);

            if (p.StringValue == null)
            {
                Assert.AreEqual("", ms1.ToString());
                Assert.AreEqual("", ms2.ToString());
            }
            else
            {
                Assert.AreEqual(p.StringValue, ms1.ToString());
                Assert.AreEqual(p.StringValue, ms2.ToString());
            }

            Assert.AreEqual(ms1, ms2);
        }
Esempio n. 12
0
        public void Player_registration_fails_when_email_already_exists()
        {
            const string email = "*****@*****.**";

            var brand139 = new Core.Brand.Interface.Data.Brand {
                Id = Guid.NewGuid(), Name = "139"
            };

            FakePlayerRepository.Players.Add(new Core.Common.Data.Player.Player {
                Email = email, BrandId = brand139.Id
            });

            var testCase = new TestPair(r => r.Email, email);

            ValidateTestCase(testCase, true);

            FakeBrandRepository.Brands.Add(brand139);

            ValidateTestCase(testCase);
        }
Esempio n. 13
0
        private void ValidateTestCase(TestPair propertyValuePair, bool validCase = false)
        {
            var propertyName = GetPropertyName(propertyValuePair.Item1);

            var registrationData = TestDataGenerator.CreateRandomRegistrationData();

            SetPropertyValue(registrationData, propertyName, propertyValuePair.Item2);
            if (propertyName == "Password")
            {
                SetPropertyValue(registrationData, "PasswordConfirm", propertyValuePair.Item2);
            }

            if (validCase)
            {
                var result = PlayerCommands.Register(registrationData);
                Assert.That(result, Is.Not.EqualTo(Guid.Empty));
            }
            else
            {
                var e = Assert.Throws <ValidationException>(() => PlayerCommands.Register(registrationData));
                Assert.That(e.Errors.Count(), Is.GreaterThanOrEqualTo(1));
                Assert.That(e.Errors.First().ErrorMessage, Is.Not.Empty);
            }
        }
Esempio n. 14
0
 public void Gather(ref TestPair <TShapeA, TShapeB> source)
 {
     A.Gather(ref source.A);
     B.Gather(ref source.B);
     ref var shared = ref source.Shared;
Esempio n. 15
0
 public void StringToInt64AndBack(TestPair p)
 {
     Assert.AreEqual(p.StringValue, AlphanumericUtils.ToString(AlphanumericUtils.ToAlphanumericInt64(p.StringValue)));
     Assert.AreEqual(p.StringValue, AlphanumericUtils.ToString(AlphanumericUtils.ToAlphanumericUInt64(p.StringValue)));
 }
Esempio n. 16
0
 public void Int64ToString(TestPair p)
 {
     Assert.AreEqual(p.StringValue, AlphanumericUtils.ToString(p.IntValue));
     Assert.AreEqual(p.StringValue, AlphanumericUtils.ToString((UInt64)p.IntValue));
 }
Esempio n. 17
0
 public void Player_registration_fails_when_fields_not_within_its_allowed_range(TestPair propertyValuePair)
 {
     ValidateTestCase(propertyValuePair);
 }
Esempio n. 18
0
 public void Player_registration_should_not_fail_when_fields_are_valid(TestPair propertyValuePair)
 {
     ValidateTestCase(propertyValuePair, true);
 }
Esempio n. 19
0
 public void IsValidString(TestPair p)
 {
     Assert.IsTrue(AlphanumericUtils.IsValidAlphanumeric(p.StringValue));
     Assert.IsTrue(AlphanumericUtils.IsValidAlphanumeric((IReadOnlyString)(new MutableString().Assign(p.StringValue))));
 }
Esempio n. 20
0
 public void Player_regisration_fails_when_required_field_is_missing(TestPair propertyValuePair)
 {
     ValidateTestCase(propertyValuePair);
 }
Esempio n. 21
0
 public void PrintStr(TestPair p)
 {
     Console.WriteLine("0x{0:X} -> '{1}'", p.intValue, AlphanumericUtils.ToString(p.intValue));
 }
Esempio n. 22
0
 public void PrintHex(TestPair p)
 {
     Console.WriteLine("'{0}' -> 0x{1:X}", p.stringValue, AlphanumericUtils.ToAlphanumericInt64(p.stringValue));
 }
        protected override async void HandleClient(SimpleSocket clientSocket, string url)
        {
            await AcceptConnection(clientSocket);

            var socketMessageLayer = new SocketMessageLayer(clientSocket, true);

            socketMessageLayer.AddPacketHandler<TestRegistrationRequest>(request =>
            {
                if (request.Tester)
                {
                    switch (request.Platform)
                    {
                        case (int)PlatformType.Windows:
                            {
                                Process process = null;
                                var debugInfo = "";
                                try
                                {
                                    var workingDir = Path.GetDirectoryName(request.Cmd);
                                    if (workingDir != null)
                                    {
                                        var start = new ProcessStartInfo
                                        {
                                            WorkingDirectory = workingDir,
                                            FileName = request.Cmd
                                        };
                                        start.EnvironmentVariables["SiliconStudioXenkoDir"] = Environment.GetEnvironmentVariable("SiliconStudioXenkoDir");
                                        start.UseShellExecute = false;
                                        start.RedirectStandardError = true;
                                        start.RedirectStandardOutput = true;

                                        debugInfo = "Starting process " + start.FileName + " with path " + start.WorkingDirectory;
                                        socketMessageLayer.Send(new LogRequest { Message = debugInfo }).Wait();
                                        process = Process.Start(start);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    socketMessageLayer.Send(new StatusMessageRequest { Error = true, Message = "Launch exception: " + ex.Message }).Wait();
                                }

                                if (process == null)
                                {
                                    socketMessageLayer.Send(new StatusMessageRequest { Error = true, Message = "Failed to start game process. " + debugInfo }).Wait();
                                }
                                else
                                {
                                    process.OutputDataReceived += (sender, args) =>
                                    {
                                        try
                                        {
                                            socketMessageLayer.Send(new LogRequest { Message = $"STDIO: {args.Data}" }).Wait();
                                        }
                                        catch
                                        {
                                        }
                                    };

                                    process.ErrorDataReceived += (sender, args) =>
                                    {
                                        try
                                        {
                                            socketMessageLayer.Send(new LogRequest { Message = $"STDERR: {args.Data}" }).Wait();
                                        }
                                        catch
                                        {
                                        }
                                    };

                                    process.BeginOutputReadLine();
                                    process.BeginErrorReadLine();

                                    var currenTestPair = new TestPair { TesterSocket = socketMessageLayer, GameName = request.GameAssembly, Process = process };
                                    processes[request.GameAssembly] = currenTestPair;
                                    testerToGame[socketMessageLayer] = currenTestPair;
                                    socketMessageLayer.Send(new LogRequest { Message = "Process created, id: " + process.Id.ToString() }).Wait();
                                }
                                break;
                            }
                        case (int)PlatformType.Android:
                            {
                                Process process = null;
                                try
                                {
                                    process = Process.Start("cmd.exe", $"/C adb shell monkey -p {request.GameAssembly}.{request.GameAssembly} -c android.intent.category.LAUNCHER 1");
                                }
                                catch (Exception ex)
                                {
                                    socketMessageLayer.Send(new StatusMessageRequest { Error = true, Message = "Launch exception: " + ex.Message }).Wait();
                                }

                                if (process == null)
                                {
                                    socketMessageLayer.Send(new StatusMessageRequest { Error = true, Message = "Failed to start game process." }).Wait();
                                }
                                else
                                {
                                    lock (loggerLock)
                                    {
                                        currentTester = socketMessageLayer;
                                    }

                                    var currenTestPair = new TestPair
                                    {
                                        TesterSocket = socketMessageLayer,
                                        GameName = request.GameAssembly,
                                        Process = process,
                                        TestEndAction = () =>
{
                                            // force stop - only works for Android 3.0 and above.
                                            Process.Start("cmd.exe", $"/C adb shell am force-stop {request.GameAssembly}.{request.GameAssembly}");
}
                                    };
                                    processes[request.GameAssembly] = currenTestPair;
                                    testerToGame[socketMessageLayer] = currenTestPair;
                                    socketMessageLayer.Send(new LogRequest { Message = "Process created, id: " + process.Id.ToString() }).Wait();
                                }
                                break;
                            }
                        case (int)PlatformType.iOS:
                            {
                                Process process = null;
                                var debugInfo = "";
                                try
                                {
                                    Thread.Sleep(5000); //ios processes might be slow to close, we must make sure that we start clean
                                    var start = new ProcessStartInfo
                                    {
                                        WorkingDirectory = $"{Environment.GetEnvironmentVariable("SiliconStudioXenkoDir")}\\Bin\\Windows-Direct3D11\\",
                                        FileName = $"{Environment.GetEnvironmentVariable("SiliconStudioXenkoDir")}\\Bin\\Windows-Direct3D11\\idevicedebug.exe",
                                        Arguments = $"run com.your-company.{request.GameAssembly}",
                                        UseShellExecute = false
                                    };
                                    debugInfo = "Starting process " + start.FileName + " with path " + start.WorkingDirectory;
                                    process = Process.Start(start);
                                }
                                catch (Exception ex)
                                {
                                    socketMessageLayer.Send(new StatusMessageRequest { Error = true, Message = $"Launch exception: {ex.Message} info: {debugInfo}" }).Wait();
                                }

                                if (process == null)
                                {
                                    socketMessageLayer.Send(new StatusMessageRequest { Error = true, Message = "Failed to start game process. " + debugInfo }).Wait();
                                }
                                else
                                {
                                    lock (loggerLock)
                                    {
                                        currentTester = socketMessageLayer;
                                    }

                                    var currenTestPair = new TestPair { TesterSocket = socketMessageLayer, GameName = request.GameAssembly, Process = process };
                                    processes[request.GameAssembly] = currenTestPair;
                                    testerToGame[socketMessageLayer] = currenTestPair;
                                    socketMessageLayer.Send(new LogRequest { Message = "Process created, id: " + process.Id.ToString() }).Wait();
                                }
                                break;
                            }
                    }
                }
                else //Game process
                {
                    TestPair pair;
                    if (!processes.TryGetValue(request.GameAssembly, out pair)) return;

                    pair.GameSocket = socketMessageLayer;

                    testerToGame[pair.TesterSocket] = pair;
                    gameToTester[pair.GameSocket] = pair;

                    pair.TesterSocket.Send(new StatusMessageRequest { Error = false, Message = "Start" }).Wait();

                    Console.WriteLine($"Starting test {request.GameAssembly}");
                }
            });

            socketMessageLayer.AddPacketHandler<KeySimulationRequest>(request =>
            {
                var game = testerToGame[socketMessageLayer];
                game.GameSocket.Send(request).Wait();
            });

            socketMessageLayer.AddPacketHandler<TapSimulationRequest>(request =>
            {
                var game = testerToGame[socketMessageLayer];
                game.GameSocket.Send(request).Wait();
            });

            socketMessageLayer.AddPacketHandler<ScreenshotRequest>(request =>
            {
                var game = testerToGame[socketMessageLayer];
                game.GameSocket.Send(request).Wait();
            });

            socketMessageLayer.AddPacketHandler<TestEndedRequest>(request =>
            {
                var game = testerToGame[socketMessageLayer];
                game.GameSocket.Send(request).Wait();

                testerToGame.Remove(socketMessageLayer);
                gameToTester.Remove(game.GameSocket);
                processes.Remove(game.GameName);

                socketMessageLayer.Context.Dispose();
                game.GameSocket.Context.Dispose();

                game.Process.Kill();
                game.Process.Dispose();

                lock (loggerLock)
                {
                    currentTester = null;
                }

                game.TestEndAction?.Invoke();

                Console.WriteLine($"Finished test {game.GameName}");
            });

            socketMessageLayer.AddPacketHandler<TestAbortedRequest>(request =>
            {
                var game = testerToGame[socketMessageLayer];

                testerToGame.Remove(socketMessageLayer);
                processes.Remove(game.GameName);

                socketMessageLayer.Context.Dispose();

                game.Process.Kill();
                game.Process.Dispose();

                lock (loggerLock)
                {
                    currentTester = null;
                }

                game.TestEndAction?.Invoke();

                Console.WriteLine($"Aborted test {game.GameName}");
            });

            socketMessageLayer.AddPacketHandler<ScreenShotPayload>(request =>
            {
                var tester = gameToTester[socketMessageLayer];

                var imageData = new TestResultImage();
                var stream = new MemoryStream(request.Data);
                imageData.Read(new BinaryReader(stream));
                stream.Dispose();
                var resultFileStream = File.OpenWrite(request.FileName);
                imageData.Image.Save(resultFileStream, ImageFileType.Png);
                resultFileStream.Dispose();

                tester.TesterSocket.Send(new ScreenshotStored()).Wait();
            });

            Task.Run(async () =>
            {
                try
                {
                    await socketMessageLayer.MessageLoop();
                }
                catch
                {
                }
            });
        }
Esempio n. 24
0
        public void ToStringOverrideWorksCorrectly()
        {
            var stringRepresentation = new TestPair <int, long>().ToString();

            Assert.AreEqual(stringRepresentation, "(0,0)");
        }
Esempio n. 25
0
 int GetNonMatchingOffset(TestPair pair)
 {
     return(GetViewOffset(pair.Probe.View, pair.Candidate.View) * (FingerCount - 1)
            + GetDistinctFingerOffset(pair.Probe.Finger, pair.Candidate.Finger));
 }
Esempio n. 26
0
        protected override async void HandleClient(SimpleSocket clientSocket, string url)
        {
            await AcceptConnection(clientSocket);

            var socketMessageLayer = new SocketMessageLayer(clientSocket, true);

            socketMessageLayer.AddPacketHandler <TestRegistrationRequest>(async request =>
            {
                if (request.Tester)
                {
                    switch (request.Platform)
                    {
                    case (int)PlatformType.Windows:
                        {
                            Process process = null;
                            var debugInfo   = "";
                            try
                            {
                                var workingDir = Path.GetDirectoryName(request.Cmd);
                                if (workingDir != null)
                                {
                                    var start = new ProcessStartInfo
                                    {
                                        WorkingDirectory = workingDir,
                                        FileName         = request.Cmd
                                    };
                                    start.UseShellExecute        = false;
                                    start.RedirectStandardError  = true;
                                    start.RedirectStandardOutput = true;

                                    debugInfo = "Starting process " + start.FileName + " with path " + start.WorkingDirectory;
                                    await socketMessageLayer.Send(new LogRequest {
                                        Message = debugInfo
                                    });
                                    process = Process.Start(start);
                                }
                            }
                            catch (Exception ex)
                            {
                                await socketMessageLayer.Send(new StatusMessageRequest {
                                    Error = true, Message = "Launch exception: " + ex.Message
                                });
                            }

                            if (process == null)
                            {
                                await socketMessageLayer.Send(new StatusMessageRequest {
                                    Error = true, Message = "Failed to start game process. " + debugInfo
                                });
                            }
                            else
                            {
                                process.OutputDataReceived += async(sender, args) =>
                                {
                                    try
                                    {
                                        if (args.Data != null)
                                        {
                                            await socketMessageLayer.Send(new LogRequest {
                                                Message = $"STDIO: {args.Data}"
                                            });
                                        }
                                    }
                                    catch
                                    {
                                    }
                                };

                                process.ErrorDataReceived += async(sender, args) =>
                                {
                                    try
                                    {
                                        if (args.Data != null)
                                        {
                                            await socketMessageLayer.Send(new LogRequest {
                                                Message = $"STDERR: {args.Data}"
                                            });
                                        }
                                    }
                                    catch
                                    {
                                    }
                                };

                                process.BeginOutputReadLine();
                                process.BeginErrorReadLine();

                                var currenTestPair = new TestPair {
                                    TesterSocket = socketMessageLayer, GameName = request.GameAssembly, Process = process
                                };
                                lock (processes)
                                {
                                    processes[request.GameAssembly]  = currenTestPair;
                                    testerToGame[socketMessageLayer] = currenTestPair;
                                }
                                await socketMessageLayer.Send(new LogRequest {
                                    Message = "Process created, id: " + process.Id.ToString()
                                });
                            }
                            break;
                        }

                    case (int)PlatformType.Android:
                        {
                            Process process = null;
                            try
                            {
                                process = Process.Start("cmd.exe", $"/C adb shell monkey -p {request.GameAssembly}.{request.GameAssembly} -c android.intent.category.LAUNCHER 1");
                            }
                            catch (Exception ex)
                            {
                                await socketMessageLayer.Send(new StatusMessageRequest {
                                    Error = true, Message = "Launch exception: " + ex.Message
                                });
                            }

                            if (process == null)
                            {
                                await socketMessageLayer.Send(new StatusMessageRequest {
                                    Error = true, Message = "Failed to start game process."
                                });
                            }
                            else
                            {
                                lock (loggerLock)
                                {
                                    currentTester = socketMessageLayer;
                                }

                                var currenTestPair = new TestPair
                                {
                                    TesterSocket  = socketMessageLayer,
                                    GameName      = request.GameAssembly,
                                    Process       = process,
                                    TestEndAction = () =>
                                    {
                                        // force stop - only works for Android 3.0 and above.
                                        Process.Start("cmd.exe", $"/C adb shell am force-stop {request.GameAssembly}.{request.GameAssembly}");
                                    }
                                };
                                lock (processes)
                                {
                                    processes[request.GameAssembly]  = currenTestPair;
                                    testerToGame[socketMessageLayer] = currenTestPair;
                                }
                                await socketMessageLayer.Send(new LogRequest {
                                    Message = "Process created, id: " + process.Id.ToString()
                                });
                            }
                            break;
                        }

                    case (int)PlatformType.iOS:
                        {
                            Process process = null;
                            var debugInfo   = "";
                            try
                            {
                                Thread.Sleep(5000);     //ios processes might be slow to close, we must make sure that we start clean
                                var start = new ProcessStartInfo
                                {
                                    FileName        = $"idevicedebug.exe",
                                    Arguments       = $"run com.your-company.{request.GameAssembly}",
                                    UseShellExecute = false
                                };
                                debugInfo = "Starting process " + start.FileName + " with path " + start.WorkingDirectory;
                                process   = Process.Start(start);
                            }
                            catch (Exception ex)
                            {
                                await socketMessageLayer.Send(new StatusMessageRequest {
                                    Error = true, Message = $"Launch exception: {ex.Message} info: {debugInfo}"
                                });
                            }

                            if (process == null)
                            {
                                await socketMessageLayer.Send(new StatusMessageRequest {
                                    Error = true, Message = "Failed to start game process. " + debugInfo
                                });
                            }
                            else
                            {
                                lock (loggerLock)
                                {
                                    currentTester = socketMessageLayer;
                                }

                                var currenTestPair = new TestPair {
                                    TesterSocket = socketMessageLayer, GameName = request.GameAssembly, Process = process
                                };
                                lock (processes)
                                {
                                    processes[request.GameAssembly]  = currenTestPair;
                                    testerToGame[socketMessageLayer] = currenTestPair;
                                }
                                await socketMessageLayer.Send(new LogRequest {
                                    Message = "Process created, id: " + process.Id.ToString()
                                });
                            }
                            break;
                        }
                    }
                }
                else //Game process
                {
                    TestPair pair;
                    lock (processes)
                    {
                        if (!processes.TryGetValue(request.GameAssembly, out pair))
                        {
                            return;
                        }

                        pair.GameSocket = socketMessageLayer;

                        testerToGame[pair.TesterSocket] = pair;
                        gameToTester[pair.GameSocket]   = pair;
                    }

                    await pair.TesterSocket.Send(new StatusMessageRequest {
                        Error = false, Message = "Start"
                    });

                    Console.WriteLine($"Starting test {request.GameAssembly}");
                }
            });

            socketMessageLayer.AddPacketHandler <KeySimulationRequest>(async request =>
            {
                TestPair game;
                lock (processes)
                {
                    game = testerToGame[socketMessageLayer];
                }
                await game.GameSocket.Send(request);
            });

            socketMessageLayer.AddPacketHandler <TapSimulationRequest>(async request =>
            {
                TestPair game;
                lock (processes)
                {
                    game = testerToGame[socketMessageLayer];
                }
                await game.GameSocket.Send(request);
            });

            socketMessageLayer.AddPacketHandler <ScreenshotRequest>(async request =>
            {
                TestPair game;
                lock (processes)
                {
                    game = testerToGame[socketMessageLayer];
                }
                await game.GameSocket.Send(request);
            });

            socketMessageLayer.AddPacketHandler <TestEndedRequest>(async request =>
            {
                TestPair game;
                lock (processes)
                {
                    game = testerToGame[socketMessageLayer];
                }
                await game.GameSocket.Send(request);

                lock (processes)
                {
                    testerToGame.Remove(socketMessageLayer);
                    gameToTester.Remove(game.GameSocket);
                    processes.Remove(game.GameName);
                }

                socketMessageLayer.Context.Dispose();
                game.GameSocket.Context.Dispose();

                game.Process.Kill();
                game.Process.Dispose();

                lock (loggerLock)
                {
                    currentTester = null;
                }

                game.TestEndAction?.Invoke();

                Console.WriteLine($"Finished test {game.GameName}");
            });

            socketMessageLayer.AddPacketHandler <TestAbortedRequest>(request =>
            {
                TestPair game;
                lock (processes)
                {
                    game = testerToGame[socketMessageLayer];
                    testerToGame.Remove(socketMessageLayer);
                    processes.Remove(game.GameName);
                }

                socketMessageLayer.Context.Dispose();

                game.Process.Kill();
                game.Process.Dispose();

                lock (loggerLock)
                {
                    currentTester = null;
                }

                game.TestEndAction?.Invoke();

                Console.WriteLine($"Aborted test {game.GameName}");
            });

            socketMessageLayer.AddPacketHandler <ScreenShotPayload>(async request =>
            {
                TestPair tester;
                lock (processes)
                {
                    tester = gameToTester[socketMessageLayer];
                }

                var imageData = new TestResultImage();
                var stream    = new MemoryStream(request.Data);
                imageData.Read(new BinaryReader(stream));
                stream.Dispose();
                // Ensure directory exists
                Directory.CreateDirectory(Path.GetDirectoryName(request.FileName));
                var resultFileStream = File.OpenWrite(request.FileName);
                imageData.Image.Save(resultFileStream, ImageFileType.Png);
                resultFileStream.Dispose();

                await tester.TesterSocket.Send(new ScreenshotStored());
            });

            Task.Run(async() =>
            {
                try
                {
                    await socketMessageLayer.MessageLoop();
                }
                catch
                {
                }
            });
        }
Esempio n. 27
0
 int GetMatchingOffset(TestPair pair)
 {
     return(GetDistinctViewOffset(pair.Probe.View, pair.Candidate.View));
 }