Exemplo n.º 1
0
        public async Task UploadStudentTypeWithEnumText_Returns_StudentWithEnum()
        {
            var logger = new Mock <IFormatterLogger>();

            logger.Setup(x => x.LogError(It.IsAny <string>(), It.IsAny <Exception>()));

            var goodStudentType = StudentTypes.Good;

            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var multipartFormContent       = new MultipartFormDataContent("---wwww-wwww-wwww-boundary-----");

            multipartFormContent.Add(new StringContent(Enum.GetName(typeof(StudentTypes), goodStudentType), Encoding.UTF8), $"{nameof(StudentViewModel.NullableStudentType)}");

            var uploadedModel = await multipartFormDataFormatter
                                .ReadFromStreamAsync(typeof(StudentViewModel), new MemoryStream(),
                                                     multipartFormContent, logger.Object);

            if (!(uploadedModel is StudentViewModel student))
            {
                Assert.IsInstanceOf <StudentViewModel>(uploadedModel);
                return;
            }

            Assert.AreEqual(goodStudentType, student.NullableStudentType);
        }
        public async Task UploadStudentWithoutId_Returns_StudentWithGuidEmptyId()
        {
            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var formFileCollection         = new FormFileCollection();

            var models = new Dictionary <string, StringValues>();

            var formCollection  = new FormCollection(models, formFileCollection);
            var httpContextMock = new Mock <HttpContext>();
            var httpRequestMock = new Mock <HttpRequest>();

            httpRequestMock.Setup(x => x.Form)
            .Returns(formCollection);

            httpRequestMock.Setup(x => x.ReadFormAsync(It.IsAny <CancellationToken>()))
            .ReturnsAsync(formCollection);

            httpContextMock.SetupGet(x => x.Request)
            .Returns(httpRequestMock.Object);

            var inputFormatter = new InputFormatterContext(httpContextMock.Object, string.Empty,
                                                           new ModelStateDictionary(), new EmptyModelMetaData(ModelMetadataIdentity.ForType(typeof(StudentViewModel))),
                                                           (stream, encoding) => TextReader.Null);

            var handledResult = await multipartFormDataFormatter
                                .ReadRequestBodyAsync(inputFormatter);

            Assert.IsInstanceOf <InputFormatterResult>(handledResult);

            var student = handledResult.Model as StudentViewModel;

            Assert.NotNull(student);
            Assert.AreEqual(Guid.Empty, student.Id);
        }
Exemplo n.º 3
0
        public async Task UploadBlankIdIntoProfile_Returns_StudentProfileWithId()
        {
            var profileId = Guid.Empty.ToString("D");

            var logger = new Mock <IFormatterLogger>();

            logger.Setup(x => x.LogError(It.IsAny <string>(), It.IsAny <Exception>()));

            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var multipartFormContent       = new MultipartFormDataContent("---wwww-wwww-wwww-boundary-----");

            multipartFormContent.Add(new StringContent(profileId, Encoding.UTF8), $"{nameof(StudentViewModel.Profile)}[{nameof(ProfileViewModel.Id)}]");

            var uploadedModel = await multipartFormDataFormatter
                                .ReadFromStreamAsync(typeof(StudentViewModel), new MemoryStream(),
                                                     multipartFormContent, logger.Object);

            if (!(uploadedModel is StudentViewModel student))
            {
                Assert.IsInstanceOf <StudentViewModel>(uploadedModel);
                return;
            }

            Assert.AreEqual(student.Profile.Id.ToString("D"), profileId);
        }
Exemplo n.º 4
0
        public async Task UploadStudentWithPhoto_Returns_StudentWithPhoto()
        {
            var fileName    = $"{Guid.NewGuid():D}.jpg";
            var contentType = "image/jpeg";

            var logger = new Mock <IFormatterLogger>();

            logger.Setup(x => x.LogError(It.IsAny <string>(), It.IsAny <Exception>()));

            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var multipartFormContent       = new MultipartFormDataContent("---wwww-wwww-wwww-boundary-----");

            var applicationPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var attachmentPath  = Path.Combine(applicationPath, "Data", "grapefruit-slice-332-332.jpg");
            var data            = File.ReadAllBytes(attachmentPath);

            var attachment = new ByteArrayContent(data);

            attachment.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            multipartFormContent.Add(attachment, nameof(StudentViewModel.Photo), fileName);

            var uploadedModel = await multipartFormDataFormatter
                                .ReadFromStreamAsync(typeof(StudentViewModel), new MemoryStream(),
                                                     multipartFormContent, logger.Object);

            if (!(uploadedModel is StudentViewModel student))
            {
                Assert.IsInstanceOf <StudentViewModel>(uploadedModel);
                return;
            }

            Assert.AreEqual(student.Photo.ContentLength, data.Length);
            Assert.AreEqual(student.Photo.FileName, fileName);
            Assert.AreEqual(student.Photo.ContentType, contentType);
        }
        public async Task UploadStudentWithBufferedAttachment_Returns_StudentWithBufferedAttachment()
        {
            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var formFileCollection         = new FormFileCollection();

            var applicationPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var attachmentPath  = Path.Combine(applicationPath, "Data", "grapefruit-slice-332-332.jpg");
            var data            = File.ReadAllBytes(attachmentPath);

            var fileName   = $"{Guid.NewGuid().ToString("D")}.jpg";
            var attachment = new FormFile(new MemoryStream(data), 0, data.Length,
                                          $"{nameof(StudentViewModel.Profile)}[{nameof(ProfileViewModel.BufferedAttachment)}]", fileName);

            formFileCollection.Add(attachment);
            attachment.Headers     = new HeaderDictionary();
            attachment.ContentType = "image/jpeg";

            var formCollection  = new FormCollection(new Dictionary <string, StringValues>(), formFileCollection);
            var httpContextMock = new Mock <HttpContext>();
            var httpRequestMock = new Mock <HttpRequest>();

            httpRequestMock.Setup(x => x.Form)
            .Returns(formCollection);

            httpRequestMock.Setup(x => x.ReadFormAsync(It.IsAny <CancellationToken>()))
            .ReturnsAsync(formCollection);

            httpContextMock.SetupGet(x => x.Request)
            .Returns(httpRequestMock.Object);

            var inputFormatter = new InputFormatterContext(httpContextMock.Object, string.Empty,
                                                           new ModelStateDictionary(), new EmptyModelMetaData(ModelMetadataIdentity.ForType(typeof(StudentViewModel))),
                                                           (stream, encoding) => TextReader.Null);

            var handledResult = await multipartFormDataFormatter
                                .ReadRequestBodyAsync(inputFormatter);

            Assert.IsInstanceOf <InputFormatterResult>(handledResult);

            var student = handledResult.Model as StudentViewModel;

            Assert.NotNull(student);
            Assert.NotNull(student.Profile);
            Assert.NotNull(student.Profile.BufferedAttachment);
            Assert.AreEqual(attachment.FileName, student.Profile.BufferedAttachment.FileName);
            Assert.AreEqual(attachment.ContentType, student.Profile.BufferedAttachment.ContentType);
            Assert.AreEqual(attachment.Length, student.Profile.BufferedAttachment.ContentLength);
        }
        public async Task UploadStudentWithChildIds_Returns_StudentWithChildIds()
        {
            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var formFileCollection         = new FormFileCollection();

            var childIds = Enumerable.Range(1, 3)
                           .Select(x => Guid.NewGuid())
                           .ToList();

            var models = new Dictionary <string, StringValues>();

            for (var index = 0; index < childIds.Count; index++)
            {
                models.Add($"{nameof(StudentViewModel.ChildIds)}[{index}]", childIds[index].ToString("D"));
            }

            var formCollection  = new FormCollection(models, formFileCollection);
            var httpContextMock = new Mock <HttpContext>();
            var httpRequestMock = new Mock <HttpRequest>();

            httpRequestMock.Setup(x => x.Form)
            .Returns(formCollection);

            httpRequestMock.Setup(x => x.ReadFormAsync(It.IsAny <CancellationToken>()))
            .ReturnsAsync(formCollection);

            httpContextMock.SetupGet(x => x.Request)
            .Returns(httpRequestMock.Object);

            var inputFormatter = new InputFormatterContext(httpContextMock.Object, string.Empty,
                                                           new ModelStateDictionary(), new EmptyModelMetaData(ModelMetadataIdentity.ForType(typeof(StudentViewModel))),
                                                           (stream, encoding) => TextReader.Null);

            var handledResult = await multipartFormDataFormatter
                                .ReadRequestBodyAsync(inputFormatter);

            Assert.IsInstanceOf <InputFormatterResult>(handledResult);

            var student = handledResult.Model as StudentViewModel;

            Assert.NotNull(student);

            for (var id = 0; id < childIds.Count; id++)
            {
                Assert.AreEqual(childIds[id].ToString("D"), student.ChildIds[id].ToString("D"));
            }
        }
Exemplo n.º 7
0
        public async Task UploadStudentWithName_Returns_StudentWithFullName()
        {
            var studentName = "Student-001";
            var logger      = new Mock <IFormatterLogger>();

            logger.Setup(x => x.LogError(It.IsAny <string>(), It.IsAny <Exception>()));

            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var multipartFormContent       = new MultipartFormDataContent("---wwww-wwww-wwww-boundary-----");

            multipartFormContent.Add(new StringContent(studentName), nameof(StudentViewModel.FullName));
            var uploadedModel = await multipartFormDataFormatter
                                .ReadFromStreamAsync(typeof(StudentViewModel), new MemoryStream(),
                                                     multipartFormContent, logger.Object);

            Assert.IsInstanceOf <StudentViewModel>(uploadedModel);
            Assert.AreEqual((uploadedModel as StudentViewModel)?.FullName, studentName);
        }
Exemplo n.º 8
0
        public async Task UploadWithNestedRelativeIds_Returns_StudentProfileWithRelativeIds()
        {
            var relativeIds = new Guid[]
            {
                Guid.NewGuid(),
                Guid.NewGuid(),
                Guid.NewGuid(),
            };

            var logger = new Mock <IFormatterLogger>();

            logger.Setup(x => x.LogError(It.IsAny <string>(), It.IsAny <Exception>()));

            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var multipartFormContent       = new MultipartFormDataContent("---wwww-wwww-wwww-boundary-----");

            for (var i = 0; i < relativeIds.Length; i++)
            {
                var content = new StringContent(relativeIds[i].ToString("D"), Encoding.UTF8);
                multipartFormContent.Add(content, $"{nameof(StudentViewModel.Profile)}[{nameof(ProfileViewModel.RelativeIds)}][{i}]");
            }

            var uploadedModel = await multipartFormDataFormatter
                                .ReadFromStreamAsync(typeof(StudentViewModel), new MemoryStream(),
                                                     multipartFormContent, logger.Object);

            if (!(uploadedModel is StudentViewModel student))
            {
                Assert.IsInstanceOf <StudentViewModel>(uploadedModel);
                return;
            }

            Assert.NotNull(student.Profile);
            Assert.NotNull(student.Profile.RelativeIds);
            Assert.AreEqual(student.Profile.RelativeIds.Count, relativeIds.Length);

            for (var i = 0; i < relativeIds.Length; i++)
            {
                Assert.AreEqual(relativeIds[i], student.Profile.RelativeIds[i]);
            }
        }
Exemplo n.º 9
0
        public async Task UploadStudentTypeWithNullEnumText_Returns_StudentWithNullEnum()
        {
            var logger = new Mock <IFormatterLogger>();

            logger.Setup(x => x.LogError(It.IsAny <string>(), It.IsAny <Exception>()));

            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var multipartFormContent       = new MultipartFormDataContent("---wwww-wwww-wwww-boundary-----");

            var uploadedModel = await multipartFormDataFormatter
                                .ReadFromStreamAsync(typeof(StudentViewModel), new MemoryStream(),
                                                     multipartFormContent, logger.Object);

            if (!(uploadedModel is StudentViewModel student))
            {
                Assert.IsInstanceOf <StudentViewModel>(uploadedModel);
                return;
            }

            Assert.IsNull(student.NullableStudentType);
        }
        public async Task UploadIdIntoProfile_Returns_StudentProfileWithId()
        {
            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var formFileCollection         = new FormFileCollection();

            var id = Guid.NewGuid().ToString("D");

            var models = new Dictionary <string, StringValues>();

            models.Add($"{nameof(StudentViewModel.Profile)}[{nameof(ProfileViewModel.Id)}]", id);

            var formCollection  = new FormCollection(models, formFileCollection);
            var httpContextMock = new Mock <HttpContext>();
            var httpRequestMock = new Mock <HttpRequest>();

            httpRequestMock.Setup(x => x.Form)
            .Returns(formCollection);

            httpRequestMock.Setup(x => x.ReadFormAsync(It.IsAny <CancellationToken>()))
            .ReturnsAsync(formCollection);

            httpContextMock.SetupGet(x => x.Request)
            .Returns(httpRequestMock.Object);

            var inputFormatter = new InputFormatterContext(httpContextMock.Object, string.Empty,
                                                           new ModelStateDictionary(), new EmptyModelMetaData(ModelMetadataIdentity.ForType(typeof(StudentViewModel))),
                                                           (stream, encoding) => TextReader.Null);

            var handledResult = await multipartFormDataFormatter
                                .ReadRequestBodyAsync(inputFormatter);

            Assert.IsInstanceOf <InputFormatterResult>(handledResult);

            var student = handledResult.Model as StudentViewModel;

            Assert.IsNotNull(student?.Profile);
            Assert.AreEqual(id, student.Profile.Id.ToString("D"));
        }
Exemplo n.º 11
0
        public async Task UploadStudentWithChildIds_Returns_StudentWithChildIds()
        {
            var childIds = new LinkedList <Guid>();

            childIds.AddLast(Guid.NewGuid());
            childIds.AddLast(Guid.NewGuid());

            var logger = new Mock <IFormatterLogger>();

            logger.Setup(x => x.LogError(It.IsAny <string>(), It.IsAny <Exception>()));

            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var multipartFormContent       = new MultipartFormDataContent("---wwww-wwww-wwww-boundary-----");

            var index = 0;

            foreach (var childId in childIds)
            {
                multipartFormContent.Add(new StringContent(childId.ToString("D"), Encoding.UTF8), $"{nameof(StudentViewModel.ChildIds)}[{index}]");
                index++;
            }

            var uploadedModel = await multipartFormDataFormatter
                                .ReadFromStreamAsync(typeof(StudentViewModel), new MemoryStream(),
                                                     multipartFormContent, logger.Object);

            if (!(uploadedModel is StudentViewModel student))
            {
                Assert.IsInstanceOf <StudentViewModel>(uploadedModel);
                return;
            }

            for (var childId = 0; childId < childIds.Count; childId++)
            {
                Assert.AreEqual(childIds.ElementAt(childId), student.ChildIds[childId]);
            }
        }
Exemplo n.º 12
0
        public async Task UploadStudentWithParentId_Returns_StudentWithParentId()
        {
            var parentId = Guid.NewGuid().ToString("D");

            var logger = new Mock <IFormatterLogger>();

            logger.Setup(x => x.LogError(It.IsAny <string>(), It.IsAny <Exception>()));

            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var multipartFormContent       = new MultipartFormDataContent("---wwww-wwww-wwww-boundary-----");

            multipartFormContent.Add(new StringContent(parentId, Encoding.UTF8), nameof(StudentViewModel.ParentId));
            var uploadedModel = await multipartFormDataFormatter
                                .ReadFromStreamAsync(typeof(StudentViewModel), new MemoryStream(),
                                                     multipartFormContent, logger.Object);

            if (!(uploadedModel is StudentViewModel student))
            {
                Assert.IsInstanceOf <StudentViewModel>(uploadedModel);
                return;
            }

            Assert.AreEqual(student.ParentId?.ToString("D"), parentId);
        }