/// <summary>
        /// Create new <see cref="ParameterValueSet"/> for a <see cref="Parameter"/>
        /// </summary>
        /// <param name="parameter">The <see cref="Parameter"/></param>
        /// <param name="actualOption">The actual <see cref="CDP4Common.DTO.Option"/></param>
        /// <param name="transaction">The current transaction</param>
        /// <param name="partition">The current partition</param>
        /// <param name="securityContext">The security context</param>
        /// <param name="newOldActualStateMap">The map that links the new <see cref="ActualFiniteState"/> to the old ones</param>
        /// <param name="oldValueSets">The old <see cref="ParameterValueSet"/></param>
        /// <param name="newOldValueSetMap">The map that links the new to old <see cref="ParameterValueSet"/></param>
        private void CreateParameterValueSets(Parameter parameter, Guid?actualOption, NpgsqlTransaction transaction, string partition, ISecurityContext securityContext, IReadOnlyDictionary <ActualFiniteState, ActualFiniteState> newOldActualStateMap, IReadOnlyList <ParameterValueSet> oldValueSets, ref Dictionary <ParameterValueSet, ParameterValueSet> newOldValueSetMap)
        {
            if (newOldActualStateMap == null || !newOldActualStateMap.Any())
            {
                // the parameter lost the state dependency
                var oldValueSet = oldValueSets.FirstOrDefault(x => x.ActualOption == actualOption);
                var newValueset = this.CreateParameterValueSet(oldValueSet, parameter, actualOption, null, transaction, partition, securityContext);
                newOldValueSetMap.Add(newValueset, oldValueSet);
                return;
            }

            foreach (var newOldStatePair in newOldActualStateMap)
            {
                ParameterValueSet oldValueSet;
                if (newOldStatePair.Value == null)
                {
                    oldValueSet = null;
                }
                else
                {
                    oldValueSet =
                        oldValueSets.SingleOrDefault(
                            x =>
                            x.ActualOption == actualOption &&
                            x.ActualState == newOldStatePair.Value.Iid);
                }

                var newValueSet = this.CreateParameterValueSet(oldValueSet, parameter, actualOption, newOldStatePair.Key.Iid, transaction, partition, securityContext);
                newOldValueSetMap.Add(newValueSet, oldValueSet);
            }
        }
Beispiel #2
0
        public void VerifyThatAfterUpdateStateChangesWorks()
        {
            var originalThing = this.parameter.DeepClone <Thing>();

            this.valueSetService.Setup(
                x => x.DeleteConcept(null, "partition", It.IsAny <ParameterValueSet>(), this.parameter)).Returns(true);

            this.parameter.ParameterType = this.cptParameterType.Iid;

            this.parameter.StateDependence = null;
            var valueset = new ParameterValueSet(Guid.NewGuid(), 0);

            this.parameter.ValueSet.Add(valueset.Iid);

            var updatedParameter = new Parameter(this.parameter.Iid, 0)
            {
                StateDependence = this.actualList.Iid
            };

            updatedParameter.ValueSet.Add(valueset.Iid);
            updatedParameter.ParameterType = this.cptParameterType.Iid;

            this.sideEffect.AfterUpdate(updatedParameter, this.elementDefinition, originalThing, this.npgsqlTransaction, "partition", this.securityContext.Object);

            this.valueSetService.Verify(x => x.CreateConcept(null, "partition", It.Is <ParameterValueSet>(vs => vs.ActualState == this.actualState1.Iid), updatedParameter, -1), Times.Exactly(1));
            this.valueSetService.Verify(x => x.CreateConcept(null, "partition", It.Is <ParameterValueSet>(vs => vs.ActualState == this.actualState2.Iid), updatedParameter, -1), Times.Exactly(1));
        }
 public bool Write(NpgsqlTransaction transaction, string partition, Parameter parameter, Thing container = null)
 {
     parameter.ValueSet.Clear();
     parameter.ValueSet.Add(Guid.NewGuid());
     this.writtenThings.Add(parameter);
     return(true);
 }
Beispiel #4
0
        public void VerifyOwnerChangedSideEffects()
        {
            this.parameter.ParameterType = this.boolPt.Iid;
            var domain1       = new DomainOfExpertise(Guid.NewGuid(), 0);
            var domain2       = new DomainOfExpertise(Guid.NewGuid(), 0);
            var originalThing = this.parameter.DeepClone <Thing>();

            this.parameter.Owner = domain1.Iid;

            var updatedParameter = new Parameter(this.parameter.Iid, 0)
            {
                ParameterType = this.boolPt.Iid, Owner = domain2.Iid, AllowDifferentOwnerOfOverride = true
            };
            var parameterOverride1 = new ParameterOverride(Guid.NewGuid(), 0)
            {
                Parameter = updatedParameter.Iid, Owner = domain2.Iid
            };
            var domain2Subscription = new ParameterSubscription(Guid.NewGuid(), 0)
            {
                Owner = domain2.Iid
            };

            updatedParameter.ParameterSubscription.Add(domain2Subscription.Iid);
            parameterOverride1.ParameterSubscription.Add(domain2Subscription.Iid);

            this.parameterSubscriptionService.Setup(x => x.GetShallow(It.IsAny <NpgsqlTransaction>(), It.IsAny <string>(), It.IsAny <IEnumerable <Guid> >(), this.securityContext.Object))
            .Returns(new List <Thing> {
                domain2Subscription
            });

            this.parameterSubscriptionService.Setup(x => x.DeleteConcept(It.IsAny <NpgsqlTransaction>(),
                                                                         It.IsAny <string>(), It.IsAny <Thing>(), It.IsAny <Thing>())).Returns(true);

            this.sideEffect.AfterUpdate(updatedParameter, this.elementDefinition, originalThing, this.npgsqlTransaction, "partition", this.securityContext.Object);

            // Check that the subscription owned by domain2 is deleted since domain2 is now the owner of the parameter
            this.parameterSubscriptionService.Verify(x => x.DeleteConcept(this.npgsqlTransaction, "partition", It.IsAny <ParameterSubscription>(), It.IsAny <Parameter>()),
                                                     Times.Once);

            // Since that is the only subscription, no updates are performed on ParameterSubscriptionValueSet
            this.parameterSubscriptionValueSetService.Verify(x => x.CreateConcept(this.npgsqlTransaction, "partition", It.IsAny <ParameterSubscriptionValueSet>(), It.IsAny <ParameterSubscription>(), -1),
                                                             Times.Never);

            // Check that since AllowDifferentOwnerOfOverride is True the owner of the parameterOverrides are not updated
            this.parameterOverrideService.Verify(x => x.UpdateConcept(this.npgsqlTransaction, "partition", It.IsAny <ParameterOverride>(), It.IsAny <ElementUsage>()),
                                                 Times.Never);

            var updatedParameter1 = new Parameter(this.parameter.Iid, 0)
            {
                ParameterType = this.boolPt.Iid, Owner = domain2.Iid, AllowDifferentOwnerOfOverride = false
            };

            updatedParameter1.ParameterSubscription.Add(domain2Subscription.Iid);
            this.sideEffect.AfterUpdate(updatedParameter1, this.elementDefinition, originalThing, this.npgsqlTransaction, "partition", this.securityContext.Object);

            // Check that since AllowDifferentOwnerOfOverride is False the owner of the parameterOverride is updated
            this.parameterOverrideService.Verify(x => x.UpdateConcept(this.npgsqlTransaction, "partition", It.IsAny <ParameterOverride>(), It.IsAny <ElementUsage>()),
                                                 Times.Once);
        }
        public void VerifyThatCreateValueSetsUpdateOperationsWorksStateOptionDependent()
        {
            var valueset1 = new ParameterValueSet(Guid.NewGuid(), this.assembler.Cache, this.uri);

            valueset1.Manual = new ValueArray <string>(manual);
            this.parameter1.ValueSet.Add(valueset1);
            valueset1.ActualOption = this.option1;
            valueset1.ActualState  = this.as1;

            var valueset2 = new ParameterValueSet(Guid.NewGuid(), this.assembler.Cache, this.uri);

            valueset2.Manual = new ValueArray <string>();
            this.parameter1.ValueSet.Add(valueset2);
            valueset2.ActualOption = this.option2;
            valueset2.ActualState  = this.as1;

            this.parameter1.IsOptionDependent     = true;
            this.parameter1Copy.IsOptionDependent = true;
            this.parameter1.StateDependence       = this.asl1;

            var modeldto     = this.model2.ToDto();
            var iterationDto = (Dto.Iteration) this.iteration2.ToDto();
            var def2Dto      = new Dto.ElementDefinition(this.def2Copy.Iid, 2);
            var parameterDto = new Dto.Parameter(this.parameter1Copy.Iid, 2);

            parameterDto.IsOptionDependent = true;
            var newValueSet = new Dto.ParameterValueSet(Guid.NewGuid(), 2);

            iterationDto.Element.Add(def2Dto.Iid);
            def2Dto.Parameter.Add(parameterDto.Iid);
            parameterDto.ValueSet.Add(newValueSet.Iid);

            var returnedDto = new List <Dto.Thing>
            {
                modeldto,
                iterationDto,
                def2Dto,
                parameterDto,
                newValueSet
            };

            var transactionContext = TransactionContextResolver.ResolveContext(this.iteration2);
            var context            = transactionContext.ContextRoute();

            var operationCreator   = new ValueSetOperationCreator(this.session.Object);
            var operationContainer = operationCreator.CreateValueSetsUpdateOperations(context, returnedDto, this.map);

            var operation = operationContainer.Operations.Single();
            var original  = (Dto.ParameterValueSet)operation.OriginalThing;
            var modified  = (Dto.ParameterValueSet)operation.ModifiedThing;

            Assert.AreNotEqual(original.Manual, modified.Manual);
        }
Beispiel #6
0
        /// <summary>
        /// The mapping from a database record to data transfer object.
        /// </summary>
        /// <param name="reader">
        /// An instance of the SQL reader.
        /// </param>
        /// <returns>
        /// A deserialized instance of <see cref="CDP4Common.DTO.Parameter"/>.
        /// </returns>
        public virtual CDP4Common.DTO.Parameter MapToDto(NpgsqlDataReader reader)
        {
            string tempAllowDifferentOwnerOfOverride;
            string tempExpectsOverride;
            string tempIsOptionDependent;
            string tempModifiedOn;
            string tempThingPreference;

            var valueDict      = (Dictionary <string, string>)reader["ValueTypeSet"];
            var iid            = Guid.Parse(reader["Iid"].ToString());
            var revisionNumber = int.Parse(valueDict["RevisionNumber"]);

            var dto = new CDP4Common.DTO.Parameter(iid, revisionNumber);

            dto.ExcludedDomain.AddRange(Array.ConvertAll((string[])reader["ExcludedDomain"], Guid.Parse));
            dto.ExcludedPerson.AddRange(Array.ConvertAll((string[])reader["ExcludedPerson"], Guid.Parse));
            dto.Group = reader["Group"] is DBNull ? (Guid?)null : Guid.Parse(reader["Group"].ToString());
            dto.Owner = Guid.Parse(reader["Owner"].ToString());
            dto.ParameterSubscription.AddRange(Array.ConvertAll((string[])reader["ParameterSubscription"], Guid.Parse));
            dto.ParameterType   = Guid.Parse(reader["ParameterType"].ToString());
            dto.RequestedBy     = reader["RequestedBy"] is DBNull ? (Guid?)null : Guid.Parse(reader["RequestedBy"].ToString());
            dto.Scale           = reader["Scale"] is DBNull ? (Guid?)null : Guid.Parse(reader["Scale"].ToString());
            dto.StateDependence = reader["StateDependence"] is DBNull ? (Guid?)null : Guid.Parse(reader["StateDependence"].ToString());
            dto.ValueSet.AddRange(Array.ConvertAll((string[])reader["ValueSet"], Guid.Parse));

            if (valueDict.TryGetValue("AllowDifferentOwnerOfOverride", out tempAllowDifferentOwnerOfOverride))
            {
                dto.AllowDifferentOwnerOfOverride = bool.Parse(tempAllowDifferentOwnerOfOverride);
            }

            if (valueDict.TryGetValue("ExpectsOverride", out tempExpectsOverride))
            {
                dto.ExpectsOverride = bool.Parse(tempExpectsOverride);
            }

            if (valueDict.TryGetValue("IsOptionDependent", out tempIsOptionDependent))
            {
                dto.IsOptionDependent = bool.Parse(tempIsOptionDependent);
            }

            if (valueDict.TryGetValue("ModifiedOn", out tempModifiedOn))
            {
                dto.ModifiedOn = Utils.ParseUtcDate(tempModifiedOn);
            }

            if (valueDict.TryGetValue("ThingPreference", out tempThingPreference) && tempThingPreference != null)
            {
                dto.ThingPreference = tempThingPreference.UnEscape();
            }

            return(dto);
        }
        public void VerifyThatCreateValueSetsUpdateOperationsWorks()
        {
            var valueset = new ParameterValueSet(Guid.NewGuid(), this.assembler.Cache, this.uri);

            valueset.Manual = new ValueArray <string>(manual);
            this.parameter1.ValueSet.Add(valueset);

            var subscriptionvalueset = new ParameterSubscriptionValueSet(Guid.NewGuid(), this.assembler.Cache, this.uri);

            subscriptionvalueset.Manual = new ValueArray <string>(manual);
            this.subscription1.ValueSet.Add(subscriptionvalueset);

            var modeldto     = this.model2.ToDto();
            var iterationDto = (Dto.Iteration) this.iteration2.ToDto();
            var def2Dto      = new Dto.ElementDefinition(this.def2Copy.Iid, 2);
            var parameterDto = new Dto.Parameter(this.parameter1Copy.Iid, 2);
            var newValueSet  = new Dto.ParameterValueSet(Guid.NewGuid(), 2);

            var subscription         = new Dto.ParameterSubscription(this.subscriptionCopy.Iid, 1);
            var subscriptionValueSet = new Dto.ParameterSubscriptionValueSet(Guid.NewGuid(), 1);

            iterationDto.Element.Add(def2Dto.Iid);
            def2Dto.Parameter.Add(parameterDto.Iid);
            parameterDto.ValueSet.Add(newValueSet.Iid);
            parameterDto.ParameterSubscription.Add(subscription.Iid);
            subscription.ValueSet.Add(subscriptionValueSet.Iid);

            var returnedDto = new List <Dto.Thing>
            {
                modeldto,
                iterationDto,
                def2Dto,
                parameterDto,
                newValueSet,
                subscription,
                subscriptionValueSet
            };

            var transactionContext = TransactionContextResolver.ResolveContext(this.iteration2);
            var context            = transactionContext.ContextRoute();

            var operationCreator   = new ValueSetOperationCreator(this.session.Object);
            var operationContainer = operationCreator.CreateValueSetsUpdateOperations(context, returnedDto, this.map);

            Assert.AreEqual(2, operationContainer.Operations.Count());
            var operation   = operationContainer.Operations.Single(x => x.OriginalThing.ClassKind == ClassKind.ParameterValueSet);
            var originalPvs = (Dto.ParameterValueSet)operation.OriginalThing;
            var modifiedPvs = (Dto.ParameterValueSet)operation.ModifiedThing;

            Assert.AreNotEqual(originalPvs.Manual, modifiedPvs.Manual);
        }
        /// <summary>
        /// Update a <see cref="Parameter"/> with new <see cref="ParameterValueSet"/>
        /// </summary>
        /// <param name="parameter">The <see cref="Parameter"/></param>
        /// <param name="iteration">The <see cref="Iteration"/></param>
        /// <param name="transaction">The current transaction</param>
        /// <param name="partition">The current partition</param>
        /// <param name="securityContext">The security context</param>
        /// <param name="newOldActualStateMap">The map that links the new to old <see cref="ActualFiniteState"/></param>
        /// <param name="newOldValueSetMap">The resulting map that links the new to old <see cref="ParameterValueSet"/></param>
        private void UpdateParameter(Parameter parameter, Iteration iteration, NpgsqlTransaction transaction, string partition, ISecurityContext securityContext, IReadOnlyDictionary <ActualFiniteState, ActualFiniteState> newOldActualStateMap, ref Dictionary <ParameterValueSet, ParameterValueSet> newOldValueSetMap)
        {
            var oldValueSets = this.ParameterValueSetService.GetShallow(transaction, partition, parameter.ValueSet, securityContext)
                               .Where(i => i is ParameterValueSet).Cast <ParameterValueSet>().ToList();

            if (parameter.IsOptionDependent)
            {
                foreach (var orderedItem in iteration.Option.OrderBy(x => x.K))
                {
                    var actualOption = Guid.Parse(orderedItem.V.ToString());
                    this.CreateParameterValueSets(parameter, actualOption, transaction, partition, securityContext, newOldActualStateMap, oldValueSets, ref newOldValueSetMap);
                }
            }
            else
            {
                this.CreateParameterValueSets(parameter, null, transaction, partition, securityContext, newOldActualStateMap, oldValueSets, ref newOldValueSetMap);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Update a database record from the supplied data transfer object.
        /// </summary>
        /// <param name="transaction">
        /// The current <see cref="NpgsqlTransaction"/> to the database.
        /// </param>
        /// <param name="partition">
        /// The database partition (schema) where the requested resource will be updated.
        /// </param>
        /// <param name="parameter">
        /// The Parameter DTO that is to be updated.
        /// </param>
        /// <param name="container">
        /// The container of the DTO to be updated.
        /// </param>
        /// <returns>
        /// True if the concept was successfully updated.
        /// </returns>
        public virtual bool Update(NpgsqlTransaction transaction, string partition, CDP4Common.DTO.Parameter parameter, CDP4Common.DTO.Thing container = null)
        {
            bool isHandled;
            var  valueTypeDictionaryAdditions = new Dictionary <string, string>();
            var  beforeUpdate = this.BeforeUpdate(transaction, partition, parameter, container, out isHandled, valueTypeDictionaryAdditions);

            if (!isHandled)
            {
                beforeUpdate = beforeUpdate && base.Update(transaction, partition, parameter, container);

                var valueTypeDictionaryContents = new Dictionary <string, string>
                {
                    { "AllowDifferentOwnerOfOverride", !this.IsDerived(parameter, "AllowDifferentOwnerOfOverride") ? parameter.AllowDifferentOwnerOfOverride.ToString() : string.Empty },
                    { "ExpectsOverride", !this.IsDerived(parameter, "ExpectsOverride") ? parameter.ExpectsOverride.ToString() : string.Empty },
                }.Concat(valueTypeDictionaryAdditions).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

                using (var command = new NpgsqlCommand())
                {
                    var sqlBuilder = new System.Text.StringBuilder();
                    sqlBuilder.AppendFormat("UPDATE \"{0}\".\"Parameter\"", partition);
                    sqlBuilder.AppendFormat(" SET (\"ValueTypeDictionary\", \"Container\", \"RequestedBy\")");
                    sqlBuilder.AppendFormat(" = (:valueTypeDictionary, :container, :requestedBy)");
                    sqlBuilder.AppendFormat(" WHERE \"Iid\" = :iid;");

                    command.Parameters.Add("iid", NpgsqlDbType.Uuid).Value = parameter.Iid;
                    command.Parameters.Add("valueTypeDictionary", NpgsqlDbType.Hstore).Value = valueTypeDictionaryContents;
                    command.Parameters.Add("container", NpgsqlDbType.Uuid).Value             = container.Iid;
                    command.Parameters.Add("requestedBy", NpgsqlDbType.Uuid).Value           = !this.IsDerived(parameter, "RequestedBy") ? Utils.NullableValue(parameter.RequestedBy) : Utils.NullableValue(null);

                    command.CommandText = sqlBuilder.ToString();
                    command.Connection  = transaction.Connection;
                    command.Transaction = transaction;

                    this.ExecuteAndLogCommand(command);
                }
            }

            return(this.AfterUpdate(beforeUpdate, transaction, partition, parameter, container));
        }
Beispiel #10
0
        /// <summary>
        /// Insert a new database record, or updates one if it already exists from the supplied data transfer object.
        /// This is typically used during the import of existing data to the Database.
        /// </summary>
        /// <param name="transaction">
        /// The current <see cref="NpgsqlTransaction"/> to the database.
        /// </param>
        /// <param name="partition">
        /// The database partition (schema) where the requested resource will be stored.
        /// </param>
        /// <param name="parameter">
        /// The parameter DTO that is to be persisted.
        /// </param>
        /// <param name="container">
        /// The container of the DTO to be persisted.
        /// </param>
        /// <returns>
        /// True if the concept was successfully persisted.
        /// </returns>
        public virtual bool Upsert(NpgsqlTransaction transaction, string partition, CDP4Common.DTO.Parameter parameter, CDP4Common.DTO.Thing container = null)
        {
            var valueTypeDictionaryAdditions = new Dictionary <string, string>();

            base.Upsert(transaction, partition, parameter, container);

            var valueTypeDictionaryContents = new Dictionary <string, string>
            {
                { "AllowDifferentOwnerOfOverride", !this.IsDerived(parameter, "AllowDifferentOwnerOfOverride") ? parameter.AllowDifferentOwnerOfOverride.ToString() : string.Empty },
                { "ExpectsOverride", !this.IsDerived(parameter, "ExpectsOverride") ? parameter.ExpectsOverride.ToString() : string.Empty },
            }.Concat(valueTypeDictionaryAdditions).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            using (var command = new NpgsqlCommand())
            {
                var sqlBuilder = new System.Text.StringBuilder();

                sqlBuilder.AppendFormat("INSERT INTO \"{0}\".\"Parameter\"", partition);
                sqlBuilder.AppendFormat(" (\"Iid\", \"ValueTypeDictionary\", \"Container\", \"RequestedBy\")");
                sqlBuilder.AppendFormat(" VALUES (:iid, :valueTypeDictionary, :container, :requestedBy)");

                command.Parameters.Add("iid", NpgsqlDbType.Uuid).Value = parameter.Iid;
                command.Parameters.Add("valueTypeDictionary", NpgsqlDbType.Hstore).Value = valueTypeDictionaryContents;
                command.Parameters.Add("container", NpgsqlDbType.Uuid).Value             = container.Iid;
                command.Parameters.Add("requestedBy", NpgsqlDbType.Uuid).Value           = !this.IsDerived(parameter, "RequestedBy") ? Utils.NullableValue(parameter.RequestedBy) : Utils.NullableValue(null);
                sqlBuilder.Append(" ON CONFLICT (\"Iid\")");
                sqlBuilder.Append(" DO UPDATE ");
                sqlBuilder.Append(" SET (\"ValueTypeDictionary\", \"Container\", \"RequestedBy\")");
                sqlBuilder.Append(" = (:valueTypeDictionary, :container, :requestedBy);");

                command.CommandText = sqlBuilder.ToString();
                command.Connection  = transaction.Connection;
                command.Transaction = transaction;

                this.ExecuteAndLogCommand(command);
            }

            return(true);
        }
        public void VerifyInvalidOperationException()
        {
            var valueset1 = new ParameterValueSet(Guid.NewGuid(), this.assembler.Cache, this.uri);

            valueset1.Manual = new ValueArray <string>(manual);
            this.parameter1.ValueSet.Add(valueset1);
            valueset1.ActualOption = this.option1;
            valueset1.ActualState  = this.as1;

            var modeldto     = this.model2.ToDto();
            var iterationDto = (Dto.Iteration) this.iteration2.ToDto();
            var def2Dto      = new Dto.ElementDefinition(this.def2Copy.Iid, 2);
            var parameterDto = new Dto.Parameter(this.parameter1Copy.Iid, 2);

            parameterDto.IsOptionDependent = true;
            var newValueSet = new Dto.ParameterValueSet(Guid.NewGuid(), 2);

            iterationDto.Element.Add(def2Dto.Iid);
            def2Dto.Parameter.Add(parameterDto.Iid);
            parameterDto.ValueSet.Add(newValueSet.Iid);

            var returnedDto = new List <Dto.Thing>
            {
                iterationDto,
                def2Dto,
                parameterDto,
                newValueSet
            };

            var transactionContext = TransactionContextResolver.ResolveContext(this.iteration2);
            var context            = transactionContext.ContextRoute();

            var operationCreator = new ValueSetOperationCreator(this.session.Object);

            Assert.Throws <InvalidOperationException>(() => operationCreator.CreateValueSetsUpdateOperations(context, returnedDto, this.map));
        }
        public void VerifyCopyElementDefWorks()
        {
            var modelSetupService = new Mock <IEngineeringModelSetupService>();
            var modelSetup        = new EngineeringModelSetup(Guid.NewGuid(), 0);

            modelSetupService.Setup(x => x.GetEngineeringModelSetup(It.IsAny <NpgsqlTransaction>(), It.IsAny <Guid>())).Returns(modelSetup);

            this.copySourceDtos = new List <Thing>();

            var boolParamTypeId = Guid.NewGuid();
            var mrdl            = new ModelReferenceDataLibrary(Guid.NewGuid(), 1);

            mrdl.ParameterType.Add(boolParamTypeId);

            var sourceIteration   = new Iteration(Guid.NewGuid(), 1);
            var sourceElementDef1 = new ElementDefinition(Guid.NewGuid(), 1);
            var sourceElementDef2 = new ElementDefinition(Guid.NewGuid(), 1);
            var sourceUsage1      = new ElementUsage(Guid.NewGuid(), 1)
            {
                ElementDefinition = sourceElementDef2.Iid
            };

            sourceElementDef1.ContainedElement.Add(sourceUsage1.Iid);
            sourceIteration.Element.Add(sourceElementDef1.Iid);
            sourceIteration.Element.Add(sourceElementDef2.Iid);

            var parameter1 = new Parameter(Guid.NewGuid(), 1)
            {
                ParameterType = boolParamTypeId
            };
            var pvs1 = new ParameterValueSet(Guid.NewGuid(), 1)
            {
                Manual      = new ValueArray <string>(new[] { "true" }),
                Computed    = new ValueArray <string>(new[] { "-" }),
                Reference   = new ValueArray <string>(new[] { "-" }),
                Published   = new ValueArray <string>(new[] { "-" }),
                ValueSwitch = ParameterSwitchKind.MANUAL
            };

            var parameter2 = new Parameter(Guid.NewGuid(), 1)
            {
                ParameterType = boolParamTypeId
            };
            var pvs2 = new ParameterValueSet(Guid.NewGuid(), 1)
            {
                Manual      = new ValueArray <string>(new[] { "true" }),
                Computed    = new ValueArray <string>(new[] { "-" }),
                Reference   = new ValueArray <string>(new[] { "-" }),
                Published   = new ValueArray <string>(new[] { "-" }),
                ValueSwitch = ParameterSwitchKind.MANUAL
            };

            parameter1.ValueSet.Add(pvs1.Iid);
            sourceElementDef1.Parameter.Add(parameter1.Iid);
            parameter2.ValueSet.Add(pvs2.Iid);
            sourceElementDef2.Parameter.Add(parameter2.Iid);

            var override2 = new ParameterOverride(Guid.NewGuid(), 1);

            override2.Parameter = parameter2.Iid;
            var ovs = new ParameterOverrideValueSet(Guid.NewGuid(), 1)
            {
                ParameterValueSet = pvs2.Iid
            };

            override2.ValueSet.Add(ovs.Iid);
            sourceUsage1.ParameterOverride.Add(override2.Iid);

            this.copySourceDtos.Add(sourceIteration);
            this.copySourceDtos.Add(sourceElementDef1);
            this.copySourceDtos.Add(sourceElementDef2);
            this.copySourceDtos.Add(sourceUsage1);
            this.copySourceDtos.Add(parameter1);
            this.copySourceDtos.Add(pvs1);
            this.copySourceDtos.Add(parameter2);
            this.copySourceDtos.Add(pvs2);
            this.copySourceDtos.Add(override2);
            this.copySourceDtos.Add(ovs);

            var targetIteration = new Iteration(Guid.NewGuid(), 1);

            this.serviceProvider.Setup(x => x.MapToReadService(It.IsAny <string>())).Returns <string>(x => new TestSourceService(this.copySourceDtos, x));
            this.serviceProvider.Setup(x => x.MapToReadService(It.Is <string>(t => t == ClassKind.ModelReferenceDataLibrary.ToString())))
            .Returns <string>(x => new TestSourceService(new List <Thing> {
                mrdl
            }, x));

            this.serviceProvider.Setup(x => x.MapToReadService(It.Is <string>(t => t == ClassKind.Iteration.ToString())))
            .Returns <string>(x => new TestSourceService(new List <Thing> {
                sourceIteration, targetIteration
            }, x));

            var customOperationSideEffectProcessor = new Mock <IOperationSideEffectProcessor>();

            customOperationSideEffectProcessor.Setup(x => x.BeforeCreate(It.IsAny <Thing>(), It.IsAny <Thing>(), It.IsAny <NpgsqlTransaction>(), It.IsAny <string>(), It.IsAny <ISecurityContext>())).
            Returns(true);

            var paramSubscriptionService = new ParameterSubscriptionService
            {
                ParameterSubscriptionDao = new Mock <IParameterSubscriptionDao>().Object,
                PermissionService        = this.permissionService.Object,
            };

            var parameterContextProvider = new OldParameterContextProvider
            {
                ParameterValueSetService = new TestSourceService(this.copySourceDtos, ClassKind.ParameterValueSet.ToString())
            };

            var paramGroupService = new ParameterGroupService
            {
                PermissionService = this.permissionService.Object,

                TransactionManager = this.transactionManager.Object,
                ParameterGroupDao  = new Mock <IParameterGroupDao>().Object
            };

            var valueSetService = new Mock <IParameterValueSetService>();

            valueSetService.Setup(x => x.GetShallow(It.IsAny <NpgsqlTransaction>(), It.IsAny <string>(), It.IsAny <IEnumerable <Guid> >(), It.IsAny <ISecurityContext>()))
            .Returns <NpgsqlTransaction, string, IEnumerable <Guid>, ISecurityContext>((a, b, c, d) =>
            {
                var list = new List <ParameterValueSet>();
                foreach (var guid in c)
                {
                    var vs = new ParameterValueSet(guid, 1)
                    {
                        Manual    = new ValueArray <string>(new [] { "-" }),
                        Computed  = new ValueArray <string>(new [] { "-" }),
                        Reference = new ValueArray <string>(new [] { "-" }),
                        Published = new ValueArray <string>(new [] { "-" })
                    };

                    list.Add(vs);
                }

                return(list);
            });

            var overrideValueSetService = new Mock <IParameterOverrideValueSetService>();

            overrideValueSetService.Setup(x => x.GetShallow(It.IsAny <NpgsqlTransaction>(), It.IsAny <string>(), It.IsAny <IEnumerable <Guid> >(), It.IsAny <ISecurityContext>()))
            .Returns <NpgsqlTransaction, string, IEnumerable <Guid>, ISecurityContext>((a, b, c, d) =>
            {
                var list = new List <ParameterOverrideValueSet>();
                foreach (var guid in c)
                {
                    var vs = new ParameterOverrideValueSet(guid, 1)
                    {
                        Manual    = new ValueArray <string>(new[] { "-" }),
                        Computed  = new ValueArray <string>(new[] { "-" }),
                        Reference = new ValueArray <string>(new[] { "-" }),
                        Published = new ValueArray <string>(new[] { "-" })
                    };

                    list.Add(vs);
                }

                return(list);
            });

            var paramDao     = new TestParameterDao();
            var paramService = new ParameterService
            {
                PermissionService            = this.permissionService.Object,
                ParameterDao                 = paramDao,
                OperationSideEffectProcessor = customOperationSideEffectProcessor.Object,
                TransactionManager           = this.transactionManager.Object,
                OldParameterContextProvider  = parameterContextProvider,
                ParameterSubscriptionService = paramSubscriptionService,
                ParameterValueSetService     = valueSetService.Object
            };

            var paramOverrideDao = new TestParameterOverrideDao();

            var paramOverrideService = new ParameterOverrideService
            {
                PermissionService = this.permissionService.Object,

                ParameterOverrideDao             = paramOverrideDao,
                TransactionManager               = this.transactionManager.Object,
                OperationSideEffectProcessor     = customOperationSideEffectProcessor.Object,
                ParameterSubscriptionService     = paramSubscriptionService,
                ParameterOverrideValueSetService = overrideValueSetService.Object
            };

            var usageDao     = new Mock <IElementUsageDao>();
            var usageService = new ElementUsageService
            {
                PermissionService = this.permissionService.Object,

                ParameterOverrideService     = paramOverrideService,
                ElementUsageDao              = usageDao.Object,
                TransactionManager           = this.transactionManager.Object,
                OperationSideEffectProcessor = customOperationSideEffectProcessor.Object
            };

            var edDao     = new TestElementDefinitionDao();
            var edService = new ElementDefinitionService
            {
                PermissionService = this.permissionService.Object,

                ElementDefinitionDao         = edDao,
                ElementUsageService          = usageService,
                ParameterService             = paramService,
                TransactionManager           = this.transactionManager.Object,
                OperationSideEffectProcessor = customOperationSideEffectProcessor.Object,
                ParameterGroupService        = paramGroupService
            };

            this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.ElementDefinition.ToString())).Returns(edService);
            this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.ElementUsage.ToString())).Returns(usageService);
            this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.Parameter.ToString())).Returns(paramService);
            this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.ParameterOverride.ToString())).Returns(paramOverrideService);
            this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.ParameterSubscription.ToString())).Returns(paramSubscriptionService);
            this.serviceProvider.Setup(x => x.MapToPersitableService(ClassKind.ParameterGroup.ToString())).Returns(paramGroupService);

            var postOperation = new CdpPostOperation();
            var copyinfo      = new CopyInfo
            {
                ActiveOwner = Guid.NewGuid(),
                Options     = new CopyInfoOptions
                {
                    CopyKind   = CopyKind.Deep,
                    KeepOwner  = true,
                    KeepValues = true
                },
                Source = new CopySource
                {
                    IterationId = sourceIteration.Iid,
                    Thing       = new CopyReference
                    {
                        Iid       = sourceElementDef1.Iid,
                        ClassKind = ClassKind.ElementDefinition
                    },
                    TopContainer = new CopyReference
                    {
                        Iid       = Guid.NewGuid(),
                        ClassKind = ClassKind.EngineeringModel
                    }
                },
                Target = new CopyTarget
                {
                    IterationId = targetIteration.Iid,
                    Container   = new CopyReference
                    {
                        Iid       = targetIteration.Iid,
                        ClassKind = ClassKind.Iteration
                    },
                    TopContainer = new CopyReference
                    {
                        Iid       = Guid.NewGuid(),
                        ClassKind = ClassKind.EngineeringModel
                    }
                }
            };

            postOperation.Copy.Add(copyinfo);

            this.serviceProvider.Setup(x => x.MapToReadService(ClassKind.EngineeringModelSetup.ToString())).Returns(modelSetupService.Object);
            this.operationProcessor.Process(postOperation, null, $"Iteration_{targetIteration.Iid.ToString().Replace("-", "_")}", null);

            Assert.AreEqual(2, edDao.WrittenThingCount);
            Assert.AreEqual(2, paramDao.WrittenThingCount);
            Assert.AreEqual(1, paramOverrideDao.WrittenThingCount);
            usageDao.Verify(x => x.Write(It.IsAny <NpgsqlTransaction>(), It.IsAny <string>(), It.IsAny <ElementUsage>(), It.IsAny <Thing>()), Times.Once);
        }
Beispiel #13
0
        public void Setup()
        {
            this.securityContext = new Mock <ISecurityContext>();
            this.optionService   = new Mock <IOptionService>();
            this.actualFiniteStateListService = new Mock <IActualFiniteStateListService>();
            this.parameterService             = new Mock <ICompoundParameterTypeService>();
            this.valueSetService  = new Mock <IParameterValueSetService>();
            this.iterationService = new Mock <IIterationService>();
            this.parameterOverrideValueSetService     = new Mock <IParameterOverrideValueSetService>();
            this.parameterSubscriptionValueSetService = new Mock <IParameterSubscriptionValueSetService>();
            this.parameterSubscriptionService         = new Mock <IParameterSubscriptionService>();
            this.parameterOverrideService             = new Mock <IParameterOverrideService>();
            this.parameterTypeComponentService        = new Mock <IParameterTypeComponentService>();
            this.parameterTypeService        = new Mock <IParameterTypeService>();
            this.elementUsageService         = new Mock <IElementUsageService>();
            this.defaultValueArrayFactory    = new Mock <IDefaultValueArrayFactory>();
            this.OldParameterContextProvider = new Mock <IOldParameterContextProvider>();

            this.npgsqlTransaction = null;

            this.iteration = new Iteration(Guid.NewGuid(), 1);
            this.option1   = new Option(Guid.NewGuid(), 1);
            this.option2   = new Option(Guid.NewGuid(), 1);

            this.iteration.Option.Add(new OrderedItem {
                K = 1, V = this.option1.Iid
            });
            this.iteration.Option.Add(new OrderedItem {
                K = 2, V = this.option2.Iid
            });

            this.actualList   = new ActualFiniteStateList(Guid.NewGuid(), 1);
            this.actualState1 = new ActualFiniteState(Guid.NewGuid(), 1);
            this.actualState2 = new ActualFiniteState(Guid.NewGuid(), 1);

            this.actualList.ActualState.Add(this.actualState1.Iid);
            this.actualList.ActualState.Add(this.actualState2.Iid);

            this.parameter = new Parameter(Guid.NewGuid(), 1);

            this.cptParameterType = new CompoundParameterType(Guid.NewGuid(), 1);
            this.boolPt           = new BooleanParameterType(Guid.NewGuid(), 1);
            this.cpt1             = new ParameterTypeComponent(Guid.NewGuid(), 1)
            {
                ParameterType = this.boolPt.Iid
            };
            this.cpt2 = new ParameterTypeComponent(Guid.NewGuid(), 1)
            {
                ParameterType = this.boolPt.Iid
            };

            this.cptParameterType.Component.Add(new OrderedItem {
                K = 1, V = this.cpt1.Iid.ToString()
            });
            this.cptParameterType.Component.Add(new OrderedItem {
                K = 2, V = this.cpt2.Iid.ToString()
            });

            this.sideEffect = new ParameterSideEffect
            {
                IterationService                     = this.iterationService.Object,
                ActualFiniteStateListService         = this.actualFiniteStateListService.Object,
                ParameterValueSetService             = this.valueSetService.Object,
                ParameterOverrideValueSetService     = this.parameterOverrideValueSetService.Object,
                ParameterSubscriptionValueSetService = this.parameterSubscriptionValueSetService.Object,
                ParameterOverrideService             = this.parameterOverrideService.Object,
                ParameterSubscriptionService         = this.parameterSubscriptionService.Object,
                ParameterTypeService                 = this.parameterTypeService.Object,
                ElementUsageService                  = this.elementUsageService.Object,
                ParameterTypeComponentService        = this.parameterTypeComponentService.Object,
                OptionService                        = this.optionService.Object,
                DefaultValueArrayFactory             = this.defaultValueArrayFactory.Object,
                ParameterValueSetFactory             = new ParameterValueSetFactory(),
                ParameterOverrideValueSetFactory     = new ParameterOverrideValueSetFactory(),
                ParameterSubscriptionValueSetFactory = new ParameterSubscriptionValueSetFactory(),
                OldParameterContextProvider          = this.OldParameterContextProvider.Object
            };

            // prepare mock data
            this.elementDefinition = new ElementDefinition(Guid.NewGuid(), 1);
            this.elementDefinition.Parameter.Add(this.parameter.Iid);
            this.parameterOverride = new ParameterOverride(Guid.NewGuid(), 1)
            {
                Parameter = this.parameter.Iid,
            };
            this.elementUsage = new ElementUsage(Guid.NewGuid(), 1)
            {
                ElementDefinition = this.elementDefinition.Iid, ParameterOverride = { this.parameterOverride.Iid }
            };

            this.parameterService.Setup(x => x.Get(It.IsAny <NpgsqlTransaction>(), "SiteDirectory", It.Is <IEnumerable <Guid> >(y => y.Contains(this.cptParameterType.Iid)), this.securityContext.Object))
            .Returns(new List <Thing> {
                this.cptParameterType
            });

            this.iterationService.Setup(x => x.GetActiveIteration(null, "partition", this.securityContext.Object))
            .Returns(this.iteration);

            this.actualFiniteStateListService.Setup(x => x.GetShallow(It.IsAny <NpgsqlTransaction>(), "partition", It.Is <IEnumerable <Guid> >(y => y.Contains(this.actualList.Iid)), this.securityContext.Object))
            .Returns(new List <Thing> {
                this.actualList
            });

            this.parameterTypeService.Setup(x => x.GetShallow(this.npgsqlTransaction, "SiteDirectory", null, this.securityContext.Object))
            .Returns(new List <Thing> {
                this.boolPt, this.cptParameterType
            });

            this.parameterTypeService.Setup(x => x.GetShallow(this.npgsqlTransaction, "SiteDirectory", new List <Guid> {
                this.existingNotQuantityKindParameterTypeGuid
            }, this.securityContext.Object))
            .Returns(new List <Thing> {
                new BooleanParameterType(this.existingNotQuantityKindParameterTypeGuid, 1)
            });

            this.parameterTypeService.Setup(x => x.GetShallow(this.npgsqlTransaction, "SiteDirectory", new List <Guid> {
                this.existingQuantityKindParameterTypeGuid
            }, this.securityContext.Object))
            .Returns(new List <Thing> {
                new SimpleQuantityKind(this.existingQuantityKindParameterTypeGuid, 1)
            });

            this.parameterTypeService.Setup(x => x.GetShallow(this.npgsqlTransaction, "SiteDirectory", new List <Guid> {
                this.notExistingParameterTypeGuid
            }, this.securityContext.Object))
            .Returns(new List <Thing>());

            this.parameterTypeComponentService.Setup(x => x.GetShallow(this.npgsqlTransaction, "SiteDirectory", null, this.securityContext.Object))
            .Returns(new List <Thing> {
                this.cpt1, this.cpt2
            });

            this.parameterOverrideService.Setup(x => x.GetShallow(this.npgsqlTransaction, "partition", null, this.securityContext.Object))
            .Returns(new List <Thing> {
                this.parameterOverride
            });

            this.elementUsageService.Setup(x => x.GetShallow(this.npgsqlTransaction, "partition", null, this.securityContext.Object))
            .Returns(new List <Thing> {
                this.elementUsage
            });

            this.scalarDefaultValueArray = new ValueArray <string>(new List <string>()
            {
                "-"
            });
            this.compoundDefaultValueArray = new ValueArray <string>(new List <string>()
            {
                "-", "-"
            });

            this.defaultValueArrayFactory.Setup(x => x.CreateDefaultValueArray(this.cptParameterType.Iid))
            .Returns(this.compoundDefaultValueArray);

            this.defaultValueArrayFactory.Setup(x => x.CreateDefaultValueArray(this.boolPt.Iid))
            .Returns(this.scalarDefaultValueArray);

            this.OldParameterContextProvider.Setup(x => x.GetsourceValueSet(It.IsAny <Guid?>(), It.IsAny <Guid?>())).Returns((ParameterValueSet)null);
        }
        public void Setup()
        {
            this.securityContext = new Mock <ISecurityContext>();
            this.optionService   = new Mock <IOptionService>();
            this.actualFiniteStateListService = new Mock <IActualFiniteStateListService>();
            this.valueSetService  = new Mock <IParameterValueSetService>();
            this.iterationService = new Mock <IIterationService>();
            this.parameterOverrideValueSetService     = new Mock <IParameterOverrideValueSetService>();
            this.parameterSubscriptionValueSetService = new Mock <IParameterSubscriptionValueSetService>();
            this.parameterSubscriptionService         = new Mock <IParameterSubscriptionService>();
            this.parameterOverrideService             = new Mock <IParameterOverrideService>();
            this.elementUsageService         = new Mock <IElementUsageService>();
            this.defaultValueArrayFactory    = new Mock <IDefaultValueArrayFactory>();
            this.OldParameterContextProvider = new Mock <IOldParameterContextProvider>();
            this.cachedReferenceDataService  = new Mock <ICachedReferenceDataService>();

            this.organizationalParticipationResolverService = new Mock <IOrganizationalParticipationResolverService>();
            this.organizationalParticipationResolverService.Setup(x => x.ValidateCreateOrganizationalParticipation(It.IsAny <Thing>(), It.IsAny <Thing>(), It.IsAny <ISecurityContext>(), this.npgsqlTransaction, It.IsAny <string>()));

            this.npgsqlTransaction = null;

            this.iteration = new Iteration(Guid.NewGuid(), 1);
            this.option1   = new Option(Guid.NewGuid(), 1);
            this.option2   = new Option(Guid.NewGuid(), 1);

            this.iteration.Option.Add(new OrderedItem {
                K = 1, V = this.option1.Iid
            });
            this.iteration.Option.Add(new OrderedItem {
                K = 2, V = this.option2.Iid
            });

            this.actualList   = new ActualFiniteStateList(Guid.NewGuid(), 1);
            this.actualState1 = new ActualFiniteState(Guid.NewGuid(), 1);
            this.actualState2 = new ActualFiniteState(Guid.NewGuid(), 1);

            this.actualList.ActualState.Add(this.actualState1.Iid);
            this.actualList.ActualState.Add(this.actualState2.Iid);

            this.parameter = new Parameter(Guid.NewGuid(), 1);

            this.cptParameterType = new CompoundParameterType(Guid.NewGuid(), 1);
            this.boolPt           = new BooleanParameterType(Guid.NewGuid(), 1);
            this.cpt1             = new ParameterTypeComponent(Guid.NewGuid(), 1)
            {
                ParameterType = this.boolPt.Iid
            };
            this.cpt2 = new ParameterTypeComponent(Guid.NewGuid(), 1)
            {
                ParameterType = this.boolPt.Iid
            };

            this.cptParameterType.Component.Add(new OrderedItem {
                K = 1, V = this.cpt1.Iid.ToString()
            });
            this.cptParameterType.Component.Add(new OrderedItem {
                K = 2, V = this.cpt2.Iid.ToString()
            });

            this.sideEffect = new ParameterSideEffect
            {
                IterationService                     = this.iterationService.Object,
                ActualFiniteStateListService         = this.actualFiniteStateListService.Object,
                ParameterValueSetService             = this.valueSetService.Object,
                ParameterOverrideValueSetService     = this.parameterOverrideValueSetService.Object,
                ParameterSubscriptionValueSetService = this.parameterSubscriptionValueSetService.Object,
                ParameterOverrideService             = this.parameterOverrideService.Object,
                ParameterSubscriptionService         = this.parameterSubscriptionService.Object,
                ElementUsageService                  = this.elementUsageService.Object,
                OptionService                              = this.optionService.Object,
                DefaultValueArrayFactory                   = this.defaultValueArrayFactory.Object,
                ParameterValueSetFactory                   = new ParameterValueSetFactory(),
                ParameterOverrideValueSetFactory           = new ParameterOverrideValueSetFactory(),
                ParameterSubscriptionValueSetFactory       = new ParameterSubscriptionValueSetFactory(),
                OldParameterContextProvider                = this.OldParameterContextProvider.Object,
                OrganizationalParticipationResolverService = this.organizationalParticipationResolverService.Object,
                CachedReferenceDataService                 = this.cachedReferenceDataService.Object
            };

            // prepare mock data
            this.elementDefinition = new ElementDefinition(Guid.NewGuid(), 1);
            this.elementDefinition.Parameter.Add(this.parameter.Iid);

            this.parameterOverride = new ParameterOverride(Guid.NewGuid(), 1)
            {
                Parameter = this.parameter.Iid
            };

            this.elementUsage = new ElementUsage(Guid.NewGuid(), 1)
            {
                ElementDefinition = this.elementDefinition.Iid, ParameterOverride = { this.parameterOverride.Iid }
            };

            this.iterationService.Setup(x => x.GetActiveIteration(null, "partition", this.securityContext.Object))
            .Returns(this.iteration);

            this.actualFiniteStateListService.Setup(x => x.GetShallow(It.IsAny <NpgsqlTransaction>(), "partition", It.Is <IEnumerable <Guid> >(y => y.Contains(this.actualList.Iid)), this.securityContext.Object))
            .Returns(new List <Thing> {
                this.actualList
            });

            var parameterTypeDictionary = new Dictionary <Guid, ParameterType>();

            parameterTypeDictionary.Add(this.cptParameterType.Iid, this.cptParameterType);
            parameterTypeDictionary.Add(this.boolPt.Iid, this.boolPt);

            this.cachedReferenceDataService.Setup(x => x.QueryParameterTypes(this.npgsqlTransaction, this.securityContext.Object))
            .Returns(parameterTypeDictionary);

            var parameterTypeComponentDictionary = new Dictionary <Guid, ParameterTypeComponent>();

            parameterTypeComponentDictionary.Add(this.cpt1.Iid, this.cpt1);
            parameterTypeComponentDictionary.Add(this.cpt2.Iid, this.cpt2);

            this.cachedReferenceDataService.Setup(x => x.QueryParameterTypeComponents(this.npgsqlTransaction, this.securityContext.Object))
            .Returns(parameterTypeComponentDictionary);

            this.parameterOverrideService.Setup(x => x.GetShallow(this.npgsqlTransaction, "partition", null, this.securityContext.Object))
            .Returns(new List <Thing> {
                this.parameterOverride
            });

            this.elementUsageService.Setup(x => x.GetShallow(this.npgsqlTransaction, "partition", null, this.securityContext.Object))
            .Returns(new List <Thing> {
                this.elementUsage
            });

            this.scalarDefaultValueArray = new ValueArray <string>(new List <string> {
                "-"
            });
            this.compoundDefaultValueArray = new ValueArray <string>(new List <string> {
                "-", "-"
            });

            this.defaultValueArrayFactory.Setup(x => x.CreateDefaultValueArray(this.cptParameterType.Iid))
            .Returns(this.compoundDefaultValueArray);

            this.defaultValueArrayFactory.Setup(x => x.CreateDefaultValueArray(this.boolPt.Iid))
            .Returns(this.scalarDefaultValueArray);

            this.OldParameterContextProvider.Setup(x => x.GetsourceValueSet(It.IsAny <Guid?>(), It.IsAny <Guid?>())).Returns((ParameterValueSet)null);
        }
        /// <summary>
        /// Create a <see cref="ParameterValueSet"/> with a specific option and state. The old value set is used if it exists, otherwise default values are used
        /// </summary>
        /// <param name="oldValue">The old <see cref="ParameterValueSet"/></param>
        /// <param name="parameter">The current <see cref="Parameter"/></param>
        /// <param name="actualOption">The actual <see cref="CDP4Common.DTO.Option"/></param>
        /// <param name="actualState">The <see cref="ActualFiniteState"/></param>
        /// <param name="transaction">The transaction</param>
        /// <param name="partition">The partition</param>
        /// <param name="securityContext">The security context</param>
        /// <returns>The created <see cref="ParameterValueSet"/></returns>
        private ParameterValueSet CreateParameterValueSet(ParameterValueSet oldValue, Parameter parameter, Guid?actualOption, Guid?actualState, NpgsqlTransaction transaction, string partition, ISecurityContext securityContext)
        {
            this.DefaultValueSetFactory.Load(transaction, securityContext);
            var defaultValue = this.DefaultValueSetFactory.CreateDefaultValueArray(parameter.ParameterType);

            var isOldValueNull = oldValue == null;
            var valueSet       = new ParameterValueSet(Guid.NewGuid(), 1)
            {
                Manual       = new ValueArray <string>(isOldValueNull ? defaultValue : oldValue.Manual),
                Computed     = new ValueArray <string>(isOldValueNull ? defaultValue : oldValue.Computed),
                Reference    = new ValueArray <string>(isOldValueNull ? defaultValue : oldValue.Reference),
                Published    = new ValueArray <string>(isOldValueNull ? defaultValue : oldValue.Published),
                Formula      = new ValueArray <string>(isOldValueNull ? defaultValue : oldValue.Formula),
                ActualOption = actualOption,
                ActualState  = actualState,
                ValueSwitch  = isOldValueNull ? CDP4Common.EngineeringModelData.ParameterSwitchKind.MANUAL : oldValue.ValueSwitch
            };

            this.ParameterValueSetService.CreateConcept(transaction, partition, valueSet, parameter);
            return(valueSet);
        }
Beispiel #16
0
        public async Task AssertThatRevisionsAreCachedCorrectly()
        {
            var assembler = new Assembler(this.uri);

            var parameterIid       = Guid.NewGuid();
            var parameterRevision1 = new Dto.Parameter(parameterIid, 1);  //The Parameter's 1st Revision
            var parameterRevision2 = new Dto.Parameter(parameterIid, 2);  //The Parameter's 2nd Revision
            var parameterRevision3 = new Dto.Parameter(parameterIid, 3);  //The Parameter's 3rd Revision

            var valueSet1 = new Dto.ParameterValueSet(Guid.NewGuid(), 1); //ValueSet that belongs to the parameter's 1st Revision
            var valueSet2 = new Dto.ParameterValueSet(Guid.NewGuid(), 1); //ValueSet that belongs to the parameter's 2nd Revision
            var valueSet3 = new Dto.ParameterValueSet(Guid.NewGuid(), 1); //ValueSet that belongs to the parameter's 3rd Revision

            parameterRevision1.ValueSet.Add(valueSet1.Iid);
            parameterRevision2.ValueSet.Add(valueSet2.Iid);
            parameterRevision3.ValueSet.Add(valueSet3.Iid);

            //******************************************************************************************************************
            // 1st call of Synchronize for Revision 2, which is the currently active revision
            //******************************************************************************************************************
            await assembler.Synchronize(new List <Dto.Thing> {
                parameterRevision2, valueSet2
            });

            //Cache should not be empty
            Assert.IsNotEmpty(assembler.Cache);

            //Cache should contain 2 items
            Assert.AreEqual(2, assembler.Cache.Count);

            //Get the cached version of the parameter
            var cachedParameter = assembler.Cache.First(x => x.Value.Value.Iid == parameterRevision2.Iid).Value.Value as Parameter;

            //Revision number should be 2 now
            Assert.AreEqual(parameterRevision2.RevisionNumber, cachedParameter.RevisionNumber);

            //Parameter should contain a ValueSet
            Assert.AreEqual(1, cachedParameter.ValueSet.Count);

            //Parameter should contain the correct ValueSet
            Assert.AreEqual(cachedParameter.ValueSet.First().Iid, valueSet2.Iid);

            //******************************************************************************************************************
            // 2st call of Synchronize which introduces a newer revision: Revision nr. 3.
            //******************************************************************************************************************
            await assembler.Synchronize(new List <Dto.Thing> {
                parameterRevision3, valueSet3
            });

            //Cache should still contain 2 things, because parameterRevision2 is removed from cache together with valueSet2
            //parameterRevision2 now is contained in the Revisions property of the cached version of the parameter
            Assert.AreEqual(2, assembler.Cache.Count);

            cachedParameter = assembler.Cache.First(x => x.Value.Value.Iid == parameterRevision3.Iid).Value.Value as Parameter;

            //Current cached parameter version is Revision 3
            Assert.AreEqual(parameterRevision3.RevisionNumber, cachedParameter.RevisionNumber);

            //cached parameter should contain a ValueSet
            Assert.AreEqual(1, cachedParameter.ValueSet.Count);

            //cached parameter should contain exactly 1 revision
            Assert.AreEqual(1, cachedParameter.Revisions.Count);

            //cached parameter should contain the correct ValueSet
            Assert.AreEqual(cachedParameter.ValueSet.First().Iid, valueSet3.Iid);

            //Revisions property of current cached item should contain the right revision number
            Assert.AreEqual(cachedParameter.Revisions.First().Value.RevisionNumber, parameterRevision2.RevisionNumber);

            //******************************************************************************************************************
            // 3rd call of Synchronize with older revision, that should be added as a revision to an existing cached poco
            //******************************************************************************************************************
            await assembler.Synchronize(new List <Dto.Thing> {
                parameterRevision1, valueSet1
            });

            //Cache should still contain 2 things, because parameterRevision1 is added to the Revisions property of the current cached parameter
            Assert.AreEqual(2, assembler.Cache.Count);

            cachedParameter = assembler.Cache.First(x => x.Value.Value.Iid == parameterRevision1.Iid).Value.Value as Parameter;

            //parameterRevision3 is still the current cached version
            Assert.AreEqual(parameterRevision3.RevisionNumber, cachedParameter.RevisionNumber);

            //cached parameter should contain a ValueSet
            Assert.AreEqual(1, cachedParameter.ValueSet.Count);

            //cached parameter should contain the correct ValueSet
            Assert.AreEqual(cachedParameter.ValueSet.First().Iid, valueSet3.Iid);

            //cached parameter should contain exactly 2 revisions
            Assert.AreEqual(2, cachedParameter.Revisions.Count);

            var revisionParameter1 = cachedParameter.Revisions.Single(x => x.Value.Iid == parameterRevision1.Iid && x.Value.RevisionNumber == parameterRevision1.RevisionNumber).Value as Parameter;
            var revisionParameter2 = cachedParameter.Revisions.Single(x => x.Value.Iid == parameterRevision2.Iid && x.Value.RevisionNumber == parameterRevision2.RevisionNumber).Value as Parameter;

            //Should be empty, because an older revision than the one currently in the cache was asked for
            //In that case the ValueSet belonging to the Parameter doens't get cloned (because it is unknown at that moment)
            Assert.AreEqual(0, revisionParameter1.ValueSet.Count);

            //Should be 1, because the ValueSet2 was cloned and added to the Parameter added to the Revisions property of the cached parameter
            //when revision 3 was added to the cache
            Assert.AreEqual(1, revisionParameter2.ValueSet.Count);
        }
 public bool Update(NpgsqlTransaction transaction, string partition, Parameter parameter, Thing container = null)
 {
     throw new NotImplementedException();
 }
Beispiel #18
0
        public void VerifyThatAfterUpdateUpdateTheOVerrideAndSubscription()
        {
            var valueset = new ParameterValueSet(Guid.NewGuid(), 0);

            valueset.Manual      = new ValueArray <string>(new[] { "set" });
            valueset.Published   = new ValueArray <string>(new[] { "set" });
            valueset.Computed    = new ValueArray <string>(new[] { "set" });
            valueset.ValueSwitch = ParameterSwitchKind.REFERENCE;

            this.parameter.ValueSet.Add(valueset.Iid);
            this.OldParameterContextProvider.Setup(x => x.GetsourceValueSet(null, It.IsAny <Guid?>())).Returns(valueset);

            var overrideValueSet = new ParameterOverrideValueSet(Guid.NewGuid(), 1);

            overrideValueSet.ParameterValueSet = valueset.Iid;
            overrideValueSet.Manual            = new ValueArray <string>(new[] { "override" });
            overrideValueSet.Published         = new ValueArray <string>(new[] { "override" });
            overrideValueSet.Computed          = new ValueArray <string>(new[] { "override" });
            overrideValueSet.ValueSwitch       = ParameterSwitchKind.REFERENCE;

            this.parameterOverride.ValueSet.Add(overrideValueSet.Iid);

            var subscription1 = new ParameterSubscription(Guid.NewGuid(), 1);
            var subscription2 = new ParameterSubscription(Guid.NewGuid(), 2);

            var subscription1ValueSet = new ParameterSubscriptionValueSet(Guid.NewGuid(), 1);

            subscription1ValueSet.Manual             = new ValueArray <string>(new [] { "sub1" });
            subscription1ValueSet.SubscribedValueSet = valueset.Iid;

            var subscription2ValueSet = new ParameterSubscriptionValueSet(Guid.NewGuid(), 1);

            subscription2ValueSet.Manual             = new ValueArray <string>(new[] { "sub2" });
            subscription2ValueSet.SubscribedValueSet = overrideValueSet.Iid;

            subscription1.ValueSet.Add(subscription1ValueSet.Iid);
            subscription2.ValueSet.Add(subscription2ValueSet.Iid);

            var originalThing = this.parameter.DeepClone <Thing>();

            this.parameterOverride.ParameterSubscription.Add(subscription2.Iid);
            this.parameter.ParameterSubscription.Add(subscription1.Iid);

            this.parameterOverrideService.Setup(
                x => x.GetShallow(this.npgsqlTransaction, "partition", null, this.securityContext.Object))
            .Returns(new List <Thing> {
                this.parameterOverride
            });

            this.parameterSubscriptionService.Setup(x =>
                                                    x.GetShallow(this.npgsqlTransaction, "partition",
                                                                 It.Is <IEnumerable <Guid> >(g => g.Contains(subscription1.Iid) && g.Contains(subscription2.Iid)),
                                                                 this.securityContext.Object))
            .Returns(new List <Thing> {
                subscription1, subscription2
            });

            this.valueSetService.Setup(x => x.DeleteConcept(null, "partition", It.IsAny <ParameterValueSet>(), this.parameter))
            .Returns(true);

            this.parameterOverrideValueSetService
            .Setup(x => x.GetShallow(null, "partition", It.Is <IEnumerable <Guid> >(y => y.Contains(overrideValueSet.Iid)), this.securityContext.Object))
            .Returns(new[] { overrideValueSet });

            this.parameterSubscriptionValueSetService
            .Setup(x => x.GetShallow(null, "partition", It.Is <IEnumerable <Guid> >(y => y.Contains(subscription1ValueSet.Iid)), this.securityContext.Object))
            .Returns(new[] { subscription1ValueSet });

            this.parameterSubscriptionValueSetService
            .Setup(x => x.GetShallow(null, "partition", It.Is <IEnumerable <Guid> >(y => y.Contains(subscription2ValueSet.Iid)), this.securityContext.Object))
            .Returns(new[] { subscription2ValueSet });

            this.parameter.ParameterType   = this.cptParameterType.Iid;
            this.parameter.StateDependence = null;

            var updatedParameter = new Parameter(this.parameter.Iid, 0)
            {
                StateDependence = this.actualList.Iid
            };

            updatedParameter.ValueSet.Add(valueset.Iid);
            updatedParameter.ParameterType = this.cptParameterType.Iid;
            updatedParameter.ParameterSubscription.Add(subscription1.Iid);

            this.sideEffect.AfterUpdate(updatedParameter, this.elementDefinition, originalThing, this.npgsqlTransaction, "partition", this.securityContext.Object);

            this.valueSetService.Verify(x => x.CreateConcept(this.npgsqlTransaction, "partition", It.Is <ParameterValueSet>(y => y.Manual.Contains("set")), updatedParameter, -1),
                                        Times.Exactly(2));

            this.parameterOverrideValueSetService.Verify(x => x.CreateConcept(this.npgsqlTransaction, "partition", It.Is <ParameterOverrideValueSet>(y => y.Manual.Contains("override")), this.parameterOverride, -1),
                                                         Times.Exactly(2));

            this.parameterSubscriptionValueSetService.Verify(x => x.CreateConcept(this.npgsqlTransaction, "partition", It.Is <ParameterSubscriptionValueSet>(y => y.Manual.Contains("sub1")), subscription1, -1),
                                                             Times.Exactly(2));

            this.parameterSubscriptionValueSetService.Verify(x => x.CreateConcept(this.npgsqlTransaction, "partition", It.Is <ParameterSubscriptionValueSet>(y => y.Manual.Contains("sub2")), subscription2, -1),
                                                             Times.Exactly(2));
        }