Exemplo n.º 1
0
 public void ReqeustFileContentWithHttpMethodTest(HttpMethod httpMethod, System.Net.HttpStatusCode expectedStatusCode)
 {
     PerformTestWithPreparedData((id) =>
     {
         var connection = PrivateApiConnection.GetConnectionForCurrentTest();
         using (LogHelper.LoggerForCurrentTest.EnterReproStep($"Request a file with {httpMethod.ToString()} HTTP method"))
         {
             var result = connection.SendAsPostAsync(FileStorageManager.EndPoint, new Dictionary <string, string> {
                 ["id"] = id
             }, httpMethod.ToNetHttpMethod()).Result;
             PrAssert.That(result.StatusCode, PrIs.EqualTo(expectedStatusCode));
         }
     });
 }
Exemplo n.º 2
0
        public static void TestsSetup()
        {
            if (ImageFileIds == null)
            {
                ImageFileIds = UploadImageFiles();
            }
            AttachmentFileIds = new Dictionary <ResourceId, Dictionary <FileType, int> >();

            var connection = PrivateApiConnection.GetConnectionForCurrentTest();

            var fileManager   = new LegacyFileManager(connection);
            var fieldManager  = new FieldManager(connection);
            var recordManager = new RecordManager(connection);

            foreach (var resource in Enum.GetValues(typeof(ResourceId)).Cast <ResourceId>().Except(new[] { ResourceId.None }))
            {
                AttachmentFileIds.Add(resource, new Dictionary <FileType, int>());
                var recordId = RecordsCreator.Data[$"{resource}"].Id;

                var requiredFields = ResourceMandatoryFields[resource](false).Keys.Concat(SearchConstants.SystemFieldsValues[resource].Values);
                var fieldIs        = fieldManager.GetFieldGuid(requiredFields, new[] { (TestCoreFramework.Enums.ResourceType)((int)resource) }).Result.Result.ToDictionary(x => x.Alias, x => UuidUtil.GetId(x.Id));
                var record         = recordManager.ReadRecords(new RecordsHandlingComponent.DataContract.RecordsGetRequestItem
                {
                    Fields   = string.Join(",", requiredFields.Select(x => resource + "." + x)),
                    Resource = (TestCoreFramework.Enums.ResourceType)((int)resource),
                    IdList   = new List <int> {
                        Convert.ToInt32(recordId)
                    }
                }).Result.Items.Single();

                var files = ImageFileIds[resource].ToDictionary(x => FieldCreator.Data[$"{resource}_File_{x.Key}"].Id, x => x.Value);

                fileManager.AssociateFilesAndRecord(resource, Convert.ToInt32(recordId), fieldIs.ToDictionary(x => x.Value, x => (object)GetStringRepresentation(record[$"{resource}.{x.Key}"])), files.ToArray());

                //apparently, Contract has no sublist to upload attachment to
                if (resource != ResourceId.Contract)
                {
                    foreach (var fileType in FileTypesToTest)
                    {
                        var fileInfo = CommonConstants.Files[fileType];
                        var fileName = fileInfo.Location.Split('/').Last().Replace("file", "attachment_file");
                        fileName = OverrideExtensionFileTypes.Contains(fileType)
                            ? fileName.Replace("." + fileInfo.Extension, ".txt")
                            : fileName;

                        AttachmentFileIds[resource][fileType] = fileManager.UploadFileAsAttachment(fileInfo.Location, ((int)resource).ToString(), recordId.ToString(), fileName);
                    }
                }
            }
        }
Exemplo n.º 3
0
        public void InvalidMethodCreatePartitionTests(HttpMethod method)
        {
            var request = new Dictionary <string, string>()
            {
                ["companyLoginId"] = "TestCompany"
            };
            var connection = PrivateApiConnection.GetConnectionForCurrentTest();

            connection.SuppressAuthentication = true;
            var defaultManager = new DefaultManager(connection);
            var result         = defaultManager.Send <object>(PartitionTestCases.EndpointMapper[HttpMethod.POST], request, method);

            PrAssert.That(result, PrIs.ErrorResponse().And.HttpCode(System.Net.HttpStatusCode.NotFound), $"Still create partition with {method} method.");
        }
Exemplo n.º 4
0
        public void ValidReturnJsonContentTypeTest(HttpMethod method)
        {
            System.Net.Http.HttpResponseMessage response;
            var connection = PrivateApiConnection.GetConnectionForCurrentTest();
            var request    = new Dictionary <string, string>
            {
                ["id"] = method == HttpMethod.POST
                ? DataTest.Data[ReportCreateStep.CreateSpec].ToString()
                : DataTest.Data[ReportCreateStep.CreateTable].ToString()
            };

            response = connection.SendAsync(EndPoint, request, method.ToNetHttpMethod()).Result;
            PrAssert.That(response.Content.Headers.ContentType.MediaType, PrIs.EqualTo("application/json"));
        }
Exemplo n.º 5
0
        private static Dictionary <ResourceId, Dictionary <FileType, int> > UploadImageFiles()
        {
            var connection = PrivateApiConnection.GetConnectionForCurrentTest();
            var manager    = new LegacyFileManager(connection);

            return(Enum.GetValues(typeof(ResourceId)).Cast <ResourceId>().Except(new[] { ResourceId.None }).ToDictionary(resource => resource,
                                                                                                                         resource => ImageFileTypes.ToDictionary(fileType => fileType,
                                                                                                                                                                 fileType =>
            {
                var fileInfo = CommonConstants.Files[fileType];
                var fieldId = FieldCreator.Data[$"{resource}_File_{fileType}"].Id;
                var fileName = fileInfo.Location.Split('/').Last().Replace("file", "image_file");
                return manager.UploadFile(fileInfo.Location, fieldId.ToString(), fileName);
            })));
        }
Exemplo n.º 6
0
 public void VerifyResponseContentTypeGetPhaseFlowTest()
 {
     System.Net.Http.HttpResponseMessage response;
     using (var step = LogHelper.LoggerForCurrentTest.EnterReproStep($"Phase Flow api"))
     {
         var con     = PrivateApiConnection.GetConnectionForCurrentTest();
         var request = new Dictionary <string, string>()
         {
             ["resourceId"] = $"{(int)ResourceId.Client}",
         };
         response = con.SendAsync(PhaseFlowTestData.PhaseFlowApi, request, HttpMethod.GET.ToNetHttpMethod()).Result;
     }
     PrAssert.That(response.IsSuccessStatusCode, "Can not request successfull");
     PrAssert.That(response.Content.Headers.ContentType.MediaType, PrIs.EqualTo("application/json"), "The content type is not as expected");
 }
Exemplo n.º 7
0
 public void VerifyResponseContentTypeTest()
 {
     System.Net.Http.HttpResponseMessage response;
     using (var step = LogHelper.LoggerForCurrentTest.EnterReproStep($"Option Flow api"))
     {
         var con     = PrivateApiConnection.GetConnectionForCurrentTest();
         var request = new Dictionary <string, string>()
         {
             ["id"] = OptionFlowTestData.ValidOptionIdMapper[OptionFlowTestData.ValidInput.LevelOne].Single().ToString()
         };
         response = con.SendAsync(OptionFlowTestData.OptionFlowApi, request, HttpMethod.GET.ToNetHttpMethod()).Result;
     }
     PrAssert.That(response.IsSuccessStatusCode, "Can not request successfull");
     PrAssert.That(response.Content.Headers.ContentType.MediaType, PrIs.EqualTo("application/json"), "The content type is not as expected");
 }
Exemplo n.º 8
0
 public void VerifyResponseContentTypeDeletePhaseFlowTest()
 {
     System.Net.Http.HttpResponseMessage response;
     using (var step = LogHelper.LoggerForCurrentTest.EnterReproStep($"Phase Flow api"))
     {
         var con     = PrivateApiConnection.GetConnectionForCurrentTest();
         var request = new Dictionary <string, object>()
         {
             ["id"]        = PhaseFlowTestData.ValidPhaseIdMapper[ResourceId.Client][PhaseFlowTestData.ValidPhaseId.PhaseId],
             ["recursive"] = true
         };
         response = con.SendAsync(PhaseFlowTestData.PhaseFlowApi, request.ToJson(), HttpMethod.DELETE.ToNetHttpMethod()).Result;
     }
     PrAssert.That(response.IsSuccessStatusCode, "Can not request successfull");
     PrAssert.That(response.Content.Headers.ContentType.MediaType, PrIs.EqualTo("application/json"), "The content type is not as expected");
 }
Exemplo n.º 9
0
 public static PrivateData <PrivateApiConnection> GetOtherConnection()
 {
     return(new PrivateData <PrivateApiConnection>(
                (session, test) =>
     {
         return Task.Run(() =>
         {
             var userInfo = AuthenticationInfoProvider.Current.Manager.GetAllAvailableUsers(new UserSpecBuilder().Admin(false)).First();
             var connection = new PrivateApiConnection();
             connection.Authenticate(userInfo.Company.Name, userInfo.Login, userInfo.Password);
             return connection;
         });
     },
                (session, test, res) => Task.Run(() =>
     {
     })));
 }
Exemplo n.º 10
0
        private void PerformTestWithoutAuthorisationWithDataPreparation(bool doDeauth, Func <PrivateApiConnection, string, object> responseProvider)
        {
            var manager = new FileStorageManager();
            var result  = manager.Upload(GenerateUploadFileRequest());

            PrAssume.That(result, PrIs.SuccessfulResponse());
            PrivateApiConnection.GetConnectionForCurrentTest().DeAuthenticate();
            try
            {
                PerformTestWithoutAuthorisation(doDeauth, responseProvider, result.Result.Id);
            }
            finally
            {
                PrivateApiConnection.GetConnectionForCurrentTest().Authenticate();
                manager.Delete(result.Result.Id);
            }
        }
 public void VerifyResponseContentTypeDeletePhaseEntryTest()
 {
     System.Net.Http.HttpResponseMessage response;
     using (var step = LogHelper.LoggerForCurrentTest.EnterReproStep($"Menu api"))
     {
         var con        = PrivateApiConnection.GetConnectionForCurrentTest();
         var deleteItem = GetDeleteItem();
         var request    = new Dictionary <string, object>()
         {
             [ParamDelete] = deleteItem
         };
         var requestJson = request.ToJson();
         response = con.SendAsync(PhaseEntryTestData.PhaseEntryApi, requestJson, HttpMethod.DELETE.ToNetHttpMethod()).Result;
     }
     PrAssert.That(response.IsSuccessStatusCode, "Can not request successfull");
     PrAssert.That(response.Content.Headers.ContentType.MediaType, PrIs.EqualTo("application/json"), "The content type is not as expected");
 }
Exemplo n.º 12
0
        private void PerformTestWithoutAuthorisation(bool doDeauth, Func <PrivateApiConnection, string, object> responseProvider, string recordId = null)
        {
            var connection = new PrivateApiConnection();

            if (doDeauth)
            {
                connection.Authenticate();
                connection.DeAuthenticate();
            }
            else
            {
                connection = new PrivateApiConnection();
                connection.SuppressAuthentication = true;
            }
            var response = responseProvider(connection, recordId);

            PrAssert.That(response, PrIs.ErrorResponse().And.HttpCode(401));
        }
Exemplo n.º 13
0
        public void TestValidPostComputationFieldValueReturnJsonContentType()
        {
            var connection  = PrivateApiConnection.GetConnectionForCurrentTest();
            var targetField = GetTargetField(ResourceId.Resume, FieldsCreator, TargetFieldsNumeric[2]);
            var request     = GenerateComputeFieldValueRequest(ResourceId.Resume, targetField,
                                                               new Dictionary <string, object>
            {
                [$"{ResourceId.Resume}.{TargetFieldsNumeric[0]}"] = 10,
                [$"{ResourceId.Resume}.{TargetFieldsNumeric[1]}"] = 20
            });
            var effectedTerminalField = ReadField(ResourceId.Resume, targetField);
            var expression            = GenerateExpression(ResourceId.Resume, Operations.Add, TargetFieldsNumeric[0], TargetFieldsNumeric[1]);

            UpdateExpressionField(ResourceId.Resume, effectedTerminalField.ToString(), expression);
            var response = connection.SendAsync(ComputeFieldValueEndPoint, JsonConvert.SerializeObject(request), System.Net.Http.HttpMethod.Post).Result;

            PrAssert.That(response.Content.Headers.ContentType.MediaType, PrIs.EqualTo("application/json"));
        }
Exemplo n.º 14
0
        public void GetRequestTest()
        {
            var connection = PrivateApiConnection.GetConnectionForCurrentTest();

            using (LogHelper.LoggerForCurrentTest.EnterReproStep("Sending GET request to the service menu endpoint"))
                using (var response = connection.SendAsync("privateapi/hrbc/service-menu", System.Net.Http.HttpMethod.Get).Result)
                {
                    PrAssert.That(response.IsSuccessStatusCode, "The server did not respond with 200 HTTP status code");

                    var responseBody = response.Content.ReadAsStringAsync().Result;

                    var itemType     = new { labelKey = "", descriptionKey = "", actionType = 0, targetUrl = "" };
                    var responseType = new { items = new [] { itemType } };

                    var results = JsonConvert.DeserializeAnonymousType(responseBody, responseType);

                    PrAssert.That(results?.items, Is.Not.Null);
                }
        }
Exemplo n.º 15
0
        public static void TestsTeardown()
        {
            var connection = PrivateApiConnection.GetConnectionForCurrentTest();
            var manager    = new LegacyFileManager(connection);

            if (ImageFileIds == null)
            {
                foreach (var id in ImageFileIds.SelectMany(x => x.Value.Values))
                {
                    manager.DeleteFile(id);
                }
            }
            if (AttachmentFileIds != null)
            {
                foreach (var id in AttachmentFileIds.SelectMany(x => x.Value.Values))
                {
                    manager.DeleteFile(id);
                }
            }
        }
Exemplo n.º 16
0
        public void TestVerifyResetUserPasswordAfterExpiredTime()
        {
            var parameterRequest     = new Dictionary <string, object>(Common.ResetUserPasswordParameters);
            var resetUserPassHandler = new ResetUserPasswordManager();
            var response             = resetUserPassHandler.ResetUserPassword(parameterRequest, System.Net.Http.HttpMethod.Post);

            LastPassword = Common.GetResetUserPassword(response);

            //Verify
            Thread.Sleep(60000 * 2); //sleep in 2 mins

            var connection = new PrivateApiConnection();

            connection.Authenticate(
                TestContext.CurrentContext.Test.Properties.Get("companyName").ToString(),
                TestContext.CurrentContext.Test.Properties.Get("adminUserLogin").ToString(),
                TestContext.CurrentContext.Test.Properties.Get("adminUserPassword").ToString());

            PrAssert.That(connection.IsAuthenticated, PrIs.True);
        }
Exemplo n.º 17
0
        public void LoginNormalUserAndSendRequestWithHeaderContainsAdminUserIdTest()
        {
            var creds             = AuthenticationInfoProvider.GetAuthSpecForCurrentTest();
            var adminUserPassword = creds.Companies.First().Value.Users.First().Password;
            var adminUserLogin    = creds.Companies.First().Value.Users.First().Login;
            var adminUserId       = creds.Companies.First().Value.Users.First().Metadata["userId"].ToString();
            var companyId         = creds.Companies.First().Value.Id;
            var companyName       = creds.Companies.First().Value.Name;

            creds.Dispose();

            var headerValue = GetFormatIdentityHeader(companyId, adminUserId, DefaultService);

            //Login by normal user
            Connection = new PrivateApiConnection(TestConfig.GetValueFromConfig("InternalServerURL"));
            Connection.Authenticate(companyName, NormalUserLogin, NormalUserPassword);

            var internalHandler = new InternalApiManager(Connection);
            var response        = internalHandler.SendRequestWithIdentityHeader(InternalAuthRequest, "X-IDENTITY", headerValue, HttpMethod.Post);

            PrAssert.That(response, PrIs.ErrorResponse().And.HttpCode(System.Net.HttpStatusCode.Unauthorized));
        }
Exemplo n.º 18
0
 public OriginalSearchManager(PrivateApiConnection connection) : base(connection)
 {
 }
Exemplo n.º 19
0
 public DashboardSettingManager(PrivateApiConnection connection) : base(connection)
 {
 }
Exemplo n.º 20
0
 public LoginManager(PrivateApiConnection connection) : base(connection)
 {
 }
Exemplo n.º 21
0
 public FileStorageManager(PrivateApiConnection connection) : base(connection)
 {
 }
Exemplo n.º 22
0
        public PrivateApiResponse <List <OptionWriteResponse> > WriteOptionAccessEndpoint(int id, Dictionary <string, object> fields, PrivateApiConnection connect)
        {
            var request = new List <Dictionary <string, object> >
            {
                new Dictionary <string, object>(fields)
                {
                    ["id"] = id,
                }
            };

            var requestString = ConvertToJsonString(request);

            using (var step = LogHelper.LoggerForCurrentTest.EnterReproStep($"Writing option"))
            {
                return(ProcessResponseWithContent <List <OptionWriteResponse> >(connect.SendAsync(OptionUpdateEndpoint, requestString, HttpMethod.Post).Result));
            }
        }
Exemplo n.º 23
0
 public HrbcSublistManager(PrivateApiConnection connection) : base(connection)
 {
 }
Exemplo n.º 24
0
 public UserManager(PrivateApiConnection connection) : base(connection)
 {
 }
Exemplo n.º 25
0
 private void Login(PrivateApiConnection connection, string company, string login, string password)
 {
     connection.DeAuthenticate();
     connection.Authenticate(company, login, password);
 }
Exemplo n.º 26
0
 public LegacyFileManager(PrivateApiConnection connection) : base(connection)
 {
 }
Exemplo n.º 27
0
 public FileUploadManager(PrivateApiConnection connection) : base(connection)
 {
 }
Exemplo n.º 28
0
        public void UpdateFieldsTest()
        {
            const string FieldPropertyToModify = "d.label.ja";
            var          resource = ResourceId.Client;
            var          aliases  = new[] { "P_Country", "P_City", "P_Prefecture" };
            var          resetProgrammingCacheField = "P_Memo";
            var          connection     = PrivateApiConnection.GetConnectionForCurrentTest();
            var          fieldHandler   = new FieldManager();
            var          optionHandler  = new OptionManager();
            var          aclHandler     = new AclManager();
            var          recordsHandler = new RecordManager();
            //PHASE1: preparing test data: reading and updating fields/options/acls/records
            var rawFields = fieldHandler.GetFieldGuid(new[] { "P_Country", "P_Phase", "P_PhaseDate" }, new[] { Porters.TestCoreFramework.Enums.ResourceType.Client })
                            .Result.Result;
            var fields     = rawFields.ToDictionary(x => $"{char.ToUpper(x.Resource[0]) + x.Resource.Substring(1)}.{x.Alias}", x => (int)UuidUtil.GetId(x.Id));
            var guidFields = rawFields.ToDictionary(x => $"{char.ToUpper(x.Resource[0]) + x.Resource.Substring(1)}.{x.Alias}", x => x.Id);

            //fields
            fieldHandler.UpdateField(resetProgrammingCacheField, ResourceId.Client, new Dictionary <string, object> {
                ["d.label.ja"] = "MEMO"
            });

            var originalFieldValues = aliases.ToDictionary(x => x, x => fieldHandler.GetFieldDetails($"{resource}.{x}").Result.Values.Single().Value);

            foreach (var alias in aliases)
            {
                fieldHandler.UpdateField(alias, ResourceId.Client, new Dictionary <string, object> {
                    [FieldPropertyToModify] = $"UPDATE_{alias.ToUpper()}_1"
                });
            }

            //options
            var data = optionHandler.SearchOption("Option.P_LanguageAbility");
            var originalOptionValues = data.Result.Single().Children;

            foreach (var child in data.Result.Single().Children)
            {
                optionHandler.UpdateOption(child.Id, new Dictionary <string, object> {
                    ["name"] = child.Alias
                });
            }

            //acl
            var aclInfo         = aclHandler.ReadAclInfo(guidFields["Client.P_Country"]);
            var originalAclInfo = aclInfo.Result[guidFields["Client.P_Country"]].Last().Value.Phases.ToDictionary(x => x.Key, x => new AclHandlingComponent.DataContract.AclResponseItem.PermissionItem {
                Permission = x.Value.Permission
            });

            aclInfo.Result[guidFields["Client.P_Country"]].Last().Value.Phases.Select(x => x.Value.Permission = 20).ToArray();
            aclHandler.SetFieldAcl(aclInfo.Result);

            //records
            var originalRecordData = recordsHandler.ReadRecords(
                RecordRequestComposer.ComposeReadRequest()
                .ForResource(Porters.TestCoreFramework.Enums.ResourceType.Client)
                .WithIds(new[] { 10001 })
                .Fields("Client.P_Country", "Client.P_Phase", "Client.P_PhaseDate")
                .Result);

            recordsHandler.UpdateRecords(
                RecordRequestComposer.ComposeUpdateRequest().Append(item => item.ForResource(Porters.TestCoreFramework.Enums.ResourceType.Client)
                                                                    .Append(x => x.WithId(10001).AppendField(fields["Client.P_Country"], "TestValue")
                                                                            .AppendField(fields["Client.P_Phase"], originalRecordData.Result.Items.Single()["Client.P_Phase"])
                                                                            .AppendField(fields["Client.P_PhaseDate"], originalRecordData.Result.Items.Single()["Client.P_PhaseDate"]))).Result);

            connection.DeAuthenticate();
            connection.DeleteAllCookies();
            //MANUAL PART: switch DB, restart memcache
            System.Threading.Thread.Sleep(new TimeSpan(0, 5, 5));

            connection.Authenticate();
            //PART3: reading from new DB, making sure that all of values are default
            fieldHandler.UpdateField(resetProgrammingCacheField, ResourceId.Client, new Dictionary <string, object> {
                ["d.label.ja"] = "MEMO"
            });

            // fields check
            var updatedValues = aliases.ToDictionary(x => x, x => fieldHandler.GetFieldDetails($"{resource}.{x}").Result.Values.Single().Value);

            foreach (var alias in aliases)
            {
                PrAssert.That(originalFieldValues[alias].Properties[FieldPropertyToModify], PrIs.EqualTo(updatedValues[alias].Properties[FieldPropertyToModify]));
            }
            //options check
            data = optionHandler.SearchOption("Option.P_LanguageAbility");
            foreach (var child in data.Result.Single().Children)
            {
                PrAssert.That(child.Name, Is.EqualTo(originalOptionValues.Single(x => x.Id == child.Id).Name));
            }
            //acl check
            aclInfo = aclHandler.ReadAclInfo(guidFields["Client.P_Country"]);
            foreach (var aclItem in originalAclInfo)
            {
                PrAssert.That(aclInfo.Result[guidFields["Client.P_Country"]].Last().Value.Phases[aclItem.Key].Permission, Is.EqualTo(aclItem.Value.Permission));
            }
            //records check
            var recordsData = recordsHandler.ReadRecords(
                RecordRequestComposer.ComposeReadRequest()
                .ForResource(Porters.TestCoreFramework.Enums.ResourceType.Client)
                .WithIds(new[] { 10001 })
                .Fields("Client.P_Country", "Client.P_Phase", "Client.P_PhaseDate")
                .Result);

            PrAssert.That(recordsData.Result.Items.Single()["Client.P_Country"], Is.EqualTo(originalRecordData.Result.Items.Single()["Client.P_Country"]));
        }
Exemplo n.º 29
0
 public FieldManager(PrivateApiConnection connection) : base(connection)
 {
 }
Exemplo n.º 30
0
 public MappingManager(PrivateApiConnection connection) : base(connection)
 {
 }