コード例 #1
0
ファイル: BucketServiceTests.cs プロジェクト: ammbyrne/dotnet
        public async Task get_async_should_return_bucket()
        {
            //Arrange
            var name   = "test";
            var bucket = new Bucket(Guid.NewGuid(), name);
            var dto    = new BucketDTO
            {
                Name = bucket.Name
            };
            var repositoryMock = new Mock <IBucketRepository>();
            var mapperMock     = new Mock <IMapper>();

            repositoryMock.Setup(x => x.GetAsync(name))
            .Returns(Task.FromResult(bucket));
            mapperMock.Setup(x => x.Map <BucketDTO>(bucket))
            .Returns(dto);

            var service = new BucketService(repositoryMock.Object, mapperMock.Object);

            //Act
            var bucketDto = await service.GetAsync(name);

            repositoryMock.Verify(x => x.GetAsync(name), Times.Once());
            mapperMock.Verify(x => x.Map <BucketDTO>(bucket), Times.Once());
        }
コード例 #2
0
        private async Task InitAsync(Access access)
        {
            await _semaphoreSlim.WaitAsync();

            try
            {
                if (_isInitialized)
                {
                    return;
                }

                _access       = access;
                BucketService = new BucketService(_access);
                ObjectService = new ObjectService(_access);
                Bucket        = await BucketService.GetBucketAsync("nutz-mich");

                _isInitialized = true;
            }
            catch (Exception ex)
            {
            }
            finally
            {
                _semaphoreSlim.Release();
            }
        }
コード例 #3
0
        public async Task GetAsync_ReturnBucket()
        {
            Bucket    bucket    = new Bucket(BucketName);
            BucketDTO bucketDto = new BucketDTO();
            Mock <IBucketRepository> bucketRepository = new Mock <IBucketRepository>();
            Mock <IMapper>           mapper           = new Mock <IMapper>();

            bucketRepository
            .Setup((it) => it.GetAsync(BucketName))
            .ReturnsAsync(bucket);

            mapper
            .Setup((it) => it.Map <BucketDTO>(bucket))
            .Returns(bucketDto);

            IBucketService bucketService = new BucketService(
                bucketRepository.Object, mapper.Object
                );

            await bucketService.GetAsync(BucketName);

            bucketRepository.Verify(
                (it) => it.GetAsync(BucketName),
                Times.Once
                );
            mapper.Verify(
                (it) => it.Map <BucketDTO>(bucket),
                Times.Once
                );
        }
コード例 #4
0
        public async Task <int> UploadLargeFilesToCloud()
        {
            #region "for large file upload; but the below code doesn't work porperly as it cann't append data at tardigrade server side;"
            var restrictedBucketService = new BucketService(access);

            var newBucketName = "flureebucket";
            var file          = await GetFlureeSnapshot("file.mp4");

            var bucket = await restrictedBucketService.GetBucketAsync(newBucketName);

            using Stream source = File.OpenRead(file.FileName);
            int    chunkSize  = 4 * 1024 * 1024;
            long   uploadSize = chunkSize;
            byte[] buffer     = new byte[chunkSize];
            int    bytesRead;
            while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
            {
                var uploadOperationRestricted = await objectService.UploadObjectAsync(bucket, file.FileName, new UploadOptions(), buffer, true);

                uploadOperationRestricted.UploadOperationProgressChanged += UploadOperationRestricted_UploadOperationProgressChanged;
                uploadOperationRestricted.UploadOperationEnded           += UploadOperationRestricted_UploadOperationEnded;
                await uploadOperationRestricted.StartUploadAsync();

                var mb = ((float)uploadSize / (float)file.File.Length) * 100;
                Console.WriteLine($"{mb} % uploaded");
                uploadSize += chunkSize;
            }

            return(0);

            #endregion
        }
コード例 #5
0
        private async Task Delete_Document_UnitTest(string authKey)
        {
            Command          deleteResponse = new Command();
            IdentityDocument getResponse    = new IdentityDocument();

            try
            {
                if (authKey.Equals(""))
                {
                    deleteResponse = await _bucketService.DeleteAsync(FirstDocumentId, _logger);

                    getResponse = await _bucketService.GetAsync <IdentityDocument>(FirstDocumentId, _logger);
                }
                else
                {
                    var bucketService = new BucketService(authKey);
                    deleteResponse = await bucketService.DeleteAsync(SecondDocumentId, _logger);

                    getResponse = await bucketService.GetAsync <IdentityDocument>(SecondDocumentId, _logger);
                }
            }
            catch (BlipHttpClientException)
            {
                getResponse.Value.ShouldBeNull();
            }
            finally
            {
                deleteResponse.Status.ShouldBe(CommandStatus.Success);
            }
        }
コード例 #6
0
        public async void Update_ErrorsOccurred_ShouldReturnErrorResponse()
        {
            var mock          = new ServiceMockFacade <IBucketService, IBucketRepository>();
            var model         = new ApiBucketServerRequestModel();
            var validatorMock = new Mock <IApiBucketServerRequestModelValidator>();

            validatorMock.Setup(x => x.ValidateUpdateAsync(It.IsAny <int>(), It.IsAny <ApiBucketServerRequestModel>())).Returns(Task.FromResult(new ValidationResult(new List <ValidationFailure>()
            {
                new ValidationFailure("text", "test")
            })));
            mock.RepositoryMock.Setup(x => x.Get(It.IsAny <int>())).Returns(Task.FromResult(new Bucket()));
            var service = new BucketService(mock.LoggerMock.Object,
                                            mock.MediatorMock.Object,
                                            mock.RepositoryMock.Object,
                                            validatorMock.Object,
                                            mock.DALMapperMockFactory.DALBucketMapperMock,
                                            mock.DALMapperMockFactory.DALFileMapperMock);

            UpdateResponse <ApiBucketServerResponseModel> response = await service.Update(default(int), model);

            response.Should().NotBeNull();
            response.Success.Should().BeFalse();
            validatorMock.Verify(x => x.ValidateUpdateAsync(It.IsAny <int>(), It.IsAny <ApiBucketServerRequestModel>()));
            mock.MediatorMock.Verify(x => x.Publish(It.IsAny <BucketUpdatedNotification>(), It.IsAny <CancellationToken>()), Times.Never());
        }
コード例 #7
0
        public async Task AccessShare_Creates_UsableSharedAccessForDownload()
        {
            string serializedAccess;
            string bucketname = "accessshare-creates-usablesharedaccessfordownload";

            byte[] bytesToUpload = ObjectServiceTest.GetRandomBytes(2048);

            using (Access scope = new Access(TestConstants.SATELLITE_URL, TestConstants.VALID_API_KEY, TestConstants.ENCRYPTION_SECRET))
            {
                await _bucketService.CreateBucketAsync(bucketname);

                var bucket = await _bucketService.GetBucketAsync(bucketname);

                var uploadOperation = await _objectService.UploadObjectAsync(bucket, "test/test-file", new UploadOptions(), bytesToUpload, false);

                await uploadOperation.StartUploadAsync();

                Permission permission = new Permission();
                permission.AllowUpload   = false; //Should not change anything as we are downloading here
                permission.AllowDownload = true;
                List <SharePrefix> sharePrefixes = new List <SharePrefix>();
                sharePrefixes.Add(new SharePrefix()
                {
                    Bucket = bucketname, Prefix = "test/"
                });
                var restricted = scope.Share(permission, sharePrefixes);
                serializedAccess = restricted.Serialize();
            }

            await Task.Delay(SATELLITE_WAIT_DURATION); //Wait a bit so that some things can happen on the satellite

            Access restrictedEnv;

            try
            {
                restrictedEnv = new Access(serializedAccess);
            }
            catch
            {
                Assert.Fail("Failed to create restricted scope from serialized scope");
                return;
            }

            var restrictedObjectService = new ObjectService(restrictedEnv);
            var restrictedBucketService = new BucketService(restrictedEnv);
            var restrictedBucket        = await restrictedBucketService.GetBucketAsync(bucketname);

            var downloadOperation = await restrictedObjectService.DownloadObjectAsync(restrictedBucket, "test/test-file", new DownloadOptions(), false);

            await downloadOperation.StartDownloadAsync();

            Assert.IsTrue(downloadOperation.Completed);
            Assert.AreEqual(bytesToUpload.Length, downloadOperation.BytesReceived);

            for (int i = 0; i < bytesToUpload.Length; i++)
            {
                Assert.AreEqual(bytesToUpload[i], downloadOperation.DownloadedBytes[i], "DownloadedBytes are not equal at index " + i);
            }
        }
コード例 #8
0
 public BucketController(BucketService bucketService,
                         BucketCutService bucketCutService,
                         IMapper mapper)
 {
     _mapper           = mapper;
     _bucketCutService = bucketCutService;
     _bucketService    = bucketService;
 }
コード例 #9
0
ファイル: AccessTest.cs プロジェクト: TopperDEL/uplink.net
        public async Task RevokeAccess_MakesAccesUnusable()
        {
            string serializedAccess;
            string bucketname = "revoke-access-makes-access-unusable";

            byte[] bytesToUpload = ObjectServiceTest.GetRandomBytes(2048);

            using (Access scope = new Access(TestConstants.SATELLITE_URL, TestConstants.VALID_API_KEY, TestConstants.ENCRYPTION_SECRET))
            {
                await _bucketService.CreateBucketAsync(bucketname);

                Permission permission = new Permission();
                permission.AllowUpload = true;
                List <SharePrefix> sharePrefixes = new List <SharePrefix>();
                sharePrefixes.Add(new SharePrefix()
                {
                    Bucket = bucketname, Prefix = "test/"
                });
                var restricted = scope.Share(permission, sharePrefixes);
                serializedAccess = restricted.Serialize();

                await Task.Delay(SATELLITE_WAIT_DURATION); //Wait a bit so that some things can happen on the satellite

                Access restrictedEnv;
                try
                {
                    restrictedEnv = new Access(serializedAccess);
                }
                catch
                {
                    Assert.Fail("Failed to create restricted scope from serialized scope");
                    return;
                }

                var restrictedObjectService = new ObjectService(restrictedEnv);
                var restrictedBucketService = new BucketService(restrictedEnv);
                var restrictedBucket        = await restrictedBucketService.GetBucketAsync(bucketname);

                var uploadOperationRestricted = await restrictedObjectService.UploadObjectAsync(restrictedBucket, "test/subfolder/test-file-upload", new UploadOptions(), bytesToUpload, false);

                await uploadOperationRestricted.StartUploadAsync();

                Assert.IsTrue(uploadOperationRestricted.Completed);
                Assert.AreEqual(bytesToUpload.Length, uploadOperationRestricted.BytesSent);

                //Revoke access
                await scope.RevokeAsync(restrictedEnv);

                //Try uploading again
                var uploadOperationRestricted2 = await restrictedObjectService.UploadObjectAsync(restrictedBucket, "test/subfolder/test-file-upload", new UploadOptions(), bytesToUpload, false);

                await uploadOperationRestricted2.StartUploadAsync();

                Assert.IsFalse(uploadOperationRestricted2.Completed);
                Assert.IsTrue(uploadOperationRestricted2.Failed);
            }
        }
コード例 #10
0
        public async Task BucketDeleteLogUnitTest_ShouldSucceed()
        {
            var client        = BuildSenderSubstitute_ReturnsSuccessStatus();
            var bucketService = new BucketService(client);
            var logger        = Substitute.For <ILogger>();
            var task          = bucketService.DeleteAsync(FirstDocumentId, logger);

            await TestInfoLogsWithOneArg <string>(task, 2, logger);
        }
コード例 #11
0
 public ImageCnController(IWebHostEnvironment webHostEnvironment,
                          MarkLogoService markLogoService,
                          BucketCutService bucketCutService,
                          BucketService bucketService)
 {
     _bucketService      = bucketService;
     _bucketCutService   = bucketCutService;
     _markLogoService    = markLogoService;
     _webHostEnvironment = webHostEnvironment;
 }
コード例 #12
0
        public async Task BucketStoreLogUnitTest_ShouldSucceed()
        {
            var document      = new IdentityDocument(IdentityString);
            var client        = BuildSenderSubstitute_ReturnsSuccessStatus();
            var bucketService = new BucketService(client);
            var logger        = Substitute.For <ILogger>();
            var task          = bucketService.SetAsync(FirstDocumentId, document, logger);

            await TestInfoLogsWithTwoArgs <IdentityDocument, string>(task, 2, logger);
        }
コード例 #13
0
        public async Task BucketGetLogUnitTest_ShouldSucceed()
        {
            var client        = BuildSenderSubstitute_ReturnsSuccessStatus();
            var bucketService = new BucketService(client);
            var logger        = Substitute.For <ILogger>();
            var task          = bucketService.GetAsync <IdentityDocument>(FirstDocumentId, logger);

            await TestInfoLogsWithTwoArgs <string, IdentityDocument>(task, 1, logger);
            await TestInfoLogsWithOneArg <string>(task, 1, logger);
        }
コード例 #14
0
ファイル: BucketServiceTest.cs プロジェクト: ndockens/Cubo
        public async Task add_async_should_invoke_repository_methods()
        {
            var name           = "test-bucket";
            var repositoryMock = new Mock <IBucketRepository>();
            var mapperMock     = new Mock <IMapper>();
            var service        = new BucketService(repositoryMock.Object, mapperMock.Object);

            await service.AddAsync(name);

            repositoryMock.Verify(x => x.AddAsync(It.IsAny <Bucket>()), Times.Once);
        }
コード例 #15
0
        public async Task ListBucketsAsync_lists_buckets_for_user()
        {
            // Arrange
            IBucketService classUnderTest = new BucketService(_s3BucketClient);

            // Act
            var response = await classUnderTest.ListBucketsAsync();

            // Assert
            Assert.IsTrue(response.HttpStatusCode == System.Net.HttpStatusCode.OK);
            Assert.IsTrue(response.Buckets.Count > 0);
        }
コード例 #16
0
        public void GetBucketItems_ItemsInBucket_ShouldReturnListOfOrderItem()
        {
            var context = new ApplicationDbContext(_testcs);
            var service = new BucketService(context);

            var items = service.GetBucketItems("Test");

            items.Wait();
            var itemsCount = items.Result.Count();

            Assert.That(itemsCount, Is.EqualTo(2));
        }
コード例 #17
0
        public void GetBucketItems_EmptyBucket_ShouldReturnEmptyList()
        {
            var context = new ApplicationDbContext(_testcs);
            var service = new BucketService(context);

            var items = service.GetBucketItems("Te"); // User doesn't exist;

            items.Wait();
            var itemsCount = items.Result.Count();

            Assert.That(itemsCount, Is.EqualTo(0));
        }
コード例 #18
0
        public async Task DeleteBucketAsync_deletes_bucket()
        {
            // Arrange
            IBucketService classUnderTest = new BucketService(_s3BucketClient);

            // Act
            var response = await classUnderTest
                           .DeleteBucketAsync(BucketName);

            // Assert
            Assert.IsTrue(response.HttpStatusCode == System.Net.HttpStatusCode.OK);
        }
コード例 #19
0
        public async Task AddAsync_CreateNewBucket()
        {
            IBucketService bucketService = new BucketService(
                new InMemoryBucketRepository(), AutoMapperConfig.InitializeMapper()
                );

            await bucketService.AddAsync(BucketName);

            BucketDTO bucketDto = await bucketService.GetAsync(BucketName);

            Assert.Equal(BucketName, bucketDto.Name);
        }
コード例 #20
0
ファイル: BucketServiceTest.cs プロジェクト: ndockens/Cubo
        public async Task add_async_should_create_new_bucket()
        {
            var repository = new InMemoryBucketRepository();
            var service    = new BucketService(repository, AutoMapperConfig.GetMapper());
            var name       = "test-bucket";

            await service.AddAsync(name);

            var bucketDto = await service.GetAsync(name);

            bucketDto.Name.Should().BeEquivalentTo(name);
        }
コード例 #21
0
 public UploadController(SettingService settingService,
                         BucketImageService bucketImageService,
                         BucketService bucketService,
                         IWebHostEnvironment hostingEnvironment,
                         IMediaItemStorage mediaItemStorage)
 {
     _mediaItemStorage   = mediaItemStorage;
     _hostingEnvironment = hostingEnvironment;
     _bucketService      = bucketService;
     _settingService     = settingService;
     _bucketImageService = bucketImageService;
 }
コード例 #22
0
        public void GetAll_gets_buckets_From_datastore()
        {
            //Arrange
            var dataStore = new Mock <IDataStore <Bucket> >();

            var service = new BucketService(datastore: dataStore.Object);

            //Act
            _ = service.GetAllAsync().Result;

            //Assert
            dataStore.Verify(mock => mock.GetAllAsync(), Times.Once);
        }
コード例 #23
0
ファイル: BucketServiceTests.cs プロジェクト: ammbyrne/dotnet
        public async Task add_async_should_create_new_bucket()
        {
            //Arrange
            var repository = new InMemoryBucketRepository();
            var service    = new BucketService(repository, AutoMapperConfig.GetMapper());
            var name       = "test";

            //Act
            await service.AddAsync(name);

            //Assert
            var bucketDto = await service.GetAsync(name);

            Assert.Equal(name, bucketDto.Name);
        }
コード例 #24
0
        public async Task AddAsync_InvokeRepositoryMethod()
        {
            Mock <IBucketRepository> bucketRepository = new Mock <IBucketRepository>();
            Mock <IMapper>           mapper           = new Mock <IMapper>();
            IBucketService           bucketService    = new BucketService(
                bucketRepository.Object, mapper.Object
                );

            await bucketService.AddAsync(BucketName);

            bucketRepository.Verify(
                (repo) => repo.AddAsync(It.IsAny <Bucket>()),
                Times.Once
                );
        }
コード例 #25
0
        public async Task AccessShare_Creates_UsableSharedAccessForUploadDeep()
        {
            string serializedAccess;
            string bucketname = "accessshare-creates-usablesharedaccessforuploaddeep";

            byte[] bytesToUpload = ObjectServiceTest.GetRandomBytes(2048);

            using (Access scope = new Access(TestConstants.SATELLITE_URL, TestConstants.VALID_API_KEY, TestConstants.ENCRYPTION_SECRET))
            {
                await _bucketService.CreateBucketAsync(bucketname);

                Permission permission = new Permission();
                permission.AllowUpload   = true;
                permission.AllowDownload = false; //should not change anything as we are uploading here
                List <SharePrefix> sharePrefixes = new List <SharePrefix>();
                sharePrefixes.Add(new SharePrefix()
                {
                    Bucket = bucketname, Prefix = "test/subfolder/"
                });
                var restricted = scope.Share(permission, sharePrefixes);
                serializedAccess = restricted.Serialize();
            }

            await Task.Delay(1500); //Wait a bit so that some things can happen on the satellite

            Access restrictedEnv;

            try
            {
                restrictedEnv = new Access(serializedAccess);
            }
            catch
            {
                Assert.Fail("Failed to create restricted scope from serialized scope");
                return;
            }

            var restrictedObjectService = new ObjectService(restrictedEnv);
            var restrictedBucketService = new BucketService(restrictedEnv);
            var restrictedBucket        = await restrictedBucketService.GetBucketAsync(bucketname);

            var uploadOperationRestricted = await restrictedObjectService.UploadObjectAsync(restrictedBucket, "test/subfolder/test-file-upload", new UploadOptions(), bytesToUpload, false);

            await uploadOperationRestricted.StartUploadAsync();

            Assert.IsTrue(uploadOperationRestricted.Completed);
            Assert.AreEqual(bytesToUpload.Length, uploadOperationRestricted.BytesSent);
        }
コード例 #26
0
        public async Task <int> UploadToCloud()
        {
            // Listing buckets.
            var bucketService = new BucketService(access);

            var buckets = await bucketService.ListBucketsAsync(new ListBucketsOptions());

            foreach (var b in buckets.Items)
            {
                Console.WriteLine(b.Name);
            }
            var restrictedBucketService = new BucketService(access);

            var newBucketName = "flureebucket";

            var bucket = await restrictedBucketService.GetBucketAsync(newBucketName);

            var fileObject = await GetFlureeSnapshot("1585578518736.avro");

            var uploadOperationRestricted = await objectService.UploadObjectAsync(bucket, fileObject.FileName, new UploadOptions(), fileObject.File, true);

            uploadOperationRestricted.UploadOperationProgressChanged += UploadOperationRestricted_UploadOperationProgressChanged;
            uploadOperationRestricted.UploadOperationEnded           += UploadOperationRestricted_UploadOperationEnded;
            await uploadOperationRestricted.StartUploadAsync();


            // Download a file from a bucket.

            var objects = await objectService.ListObjectsAsync(bucket, new ListObjectsOptions());

            foreach (var obj in objects.Items)
            {
                //work with the objects
                Console.WriteLine($"Found {obj.Key} {obj.SystemMetaData.Created}");


                //await objectService.DeleteObjectAsync(bucket, obj.Path);

//                var downloadSvc = await objectService.DownloadObjectAsync(bucket, obj.Path, false);
//                downloadSvc.DownloadOperationProgressChanged += DownloadOperation_DownloadOperationProgressChanged;
//                downloadSvc.DownloadOperationEnded += DownloadOperation_DownloadOperationEnded;
//                await downloadSvc.StartDownloadAsync();
            }


            return(0);
        }
コード例 #27
0
        public void GetAll_returns_some_buckets()
        {
            //Arrange
            var dataStore = new Mock <IDataStore <Bucket> >();

            dataStore
            .Setup(fake => fake.GetAllAsync())
            .ReturnsAsync(new List <Bucket>());

            var service = new BucketService(datastore: dataStore.Object);

            //Act
            var result = service.GetAllAsync().Result;

            //Assert
            Assert.IsNotNull(result);
        }
コード例 #28
0
        public void If_DataStore_is_not_initialized_GetAll_initializes_it()
        {
            //Arrange
            var dataStore = new Mock <IDataStore <Bucket> >();

            dataStore
            .SetupGet(fake => fake.IsInitialized)
            .Returns(false);

            var service = new BucketService(dataStore.Object);

            //Act
            service.GetAllAsync().Wait();

            //Assert
            dataStore.Verify(mock => mock.InitializeAsync(), Times.Once);
        }
コード例 #29
0
        public async void Get_ShouldReturnNullBecauseRecordNotFound()
        {
            var mock = new ServiceMockFacade <IBucketService, IBucketRepository>();

            mock.RepositoryMock.Setup(x => x.Get(It.IsAny <int>())).Returns(Task.FromResult <Bucket>(null));
            var service = new BucketService(mock.LoggerMock.Object,
                                            mock.MediatorMock.Object,
                                            mock.RepositoryMock.Object,
                                            mock.ModelValidatorMockFactory.BucketModelValidatorMock.Object,
                                            mock.DALMapperMockFactory.DALBucketMapperMock,
                                            mock.DALMapperMockFactory.DALFileMapperMock);

            ApiBucketServerResponseModel response = await service.Get(default(int));

            response.Should().BeNull();
            mock.RepositoryMock.Verify(x => x.Get(It.IsAny <int>()));
        }
コード例 #30
0
        private async Task Get_Document_UnitTest(string authKey)
        {
            IdentityDocument getResponse;
            var document = new IdentityDocument(IdentityString);

            if (authKey.Equals(""))
            {
                getResponse = await _bucketService.GetAsync <IdentityDocument>(FirstDocumentId, _logger);
            }
            else
            {
                var bucketService = new BucketService(authKey);
                getResponse = await bucketService.GetAsync <IdentityDocument>(SecondDocumentId, _logger);
            }

            getResponse.Value.Equals(document.Value).ShouldBeTrue();
        }