Esempio n. 1
0
        public async Task Updates_the_model()
        {
            var resource = _resourceBuilder.Build();

            StubModelLoader();
            var response = Substitute.For <IResponse>();

            _modelSaver.Save(_currentSupplyModel).Returns(response);

            SetupStubbedSwitch();

            response.SwitchUrl.Returns("switch-uri");

            var viewModel = new CurrentSupplyViewModel
            {
                CurrentSupplyUrl        = Uri,
                IsElectricityComparison = true,
                IsGasComparison         = false
            };

            await _sut.Index(viewModel);

            Assert.That(resource.DataTemplate.GetItem("includedFuels", "compareGas").Data, Is.EqualTo(false.ToString()));
            Assert.That(resource.DataTemplate.GetItem("includedFuels", "compareElec").Data, Is.EqualTo(true.ToString()));
        }
        public async Task Sends_to_self_rel_when_authenticated(string nextUri)
        {
            _httpClientWrapper
            .Send("web-address", Arg.Any <HttpMethod>(), Arg.Any <HttpContent>(), Arg.Any <IDictionary <string, string> >())
            .Returns(AuthorizedResponse(nextUri));

            var result = await _sut.SendAsync(_resourceBuilder.Build());

            Assert.That(result.Links, Is.Not.Null);
            Assert.That(result.Links.Single().Uri, Is.EqualTo(nextUri));
        }
        public async void AddAdditionalsAndRemovals_DeleteProperty_Success()
        {
            // Arrange
            var resourceBuilder = new ResourceBuilder().GenerateSampleData()
                                  .WithEntryLifecycleStatus(ColidEntryLifecycleStatus.Published);
            var publishedResource = resourceBuilder.Build();

            var resourceBuilder2 = new ResourceBuilder().GenerateSampleData()
                                   .WithEntryLifecycleStatus(ColidEntryLifecycleStatus.Draft)
                                   .WithPidUri(publishedResource.PidUri.ToString());

            var draftResource = resourceBuilder2.Build();

            draftResource.Properties.Remove(Graph.Metadata.Constants.Resource.Keyword);
            draftResource.Properties.Remove(Graph.Metadata.Constants.Resource.Author);

            _mockMetadataService.Setup(mock => mock.GetMetadataForEntityTypeInConfig(It.IsAny <string>(), It.IsAny <string>())).Returns(_metadata);
            var revisionGraphPrefix = publishedResource.Id + "Rev" + 1;


            Assert.True(publishedResource.Properties.ContainsKey(Graph.Metadata.Constants.Resource.Keyword));
            Assert.True(publishedResource.Properties.ContainsKey(Graph.Metadata.Constants.Resource.Author));
            // Act
            var result = await _service.AddAdditionalsAndRemovals(publishedResource, draftResource);

            // Assert
            Assert.NotNull(result);

            Assert.False(result.Properties.ContainsKey(Graph.Metadata.Constants.Resource.Author));
            Assert.False(result.Properties.ContainsKey(Graph.Metadata.Constants.Resource.Keyword));
        }
        public async void CreateResource_Success_WithPreviousVersion()
        {
            // Arrange
            var requestBuilder = new ResourceBuilder()
                                 .GenerateSampleData();

            var request  = requestBuilder.BuildRequestDto();
            var resource = requestBuilder.Build();

            request.HasPreviousVersion = Graph.Metadata.Constants.Entity.IdPrefix + Guid.NewGuid();

            var resourceCto      = new ResourcesCTO(null, null);
            var validationFacade = new EntityValidationFacade(ResourceCrudAction.Create, resource, resourceCto, request.HasPreviousVersion, _metadata, null);

            var preProcessServiceResult = Task.FromResult(new Tuple <ValidationResult, bool, EntityValidationFacade>(null, false, validationFacade));

            _mockPreProcessService.Setup(t => t.ValidateAndPreProcessResource(It.IsAny <string>(), request, It.IsAny <ResourcesCTO>(), ResourceCrudAction.Create, It.IsAny <bool>(), It.IsAny <string>())).Returns(preProcessServiceResult);

            // Act
            var result = await _service.CreateResource(request);

            // Assert
            Assert.NotNull(result);
            _mockResourceRepo.Verify(t => t.Create(validationFacade.RequestResource, It.IsAny <IList <MetadataProperty> >()), Times.Once);
            _mockResourceLinkingService.Verify(t => t.LinkResourceIntoList(validationFacade.RequestResource.PidUri, It.IsAny <Uri>()), Times.Once);
        }
Esempio n. 5
0
 public void BuilderTest3()
 {
     var state   = "abc";
     var builder = new ResourceBuilder()
                   .WithState(state);
     var json = builder.Build().ToString();
 }
Esempio n. 6
0
 public void BuilderTest2()
 {
     var state   = new string[] { "value1", "value2" };
     var builder = new ResourceBuilder()
                   .WithState(new { records = 1 })
                   .AddEmbedded("values")
                   .Resource(new ResourceBuilder().WithState(state));
     var json = builder.Build().ToString();
 }
Esempio n. 7
0
        private Resource CreateResource(string resourceType)
        {
            var resourceBuilder = new ResourceBuilder()
                                  .GenerateSampleData()
                                  .WithType(resourceType);

            var resource = resourceBuilder.Build();

            return(resource);
        }
Esempio n. 8
0
        private Resource CreateResourceWithIsCopyOfDataset(Uri resourcePidUri, params string[] linkedPidUris)
        {
            var resourceBuilder = new ResourceBuilder()
                                  .GenerateSampleData()
                                  .WithPidUri(resourcePidUri.ToString())
                                  .WithCopyOfDataset(linkedPidUris);

            var resource = resourceBuilder.Build();

            return(resource);
        }
Esempio n. 9
0
        private Resource CreateResourceWithKeyword(List <dynamic> keywords)
        {
            var resourceBuilder = new ResourceBuilder()
                                  .GenerateSampleData()
                                  .WithPidUri($"https://pid.bayer.com/kos/0308eeb4-ed33-43b8-abf7-599a57cbd718");

            var resource = resourceBuilder.Build();

            // The method WithKeyword does not allow multiple values, so set them after resource has been built
            resource.Properties.AddOrUpdate(Graph.Metadata.Constants.Resource.Keyword, keywords);

            return(resource);
        }
        public async void EditResource_Success()
        {
            // Arrange
            var requestBuilder = new ResourceBuilder()
                                 .GenerateSampleData();

            var request = requestBuilder.BuildRequestDto();

            var resource    = requestBuilder.Build();
            var publishedId = Graph.Metadata.Constants.Entity.IdPrefix + Guid.NewGuid();

            resource.Id = publishedId;

            var resourceCto = new ResourcesCTO(null, resource);

            _mockResourceRepo.Setup(s => s.GetResourcesByPidUri(resource.PidUri, It.IsAny <IList <string> >())).Returns(resourceCto);

            var validationFacade        = new EntityValidationFacade(ResourceCrudAction.Create, resource, resourceCto, request.HasPreviousVersion, _metadata, null);
            var validationResult        = new ValidationResult();
            var preProcessServiceResult = new Tuple <ValidationResult, bool, EntityValidationFacade>(validationResult, false, validationFacade);

            var newResourceId = string.Empty;

            _mockPreProcessService.Setup(t => t.ValidateAndPreProcessResource(It.IsAny <string>(), request, It.IsAny <ResourcesCTO>(), ResourceCrudAction.Update, It.IsAny <bool>(), It.IsAny <string>()))
            .ReturnsAsync(preProcessServiceResult)
            .Callback <string, ResourceRequestDTO, ResourcesCTO, ResourceCrudAction, bool, string>((a, b, c, d, e, f) =>
            {
                newResourceId = a;
                validationResult.Results.Add(new ValidationResultProperty(a, "some path", "some value", "some message", ValidationResultSeverity.Warning));
            });

            // Act
            var result = await _service.EditResource(resource.PidUri, request);

            // Assert
            Assert.All(result.ValidationResult.Results, t =>
            {
                Assert.Equal(t.Node, newResourceId);
            });

            _mockResourceRepo.Verify(s => s.DeleteDraft(result.Resource.PidUri, new Uri(result.Resource.Id)), Times.Once);
            _mockResourceRepo.Verify(s => s.Create(resource, _metadata), Times.Once);
            _mockResourceRepo.Verify(s => s.CreateLinkingProperty(resource.PidUri, new Uri(
                                                                      Graph.Metadata.Constants.Resource.HasPidEntryDraft),
                                                                  Graph.Metadata.Constants.Resource.ColidEntryLifecycleStatus.Published,
                                                                  Graph.Metadata.Constants.Resource.ColidEntryLifecycleStatus.Draft), Times.Once);
            _mockIdentifierService.Verify(s => s.DeleteAllUnpublishedIdentifiers(It.IsAny <Entity>()), Times.Never);
        }
        public async void CreateResource_Should_ThrowError_ValidationFailed()
        {
            // Arrange
            var requestBuilder = new ResourceBuilder()
                                 .GenerateSampleData();

            var request  = requestBuilder.BuildRequestDto();
            var resource = requestBuilder.Build();

            var entityValidationFacade = new EntityValidationFacade(ResourceCrudAction.Create, resource, null, null, _metadata, null);
            var result = Task.FromResult(new Tuple <ValidationResult, bool, EntityValidationFacade>(null, true, entityValidationFacade));

            _mockPreProcessService.Setup(t => t.ValidateAndPreProcessResource(It.IsAny <string>(), request, It.IsAny <ResourcesCTO>(), ResourceCrudAction.Create, It.IsAny <bool>(), It.IsAny <string>())).Returns(result);

            // Act
            await Assert.ThrowsAsync <ResourceValidationException>(() => _service.CreateResource(request));
        }
        public async void CreateInitialResourceRevision_Success()
        {
            // Arrange
            var resourceBuilder = new ResourceBuilder()
                                  .GenerateSampleData();
            var resource = resourceBuilder.Build();

            string revisionGraphPrefix = resource.Id + "Rev" + 1;
            string additionalGraphName = revisionGraphPrefix + "_added";
            // Act
            var result = _service.InitializeResourceInAdditionalsGraph(resource, _metadata);

            // Assert
            Assert.NotNull(result);
            _mockResourceRepo.Verify(t => t.CreateProperty(new Uri(resource.Id), new Uri(COLID.Graph.Metadata.Constants.Resource.HasRevision), revisionGraphPrefix, _resourceGraph), Times.Once);
            _mockResourceRepo.Verify(t => t.Create(resource, _metadata, new Uri(additionalGraphName)), Times.Once);
        }
        public async void AddAdditionalsAndRemovals_Resources_With_Different_PidUris_ThrowError()
        {
            // Arrange
            var resourceBuilder = new ResourceBuilder().GenerateSampleData()
                                  .WithEntryLifecycleStatus(ColidEntryLifecycleStatus.Published);
            var publishedResource = resourceBuilder.Build();

            var resourceBuilder2 = new ResourceBuilder().GenerateSampleData()
                                   .WithEntryLifecycleStatus(ColidEntryLifecycleStatus.Draft);
            var draftResource = resourceBuilder2.Build();

            _mockMetadataService.Setup(mock => mock.GetMetadataForEntityType(It.IsAny <string>())).Returns(_metadata);

            var revisionGraphPrefix = publishedResource.Id + "Rev" + 1;
            // Act
            await Assert.ThrowsAsync <BusinessException>(() => _service.AddAdditionalsAndRemovals(publishedResource, draftResource));
        }
        public async void EditResource__Should_ThrowError_ResourceValidation()
        {
            // Arrange
            var requestBuilder = new ResourceBuilder()
                                 .GenerateSampleData();

            var request = requestBuilder.BuildRequestDto();

            var resource    = requestBuilder.Build();
            var publishedId = Graph.Metadata.Constants.Entity.IdPrefix + Guid.NewGuid();

            resource.Id = publishedId;

            var resourceCto = new ResourcesCTO(null, resource);

            _mockResourceRepo.Setup(s => s.GetResourcesByPidUri(resource.PidUri, It.IsAny <IList <string> >())).Returns(resourceCto);

            var validationFacade        = new EntityValidationFacade(ResourceCrudAction.Create, resource, resourceCto, request.HasPreviousVersion, _metadata, null);
            var validationResult        = new ValidationResult();
            var preProcessServiceResult = new Tuple <ValidationResult, bool, EntityValidationFacade>(validationResult, true, validationFacade);

            var newResourceId = string.Empty;

            _mockPreProcessService.Setup(t => t.ValidateAndPreProcessResource(It.IsAny <string>(), request, It.IsAny <ResourcesCTO>(), ResourceCrudAction.Update, It.IsAny <bool>(), It.IsAny <string>()))
            .ReturnsAsync(preProcessServiceResult)
            .Callback <string, ResourceRequestDTO, ResourcesCTO, ResourceCrudAction, bool, string>((a, b, c, d, e, f) =>
            {
                newResourceId = a;
                validationResult.Results.Add(new ValidationResultProperty(a, "some path", "some value", "some message", ValidationResultSeverity.Warning));
            });

            // Act
            var result = await Assert.ThrowsAsync <ResourceValidationException>(() => _service.EditResource(resource.PidUri, request));

            // Assert
            _mockResourceRepo.Verify(s => s.CreateTransaction(), Times.Never);
            Assert.All(result.ValidationResult.Results, t => Assert.Equal(t.Node, publishedId));
        }
Esempio n. 15
0
        public bool SaveMeta(XmlDocument doc)
        {
            //if explorer is in edit mode, and the current RpfFileEntry is valid, convert XML to the
            //current meta format and then save the file into the RPF.
            //otherwise, save the generated file to disk?
            //(currently just return false and revert to XML file save)

            if (!(exploreForm?.EditMode ?? false))
            {
                return(false);
            }
            if (rpfFileEntry?.Parent == null)
            {
                return(false);
            }

            byte[] data = null;

#if !DEBUG
            try
#endif
            {
                switch (metaFormat)
                {
                default:
                case MetaFormat.XML: return(false);   //what are we even doing here?

                case MetaFormat.RSC:
                    var meta = XmlMeta.GetMeta(doc);
                    if ((meta.DataBlocks?.Data == null) || (meta.DataBlocks.Count == 0))
                    {
                        MessageBox.Show("Schema not supported.", "Cannot import Meta XML");
                        return(false);
                    }
                    data = ResourceBuilder.Build(meta, 2);     //meta is RSC "Version":2    (it's actually a type identifier, not a version!)
                    break;

                case MetaFormat.PSO:
                    var pso = XmlPso.GetPso(doc);
                    if ((pso.DataSection == null) || (pso.DataMapSection == null) || (pso.SchemaSection == null))
                    {
                        MessageBox.Show("Schema not supported.", "Cannot import PSO XML");
                        return(false);
                    }
                    data = pso.Save();
                    break;

                case MetaFormat.RBF:
                    var rbf = XmlRbf.GetRbf(doc);
                    if (rbf.current == null)
                    {
                        MessageBox.Show("Schema not supported.", "Cannot import RBF XML");
                        return(false);
                    }
                    data = rbf.Save();
                    break;

                case MetaFormat.Ynd:
                    var ynd = XmlYnd.GetYnd(doc);
                    if (ynd.NodeDictionary == null)
                    {
                        MessageBox.Show("Schema not supported.", "Cannot import YND XML");
                        return(false);
                    }
                    data = ynd.Save();
                    break;

                case MetaFormat.CacheFile:
                    MessageBox.Show("Sorry, CacheFile import is not supported.", "Cannot import CacheFile XML");
                    return(false);
                }
            }
#if !DEBUG
            catch (Exception ex)
            {
                MessageBox.Show("Exception encountered!\r\n" + ex.ToString(), "Cannot convert XML");
                return(false);
            }
#endif
            if (data == null)
            {
                MessageBox.Show("Schema not supported. (Unspecified error - data was null!)", "Cannot convert XML");
                return(false);
            }

            if (!rpfFileEntry.Path.ToLowerInvariant().StartsWith("mods"))
            {
                if (MessageBox.Show("This file is NOT located in the mods folder - Are you SURE you want to save this file?\r\nWARNING: This could cause permanent damage to your game!!!", "WARNING: Are you sure about this?", MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    return(false);//that was a close one
                }
            }

            try
            {
                if (!(exploreForm?.EnsureRpfValidEncryption(rpfFileEntry.File) ?? false))
                {
                    return(false);
                }

                var newentry = RpfFile.CreateFile(rpfFileEntry.Parent, rpfFileEntry.Name, data);
                if (newentry != rpfFileEntry)
                {
                }
                rpfFileEntry = newentry;

                exploreForm?.RefreshMainListViewInvoke(); //update the file details in explorer...

                modified = false;

                StatusLabel.Text = metaFormat.ToString() + " file saved successfully at " + DateTime.Now.ToString();

                return(true); //victory!
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error saving file to RPF! The RPF archive may be corrupted...\r\n" + ex.ToString(), "Really Bad Error");
            }

            return(false);
        }
Esempio n. 16
0
 protected async Task<IEnumerable<T>> Query<U>(ResourceBuilder resource, Func<T, U, T> map, object parameters = null, IDbTransaction transaction = null)
 {
     var query = await resource.Build();
     Log(query);
     return await _conn.QueryAsync<T, U, T>(query, map, parameters, transaction ?? Transaction);
 }
Esempio n. 17
0
 protected async Task<T> FirstOrDefault(ResourceBuilder resource, object parameters, IDbTransaction transaction = null)
 {
     var query = await resource.Build();
     Log(query);
     return await _conn.QuerySingleOrDefaultAsync<T>(query, parameters, transaction ?? Transaction);
 }
Esempio n. 18
0
 protected async Task<U> ExecuteScalar<U>(ResourceBuilder resource, object parameters, IDbTransaction transaction = null)
 {
     var query = await resource.Build();
     Log(query);
     return await _conn.ExecuteScalarAsync<U>(query, parameters, transaction ?? Transaction);
 }
Esempio n. 19
0
 protected async Task Execute(ResourceBuilder resource, object parameters = null, IDbTransaction transaction = null)
 {
     var query = await resource.Build();
     Log(query);
     await _conn.ExecuteAsync(query, parameters, transaction ?? Transaction);
 }
 private void StubUsageResource() => _apiClient.GetAsync <Resource>("usage-uri").Returns(_usageDataBuilder.Build());
 private void StubModelLoader()
 {
     _resource = _resourceBuilder.Build();
     _model    = new PrepareForTransferModel(_resource);
     _modelLoader.Load <Resource, PrepareForTransferModel>(_viewModel.PrepareForTransferUri).Returns(_model);
 }
Esempio n. 22
0
 private void StubFutureSupply()
 {
     _futureSupplyResource = _futureSupplyResourceBuilder.Build();
     _futureSupplyModel    = new FutureSupplyModel(_futureSupplyResource);
     _modelLoader.Load <Resource, FutureSupplyModel>(_uri).Returns(_futureSupplyModel);
 }