Exemplo n.º 1
0
        public void GetAll_ValidScenario_ListOfAppiumProcesses()
        {
            var restClientMock       = new Mock <IRestClient>();
            var appiumRepositoryMock = new Mock <IRepository <AppiumProcess> >();
            var appiumController     = new AppiumController(restClientMock.Object, appiumRepositoryMock.Object, Logger);

            var appiumProcess1 = new AppiumProcess("123", "1111", "1112", 1, "1113", "1114");
            var appiumProcess2 = new AppiumProcess("123", "1111", "1112", 1, "1113", "1114");

            var appiumProcesses = new List <AppiumProcess>
            {
                appiumProcess1,
                appiumProcess2
            };

            appiumRepositoryMock.Setup(a => a.GetAll()).Returns(appiumProcesses);

            var result = appiumController.GetAll();

            var viewResult = Assert.IsType <List <AppiumProcess> >(result);

            Assert.Equal(2, result.Count());
            Assert.Contains(appiumProcess1, viewResult);
            Assert.Contains(appiumProcess2, viewResult);
        }
Exemplo n.º 2
0
        public IActionResult Create([FromBody] AppiumProcess appiumProcess)
        {
            LogRequestToDebug();

            if (!ValidateAppiumProcess(appiumProcess, out var badRequest))
            {
                return(badRequest);
            }

            if (_appiumRepository.Find(appiumProcess.DeviceId) != null)
            {
                // 409 = Conflict
                return(StatusCodeExtension(409,
                                           $"Appium is already running for {nameof(AppiumProcess.DeviceId)} [{appiumProcess.DeviceId}]."));
            }

            try
            {
                _appiumRepository.Add(appiumProcess);
            }
            catch (Exception ex)
            {
                return(StatusCodeExtension(500, "Failed to Add AppiumProcess in database. " + ex.Message));
            }

            _logger.Debug(string.Format("Created new appiumProcess: [{0}]",
                                        JsonConvert.SerializeObject(appiumProcess)));

            return(CreatedAtRoute("getAppiumProcess", new { id = appiumProcess.DeviceId }, appiumProcess));
        }
Exemplo n.º 3
0
        public void Create_InvalidDataInRequest_BadRequest(string deviceId, string appiumPort,
                                                           string appiumBootstrapPort, int appiumPid,
                                                           string webkitDebugProxyPort, string wdaLocalPort)
        {
            var restClientMock       = new Mock <IRestClient>();
            var appiumRepositoryMock = new Mock <IRepository <AppiumProcess> >();
            var appiumController     = new AppiumController(restClientMock.Object, appiumRepositoryMock.Object, Logger);

            var appiumProcess = new AppiumProcess(deviceId, appiumPort, appiumBootstrapPort, appiumPid,
                                                  webkitDebugProxyPort, wdaLocalPort);

            var result = appiumController.Create(appiumProcess);

            Assert.IsType <BadRequestObjectResult>(result);
        }
Exemplo n.º 4
0
        public void GetById_AppiumProcessNotInDatabase_NotFound()
        {
            var restClientMock       = new Mock <IRestClient>();
            var appiumRepositoryMock = new Mock <IRepository <AppiumProcess> >();

            var appiumProcess = new AppiumProcess("123", "1111", "1112", 1, "1113", "1114");

            appiumRepositoryMock.Setup(a => a.Find(It.IsAny <string>())).Returns((AppiumProcess)null);

            var appiumController = new AppiumController(restClientMock.Object, appiumRepositoryMock.Object, Logger);

            var result = appiumController.GetById("123");

            Assert.IsType <NotFoundObjectResult>(result);
        }
Exemplo n.º 5
0
        public void Delete_ValidScenario_Ok()
        {
            var restClientMock       = new Mock <IRestClient>();
            var appiumRepositoryMock = new Mock <IRepository <AppiumProcess> >();

            var appiumProcess = new AppiumProcess("123", "1111", "1112", 1, "1113", "1114");

            appiumRepositoryMock.Setup(a => a.Find(It.IsAny <string>())).Returns(appiumProcess);

            var appiumController = new AppiumController(restClientMock.Object, appiumRepositoryMock.Object, Logger);

            var result = appiumController.Delete("123");

            Assert.IsType <OkResult>(result);
        }
Exemplo n.º 6
0
        public void Create_AlreadyRunningAppiumForDeviceId_ErrorStatusCode()
        {
            var restClientMock       = new Mock <IRestClient>();
            var appiumRepositoryMock = new Mock <IRepository <AppiumProcess> >();

            appiumRepositoryMock.Setup(a => a.Find(It.IsAny <string>())).Returns(new AppiumProcess());

            var appiumController = new AppiumController(restClientMock.Object, appiumRepositoryMock.Object, Logger);

            var appiumProcess = new AppiumProcess("123", "1111", "1112", 1, "1113", "1114");
            var result        = appiumController.Create(appiumProcess);

            var viewResult = Assert.IsType <ObjectResult>(result);

            Assert.Equal(409, viewResult.StatusCode);
        }
Exemplo n.º 7
0
        public void Create_ValidScenario_CreatedAtRoute()
        {
            var restClientMock       = new Mock <IRestClient>();
            var appiumRepositoryMock = new Mock <IRepository <AppiumProcess> >();

            appiumRepositoryMock.Setup(a => a.Find(It.IsAny <string>())).Returns((AppiumProcess)null);

            var appiumController = new AppiumController(restClientMock.Object, appiumRepositoryMock.Object, Logger);

            var appiumProcess = new AppiumProcess("123", "1111", "1112", 1, "1113", "1114");
            var result        = appiumController.Create(appiumProcess);

            var viewResult = Assert.IsType <CreatedAtRouteResult>(result);

            Assert.Equal(appiumProcess, viewResult.Value);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Gets the appium process.
        /// </summary>
        /// <returns>The appium process.</returns>
        /// <param name="id">Identifier.</param>
        private async Task <AppiumProcess> GetAppiumProcess(string id)
        {
            AppiumProcess appiumProcess = null;

            _logger.Debug("GetDevice: " + _client.BaseAddress + "api/v1/appium/" + id);
            var response = await _client.GetAsync("api/v1/appium/" + id);

            if (response.IsSuccessStatusCode)
            {
                var stream = await response.Content.ReadAsStringAsync();

                appiumProcess = JsonConvert.DeserializeObject <AppiumProcess>(stream);
            }

            return(appiumProcess);
        }
Exemplo n.º 9
0
        public void Create_AddThrowsAnException_ErrorStatusCode()
        {
            var restClientMock       = new Mock <IRestClient>();
            var appiumRepositoryMock = new Mock <IRepository <AppiumProcess> >();

            appiumRepositoryMock.Setup(a => a.Find(It.IsAny <string>())).Returns((AppiumProcess)null);
            appiumRepositoryMock.Setup(a => a.Add(It.IsAny <AppiumProcess>())).Throws(new Exception());

            var appiumController = new AppiumController(restClientMock.Object, appiumRepositoryMock.Object, Logger);

            var appiumProcess = new AppiumProcess("123", "1111", "1112", 1, "1113", "1114");
            var result        = appiumController.Create(appiumProcess);

            var viewResult = Assert.IsType <ObjectResult>(result);

            Assert.Equal(500, viewResult.StatusCode);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Adds the appium process.
        /// </summary>
        /// <returns>The appium process.</returns>
        /// <param name="appiumProcess">Appium process.</param>
        public async Task <AppiumProcess> AddAppiumProcess(AppiumProcess appiumProcess)
        {
            _logger.Info("AddAppiumProcess Thread started");
            var serializedAppiumProcess = JsonConvert.SerializeObject(appiumProcess);

            _logger.Debug(serializedAppiumProcess);
            var httpContent = new StringContent(serializedAppiumProcess, Encoding.UTF8, "application/json");

            _logger.Debug("AddAppiumProcess: " + _client.BaseAddress + "api/v1/appium");
            var response = await _client.PostAsync("api/v1/appium", httpContent);

            if (!response.IsSuccessStatusCode)
            {
                throw new HttpRequestException(response.StatusCode.ToString());
            }

            return(await GetAppiumProcess(appiumProcess.DeviceId));
        }
Exemplo n.º 11
0
        /// <inheritdoc />
        /// <summary>
        /// Starts the appium for device identifier.
        /// </summary>
        /// <returns>The appium for device identifier.</returns>
        /// <param name="deviceId">Device identifier.</param>
        public async Task <string> StartAppiumForDeviceId(string deviceId)
        {
            _logger.Info($"{nameof(StartAppiumForDeviceId)} {deviceId} Thread Started.");
            var configuration = await _restClient.GetManagerConfiguration();

            var device = await _restClient.GetDevice(deviceId);

            _logger.Debug($"{nameof(StartAppiumForDeviceId)} - device: {JsonConvert.SerializeObject(device)}");

            var appiumIpAddress        = configuration.LocalIpAddress;
            var currentAppiumProcesses = await _restClient.GetAppiumProcesses();

            _logger.Debug(
                $"{nameof(StartAppiumForDeviceId)} - currentAppiumProcesses: {JsonConvert.SerializeObject(currentAppiumProcesses)}");

            var usedAppiumPorts = new List <string>();

            foreach (var process in currentAppiumProcesses)
            {
                usedAppiumPorts.Add(process.AppiumPort);
                usedAppiumPorts.Add(process.AppiumBootstrapPort);
                usedAppiumPorts.Add(process.WebkitDebugProxyPort);
                usedAppiumPorts.Add(process.WdaLocalPort);
            }

            _logger.Debug(
                $"{nameof(StartAppiumForDeviceId)} - usedAppiumPorts: {JsonConvert.SerializeObject(usedAppiumPorts)}");

            var appiumPort = GetFreePortAsyncMac(configuration, usedAppiumPorts);

            usedAppiumPorts.Add(appiumPort);
            _logger.Debug(
                $"{nameof(StartAppiumForDeviceId)} - new appiumPort: {JsonConvert.SerializeObject(appiumPort)}");

            var appiumBootstrapPort = GetFreePortAsyncMac(configuration, usedAppiumPorts);

            usedAppiumPorts.Add(appiumBootstrapPort);
            _logger.Debug(
                $"{nameof(StartAppiumForDeviceId)} - new appiumBootstrapPort: {JsonConvert.SerializeObject(appiumBootstrapPort)}");

            var appiumLogFilePath = _appiumLogFolderPath;

            if (!appiumLogFilePath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
            {
                appiumLogFilePath += Path.DirectorySeparatorChar;
            }

            appiumLogFilePath = appiumLogFilePath + deviceId + ".log";
            _logger.Debug(
                $"{nameof(StartAppiumForDeviceId)} - appiumLogFilePath: {JsonConvert.SerializeObject(appiumLogFilePath)}");

            var webkitDebugProxyPort = GetFreePortAsyncMac(configuration, usedAppiumPorts);

            usedAppiumPorts.Add(webkitDebugProxyPort);

            var wdaLocalPort = GetFreePortAsyncMac(configuration, usedAppiumPorts);

            usedAppiumPorts.Add(wdaLocalPort);

            /*
             * String defaultCapabilities = "\\\"automation-name\\\" : \\\"XCUITest\\\"," +
             *  " \\\"teamId\\\" : \\\"CB52FCDD4H\\\"," +
             *  " \\\"signingId\\\" : \\\"iPhone Developer\\\"," +
             *  " \\\"showXcodeLog\\\" : \\\"true\\\"," +
             *  " \\\"realDeviceLogger\\\" : \\\"/usr/local/lib/node_modules/deviceconsole/deviceconsole\\\"," +
             *  " \\\"bootstrapPath\\\" : \\\"/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent\\\"," +
             *  " \\\"agentPath\\\" : \\\"/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/WebDriverAgent.xcodeproj\\\"," +
             *  " \\\"startIWDP\\\" : \\\"true\\\"," +
             *  " \\\"sessionTimeout\\\" : \\\"6000\\\"";
             */
            var appiumArguments = "" +
                                  " --session-override" +
                                  " --suppress-adb-kill-server" +
                                  " --log " + appiumLogFilePath +
                                  " --udid " + deviceId +
                                  " --address " + appiumIpAddress +
                                  " --port " + appiumPort +
                                  " --bootstrap-port " + appiumBootstrapPort +
                                  " --webkit-debug-proxy-port " + webkitDebugProxyPort +
                                  " --webdriveragent-port " + wdaLocalPort;

            /*
             * if (device.Type == Devices.Enums.DeviceType.iOS)
             * {
             *  appiumArguments += " --default-capabilities \\\'{"+defaultCapabilities+"}\\\'";
             * }
             */

            _logger.Debug(
                $"{nameof(StartAppiumForDeviceId)} - starting appium with args: {JsonConvert.SerializeObject(appiumArguments)}");

            var appiumPid = _externalProcesses.RunProcessInBackground("appium", appiumArguments);

            _logger.Debug(
                $"{nameof(StartAppiumForDeviceId)} - appium started in terminal with pid: {JsonConvert.SerializeObject(appiumPid)}");

            Thread.Sleep(3000);
            var psOutput = _externalProcesses.RunProcessAndReadOutput("ps", "ax");

            var runningAppiumProcess = psOutput.Split('\n').Where(x => x.Contains("bin/appium") && x.Contains(deviceId))
                                       .ToList();

            _logger.Debug(
                $"{nameof(StartAppiumForDeviceId)} - runningAppiumProcess {JsonConvert.SerializeObject(runningAppiumProcess)} for device {device}.");

            var processId = "";

            if (runningAppiumProcess.Count() != 1)
            {
                _logger.Error(
                    $"{nameof(StartAppiumForDeviceId)}: Multiple appium processes running with deviceId={deviceId}. Killing them all...");
                _externalProcesses.StopProcessRunningInBackground(deviceId);
            }
            else
            {
                processId = runningAppiumProcess.First().Trim().Split()[0];
                _logger.Debug(
                    $"{nameof(StartAppiumForDeviceId)} - runningAppiumProcess with pid: {JsonConvert.SerializeObject(processId)}.");
            }

            if (string.IsNullOrEmpty(processId) &&
                !_externalProcesses.IsProcessInBackgroundRunning(Convert.ToInt32(processId)))
            {
                throw new Exception($"{nameof(StartAppiumForDeviceId)}: Appium process failed to start successfully.");
            }

            appiumPid = Convert.ToInt32(processId);

            var appiumProcess = new AppiumProcess(deviceId, appiumPort, appiumBootstrapPort, appiumPid,
                                                  webkitDebugProxyPort, wdaLocalPort);

            _logger.Debug(
                $"{nameof(StartAppiumForDeviceId)} - adding appiumProcess: {JsonConvert.SerializeObject(appiumProcess)}.");

            var result = Task.Run(async() => await _restClient.AddAppiumProcess(appiumProcess)).Result;

            _logger.Debug(
                $"{nameof(StartAppiumForDeviceId)} - finished adding appiumProcess: with result [{result}].");

            if (device.Type == DeviceType.IOS)
            {
                _logger.Debug($"{nameof(StartAppiumForDeviceId)} - starting iosWebkit for ios device {device}.");

                var iosWebkitPid = StartIosWebkitDebugProxy(deviceId, webkitDebugProxyPort);
                if (!_externalProcesses.IsProcessInBackgroundRunning(iosWebkitPid))
                {
                    _logger.Error(
                        $"{nameof(StartAppiumForDeviceId)} - ios_webkit_debug_proxy process failed to start successfully.");

                    throw new Exception(
                              $"{nameof(StartAppiumForDeviceId)}: ios_webkit_debug_proxy process failed to start successfully.");
                }

                _logger.Debug($"{nameof(StartAppiumForDeviceId)} - starting IdeviceSyslog for ios device {device}.");

                StartIdeviceSyslog(deviceId);
            }

            _logger.Info($"{nameof(StartAppiumForDeviceId)} appiumEndpoint: {appiumIpAddress}:{appiumPort}");
            var appiumEndpoint = new Uri($"http://{appiumIpAddress}:{appiumPort}/wd/hub");

            return(appiumEndpoint.ToString());
        }