Beispiel #1
0
 /// <inheritdoc cref="ITransformResponseBuilder.WithTransformer(TransformerType, bool)"/>
 public IResponseBuilder WithTransformer(TransformerType transformerType, bool transformContentFromBodyAsFile = false)
 {
     UseTransformer              = true;
     TransformerType             = transformerType;
     UseTransformerForBodyAsFile = transformContentFromBodyAsFile;
     return(this);
 }
Beispiel #2
0
 public void MarkAsWinner(TransformerBattleModel autobotsTransformer, TransformerBattleModel decepticonsTransformer,
                          TransformerType transformerType)
 {
     autobotsTransformer.TransformerBattleStatus = transformerType == TransformerType.A ?
                                                   TransformerBattleStatus.Winned : TransformerBattleStatus.Losed;
     decepticonsTransformer.TransformerBattleStatus = transformerType == TransformerType.D ?
                                                      TransformerBattleStatus.Winned : TransformerBattleStatus.Losed;
 }
        public ScribanContextFactory(IFileSystemHandler fileSystemHandler, TransformerType transformerType)
        {
            Check.NotNull(fileSystemHandler, nameof(fileSystemHandler));
            Check.Condition(transformerType, t => t == TransformerType.Scriban || t == TransformerType.ScribanDotLiquid, nameof(transformerType));

            _fileSystemHandler = fileSystemHandler;
            _transformerType   = transformerType;
        }
Beispiel #4
0
        public TransformerTypeViewModel(IServiceUnitOfWork serviceUnitOfWork, TransformerType transformerType)
        {
            this.serviceUnitOfWork = serviceUnitOfWork;
            oldTransformerType     = transformerType;
            TransformerType newTransformerType = new TransformerType();

            newTransformerType.Name = transformerType.Name;
            TransformerType         = newTransformerType;
        }
Beispiel #5
0
 /// <inheritdoc/>
 public IItemMenu CreateItems(TransformerType transformerType)
 {
     return(transformerType switch
     {
         TransformerType.Tm => new TmnItemMenu(),
         TransformerType.Tmn => new TmnItemMenu(),
         TransformerType.Tmg => new TmgItemMenu(),
         TransformerType.Tmpng => new TmpngItemMenu(),
         _ => throw new ArgumentOutOfRangeException(nameof(transformerType), transformerType, null)
     });
        public void Create_With_Scriban_TransformerType_Creates_ITransformerContext(TransformerType transformerType)
        {
            // Arrange
            var sut = new ScribanContextFactory(_fileSystemHandlerMock.Object, transformerType);

            // Act
            var result = sut.Create();

            // Assert
            result.Should().NotBeNull();
        }
Beispiel #7
0
            public static Transformer CreateTransformer(TransformerType transformerType, Weapon weapon, Scanner scanner)
            {
                Transformer transformer = transformerType switch
                {
                    TransformerType.OptimusPrime => new OptimusPrime(weapon, scanner),
                    TransformerType.AutoBotX5 => new AutoBotX5(weapon, scanner),
                    _ => throw new ArgumentOutOfRangeException($"No implementation for this type {transformerType}.")
                };

                return(transformer);
            }
Beispiel #8
0
        public async Task ImportForeignTransformerTypes(WRLDCWarehouseDbContext _context, ILogger _log, string oracleConnStr, EntityWriteOption opt)
        {
            TransformerTypeExtract transTypeExtract = new TransformerTypeExtract();
            List <TransformerType> transTypes       = transTypeExtract.ExtractTransformerTypes(oracleConnStr);

            LoadTransformerType loadTrType = new LoadTransformerType();

            foreach (TransformerType trType in transTypes)
            {
                TransformerType insertedTrType = await loadTrType.LoadSingleAsync(_context, _log, trType, opt);
            }
        }
Beispiel #9
0
        public async Task Response_ProvideResponse_Scriban_WithBodyAsFile(TransformerType transformerType)
        {
            // Assign
            var request = new RequestMessage(new UrlDetails("http://localhost/foo?MyUniqueNumber=1"), "GET", ClientIp);

            var response = Response.Create()
                           .WithTransformer(transformerType)
                           .WithBodyFromFile(@"c:\\{{request.query.MyUniqueNumber}}\\test.xml");

            // Act
            var responseMessage = await response.ProvideResponseAsync(request, _settings);

            // Assert
            Check.That(responseMessage.BodyData.BodyAsFile).Equals(@"c:\1\test.xml");
        }
Beispiel #10
0
        public async Task Response_ProvideResponse_Transformer_UrlPath(TransformerType transformerType, string httpMethod)
        {
            // Assign
            var urlDetails = UrlUtils.Parse(new Uri("http://localhost/wiremock/a/b"), new PathString("/wiremock"));
            var request    = new RequestMessage(urlDetails, httpMethod, ClientIp);

            var response = Response.Create()
                           .WithBody("url={{request.Url}} absoluteurl={{request.AbsoluteUrl}} path={{request.Path}} absolutepath={{request.AbsolutePath}}")
                           .WithTransformer(transformerType);

            // Act
            var responseMessage = await response.ProvideResponseAsync(request, _settings);

            // Assert
            Check.That(responseMessage.BodyData.BodyAsString).Equals("url=http://localhost/a/b absoluteurl=http://localhost/wiremock/a/b path=/a/b absolutepath=/wiremock/a/b");
        }
Beispiel #11
0
        public async Task Response_ProvideResponse_Scriban_PathSegments(TransformerType transformerType)
        {
            // Assign
            var urlDetails = UrlUtils.Parse(new Uri("http://localhost/wiremock/a/b"), new PathString("/wiremock"));
            var request    = new RequestMessage(urlDetails, "POST", ClientIp);

            var response = Response.Create()
                           .WithBody("{{request.PathSegments.[0]}} {{request.AbsolutePathSegments.[0]}}")
                           .WithTransformer(transformerType);

            // Act
            var responseMessage = await response.ProvideResponseAsync(request, _settings);

            // Assert
            Check.That(responseMessage.BodyData.BodyAsString).Equals("a wiremock");
        }
 private static IWebhook InitWebhook(
     string url,
     string method,
     IDictionary <string, WireMockList <string> > headers,
     bool useTransformer,
     TransformerType transformerType)
 {
     return(new Webhook
     {
         Request = new WebhookRequest
         {
             Url = url,
             Method = method ?? "post",
             Headers = headers,
             UseTransformer = useTransformer,
             TransformerType = transformerType
         }
     });
 }
Beispiel #13
0
        public async Task Response_ProvideResponse_Transformer_UrlPathVerb(TransformerType transformerType)
        {
            // Assign
            var body = new BodyData
            {
                BodyAsString     = "whatever",
                DetectedBodyType = BodyType.String
            };
            var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POSt", ClientIp, body);

            var response = Response.Create()
                           .WithBody("test {{request.Url}} {{request.Path}} {{request.Method}}")
                           .WithTransformer(transformerType);

            // Act
            var responseMessage = await response.ProvideResponseAsync(request, _settings);

            // Assert
            Check.That(responseMessage.BodyData.BodyAsString).Equals("test http://localhost/foo /foo POSt");
        }
Beispiel #14
0
        public async Task Response_ProvideResponse_Scriban_Query(TransformerType transformerType)
        {
            // Assign
            var body = new BodyData
            {
                BodyAsString     = "abc",
                DetectedBodyType = BodyType.String
            };
            var request = new RequestMessage(new UrlDetails("http://localhost/foo?a=1&a=2&b=5"), "POST", ClientIp, body);

            var response = Response.Create()
                           .WithBody("test keya={{request.query.a}} idx={{request.query.a.[0]}} idx={{request.query.a.[1]}} keyb={{request.query.b}}")
                           .WithTransformer(transformerType);

            // Act
            var responseMessage = await response.ProvideResponseAsync(request, _settings);

            // Assert
            Check.That(responseMessage.BodyData.BodyAsString).Equals("test keya=1 idx=1 idx=2 keyb=5");
        }
Beispiel #15
0
        public async Task Response_ProvideResponse_Transformer_StatusCodeIsNull(TransformerType transformerType)
        {
            // Assign
            var body = new BodyData
            {
                BodyAsString     = "abc",
                DetectedBodyType = BodyType.String
            };
            var request = new RequestMessage(new UrlDetails("http://localhost/foo?a=400"), "POST", ClientIp, body);

            var response = Response.Create()
                           .WithBody("test")
                           .WithTransformer(transformerType);

            // Act
            var responseMessage = await response.ProvideResponseAsync(request, _settings);

            // Assert
            Check.That(responseMessage.BodyData.BodyAsString).Equals("test");
            Check.That(responseMessage.StatusCode).Equals(null);
        }
Beispiel #16
0
        private static ICryptoTransform GetCryptoTransformer(TransformerType transformerType, byte[] encryptionKey)
        {
            using (var aes = Aes.Create())
            {
                aes.BlockSize = 128;
                aes.KeySize   = 256;
                aes.IV        = new byte[16];
                aes.Key       = encryptionKey.GetHash <SHA256Managed>();

                switch (transformerType)
                {
                case TransformerType.Encript:
                    return(aes.CreateEncryptor());

                case TransformerType.Decript:
                    return(aes.CreateDecryptor());

                default:
                    throw new ArgumentOutOfRangeException(nameof(transformerType), transformerType, null);
                }
            }
        }
        /// <see cref="IRespondWithAProvider.WithWebhook(string, string, IDictionary{string, WireMockList{string}}, object, bool, TransformerType)"/>
        public IRespondWithAProvider WithWebhook(
            [NotNull] string url,
            [CanBeNull] string method = "post",
            [CanBeNull] IDictionary <string, WireMockList <string> > headers = null,
            [CanBeNull] object body         = null,
            bool useTransformer             = true,
            TransformerType transformerType = TransformerType.Handlebars)
        {
            Webhooks = new[] { InitWebhook(url, method, headers, useTransformer, transformerType) };

            if (body != null)
            {
                Webhooks[0].Request.BodyData = new BodyData
                {
                    BodyAsJson       = body,
                    DetectedBodyType = BodyType.Json,
                    DetectedBodyTypeFromContentType = BodyType.Json
                };
            }

            return(this);
        }
Beispiel #18
0
        public async Task Response_ProvideResponse_Scriban_Headers(TransformerType transformerType)
        {
            // Assign
            var body = new BodyData
            {
                BodyAsString     = "abc",
                DetectedBodyType = BodyType.String
            };
            var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body, new Dictionary <string, string[]> {
                { "Content-Type", new[] { "text/plain" } }
            });

            var response = Response.Create().WithHeader("x", "{{request.Headers[\"Content-Type\"]}}", "{{request.Url}}").WithBody("test").WithTransformer(transformerType);

            // Act
            var responseMessage = await response.ProvideResponseAsync(request, _settings);

            // Assert
            Check.That(responseMessage.BodyData.BodyAsString).Equals("test");
            Check.That(responseMessage.Headers).ContainsKey("x");
            Check.That(responseMessage.Headers["x"]).Contains("text/plain");
            Check.That(responseMessage.Headers["x"]).Contains("http://localhost/foo");
        }
Beispiel #19
0
        public async Task <TransformerType> LoadSingleAsync(WRLDCWarehouseDbContext _context, ILogger _log, TransformerType transType, EntityWriteOption opt)
        {
            // check if entity already exists
            TransformerType existingTrType = await _context.TransformerTypes.SingleOrDefaultAsync(trT => trT.WebUatId == transType.WebUatId);

            // check if we have to replace the entity completely
            if (opt == EntityWriteOption.Replace && existingTrType != null)
            {
                _context.TransformerTypes.Remove(existingTrType);
            }

            // if entity is not present, then insert or check if we have to replace the entity completely
            if (existingTrType == null || (opt == EntityWriteOption.Replace && existingTrType != null))
            {
                _context.TransformerTypes.Add(transType);
                await _context.SaveChangesAsync();

                return(transType);
            }

            // check if we should not modify existing entities
            if (opt == EntityWriteOption.DontReplace && existingTrType != null)
            {
                return(existingTrType);
            }

            // check if we have to modify the entity
            if (opt == EntityWriteOption.Modify && existingTrType != null)
            {
                existingTrType.Name = transType.Name;
                await _context.SaveChangesAsync();

                return(existingTrType);
            }
            return(null);
        }
Beispiel #20
0
 public void Delete(TransformerType t)
 {
     dataBase.TransformerTypes.Delete(t);
     dataBase.Save();
 }
Beispiel #21
0
        public async Task Response_ProvideResponse_Transformer_Origin_Port_Protocol_Host(TransformerType transformerType)
        {
            // Assign
            var body = new BodyData
            {
                BodyAsString     = "abc",
                DetectedBodyType = BodyType.String
            };
            var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);

            var response = Response.Create()
                           .WithBody("test {{request.Origin}} {{request.Port}} {{request.Protocol}} {{request.Host}}")
                           .WithTransformer(transformerType);

            // Act
            var responseMessage = await response.ProvideResponseAsync(request, _settings);

            // Assert
            Check.That(responseMessage.BodyData.BodyAsString).Equals("test http://localhost:1234 1234 http localhost");
        }
Beispiel #22
0
        public async Task Response_ProvideResponse_Transformer_WithBodyAsJson_ResultAsObject(TransformerType transformerType)
        {
            // Assign
            string jsonString = "{ \"things\": [ { \"name\": \"RequiredThing\" }, { \"name\": \"Wiremock\" } ] }";
            var    bodyData   = new BodyData
            {
                BodyAsJson       = JsonConvert.DeserializeObject(jsonString),
                DetectedBodyType = BodyType.Json,
                Encoding         = Encoding.UTF8
            };
            var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);

            var responseBuilder = Response.Create()
                                  .WithBodyAsJson(new { x = "test {{request.Path}}" })
                                  .WithTransformer(transformerType);

            // Act
            var response = await responseBuilder.ProvideResponseAsync(request, _settings);

            // Assert
            Check.That(JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson)).Equals("{\"x\":\"test /foo_object\"}");
        }
Beispiel #23
0
 public void Update(TransformerType t)
 {
     dataBase.TransformerTypes.Update(t);
     dataBase.Save();
 }
Beispiel #24
0
        public async Task <Transformer> LoadSingleAsync(WRLDCWarehouseDbContext _context, ILogger _log, TransformerForeign trForeign, EntityWriteOption opt)
        {
            // check if entity already exists
            Transformer existingTr = await _context.Transformers.SingleOrDefaultAsync(tr => tr.WebUatId == trForeign.WebUatId);

            // check if we should not modify existing entities
            if (opt == EntityWriteOption.DontReplace && existingTr != null)
            {
                return(existingTr);
            }

            // check if substation type is valid
            string ssTypeSubstation = "SubStation";
            string ssTypeGenStation = "Generating Station";

            if (!(trForeign.StationType == ssTypeSubstation || trForeign.StationType == ssTypeGenStation))
            {
                _log.LogCritical($"substation type is not {ssTypeSubstation} or {ssTypeGenStation} while inserting Transformer with webUatId {trForeign.WebUatId} and name {trForeign.Name}");
                return(null);
            }

            MajorSubstation hvSubstation         = null;
            int             hvSubstationWebUatId = -1;

            if (trForeign.StationType == ssTypeSubstation)
            {
                // The transformer is in Substation
                hvSubstationWebUatId = trForeign.HVStationWebUatId;
                hvSubstation         = await _context.MajorSubstations.SingleOrDefaultAsync(hvss => hvss.WebUatId == hvSubstationWebUatId);

                if (hvSubstation == null)
                {
                    _log.LogCritical($"Unable to find MajorSubstation with webUatId {hvSubstationWebUatId} while inserting Transformer with webUatId {trForeign.WebUatId} and name {trForeign.Name}");
                    return(null);
                }
            }

            GeneratingStation hvGenStation = null;
            int hvGenstationWebUatId       = -1;

            if (trForeign.StationType == ssTypeGenStation)
            {
                // The transformer is in GeneratingStation
                hvGenstationWebUatId = trForeign.HVStationWebUatId;
                hvGenStation         = await _context.GeneratingStations.SingleOrDefaultAsync(hvgt => hvgt.WebUatId == hvGenstationWebUatId);

                if (hvGenStation == null)
                {
                    _log.LogCritical($"Unable to find GeneratingStation with webUatId {hvGenstationWebUatId} while inserting Transformer with webUatId {trForeign.WebUatId} and name {trForeign.Name}");
                    return(null);
                }
            }

            // find the HV Voltage of the Transformer via the Voltage WebUatId
            int       hvVoltWebUatId = trForeign.HighVoltLevelWebUatId;
            VoltLevel hvVolt         = await _context.VoltLevels.SingleOrDefaultAsync(vl => vl.WebUatId == hvVoltWebUatId);

            // if voltage level doesnot exist, skip the import. Ideally, there should not be such case
            if (hvVolt == null)
            {
                _log.LogCritical($"Unable to find HV VoltLevel with webUatId {hvVoltWebUatId} while inserting Transformer with webUatId {trForeign.WebUatId} and name {trForeign.Name}");
                return(null);
            }

            // find the LV Voltage of the Transformer via the Voltage WebUatId
            int       lvVoltWebUatId = trForeign.LowVoltLevelWebUatId;
            VoltLevel lvVolt         = await _context.VoltLevels.SingleOrDefaultAsync(vl => vl.WebUatId == lvVoltWebUatId);

            // if voltage level doesnot exist, skip the import. Ideally, there should not be such case
            if (lvVolt == null)
            {
                _log.LogCritical($"Unable to find LV VoltLevel with webUatId {lvVoltWebUatId} while inserting Transformer with webUatId {trForeign.WebUatId} and name {trForeign.Name}");
                // uncomment this after vendor complies for non null LV voltage types
                // return null;
            }

            // find the State of the substation via the State WebUatId
            int   stateWebUatId = trForeign.StateWebUatId;
            State state         = await _context.States.SingleOrDefaultAsync(s => s.WebUatId == stateWebUatId);

            // if state doesnot exist, skip the import. Ideally, there should not be such case
            if (state == null)
            {
                _log.LogCritical($"Unable to find State with webUatId {stateWebUatId} while inserting Transformer with webUatId {trForeign.WebUatId} and name {trForeign.Name}");
                return(null);
            }

            // find the TransformerType of the Transformer via the TransformerTypeWebUatId
            int             trTypeWebUatId = trForeign.TransTypeWebUatId;
            TransformerType trType         = await _context.TransformerTypes.SingleOrDefaultAsync(trt => trt.WebUatId == trTypeWebUatId);

            // if TransformerType doesnot exist, skip the import. Ideally, there should not be such case
            if (trType == null)
            {
                _log.LogCritical($"Unable to find TransformerType with webUatId {trTypeWebUatId} while inserting Transformer with webUatId {trForeign.WebUatId} and name {trForeign.Name}");
                return(null);
            }

            // check if we have to replace the entity completely
            if (opt == EntityWriteOption.Replace && existingTr != null)
            {
                _context.Transformers.Remove(existingTr);
            }

            // if entity is not present, then insert or check if we have to replace the entity completely
            if (existingTr == null || (opt == EntityWriteOption.Replace && existingTr != null))
            {
                Transformer newTr = new Transformer();
                newTr.Name            = trForeign.Name;
                newTr.StationType     = trForeign.StationType;
                newTr.HighVoltLevelId = hvVolt.VoltLevelId;
                if (lvVolt != null)
                {
                    newTr.LowVoltLevelId = lvVolt.VoltLevelId;
                }
                newTr.TransformerNumber = trForeign.TransformerNumber;
                newTr.TransformerTypeId = trType.TransformerTypeId;
                newTr.StateId           = state.StateId;
                newTr.MVACapacity       = trForeign.MVACapacity;
                newTr.CodDate           = trForeign.CodDate;
                newTr.CommDate          = trForeign.CommDate;
                newTr.DecommDate        = trForeign.DecommDate;
                newTr.WebUatId          = trForeign.WebUatId;
                if (trForeign.StationType == ssTypeSubstation)
                {
                    newTr.HvSubstationId = hvSubstation.MajorSubstationId;
                }
                else if (trForeign.StationType == ssTypeGenStation)
                {
                    newTr.HvGeneratingStationId = hvGenStation.GeneratingStationId;
                }

                _context.Transformers.Add(newTr);
                await _context.SaveChangesAsync();

                return(newTr);
            }

            // check if we have to modify the entity
            if (opt == EntityWriteOption.Modify && existingTr != null)
            {
                existingTr.Name            = trForeign.Name;
                existingTr.StationType     = trForeign.StationType;
                existingTr.HighVoltLevelId = hvVolt.VoltLevelId;
                if (lvVolt != null)
                {
                    existingTr.LowVoltLevelId = lvVolt.VoltLevelId;
                }
                existingTr.TransformerNumber = trForeign.TransformerNumber;
                existingTr.TransformerTypeId = trType.TransformerTypeId;
                existingTr.StateId           = state.StateId;
                existingTr.MVACapacity       = trForeign.MVACapacity;
                existingTr.CodDate           = trForeign.CodDate;
                existingTr.CommDate          = trForeign.CommDate;
                existingTr.DecommDate        = trForeign.DecommDate;
                if (trForeign.StationType == ssTypeSubstation)
                {
                    existingTr.HvSubstationId = hvSubstation.MajorSubstationId;
                }
                else if (trForeign.StationType == ssTypeGenStation)
                {
                    existingTr.HvGeneratingStationId = hvGenStation.GeneratingStationId;
                }
                await _context.SaveChangesAsync();

                return(existingTr);
            }
            return(null);
        }
Beispiel #25
0
    public void PlayOnce(TransformerType type)
    {
        switch (type)
        {
        case TransformerType.Position:
            currentPositioner?.Kill();
            transform.localPosition = !positioner.IsReverting ? startPosition : transform.localPosition + positioner.Target;

            currentPositioner = transform
                                .DOLocalMove(!positioner.IsReverting ? transform.localPosition + positioner.Target : startPosition, positioner.Duration)
                                .SetEase(positioner.Ease)
                                .SetUpdate(UpdateType.Normal, positioner.IsIgnoringTime)
                                .Play();
            break;

        case TransformerType.Rotation:

            currentRotater?.Kill();

            Vector3 target = !rotater.IsReverting ?
                             new Vector3(transform.localRotation.x, transform.localRotation.y, transform.localRotation.z + rotationAmplitudeFactor * rotater.AngleTarget) :
                             startRotation;

            if (rotater.HasFullAmplitude)
            {
                transform.localRotation = !rotater.IsReverting ?
                                          Quaternion.Euler(new Vector3(startRotation.x, startRotation.y, startRotation.z - rotater.AngleTarget)) :
                                          Quaternion.Euler(target);

                currentRotater = transform
                                 .DORotate(target, rotater.Duration, RotateMode.FastBeyond360)
                                 .SetEase(rotater.Ease)
                                 .SetRelative()
                                 .SetUpdate(UpdateType.Normal, rotater.IsIgnoringTime)
                                 .Play();
            }
            else
            {
                transform.localRotation = !rotater.IsReverting ?
                                          Quaternion.Euler(new Vector3(startRotation.x, startRotation.y, startRotation.z)) :
                                          Quaternion.Euler(target);

                currentRotater = transform
                                 .DORotate(target, rotater.Duration, RotateMode.FastBeyond360)
                                 .SetEase(rotater.Ease)
                                 .SetRelative()
                                 .SetUpdate(UpdateType.Normal, rotater.IsIgnoringTime)
                                 .Play();
            }

            break;

        case TransformerType.Scale:
            currentScaler?.Kill();

            float currentFactor = scaler.Factor.RandomValue;
            transform.localScale = !scaler.IsReverting ? startScale : startScale * currentFactor;

            currentScaler = transform
                            .DOScale(!scaler.IsReverting ? startScale * currentFactor : startScale, scaler.Duration)
                            .SetEase(scaler.Ease)
                            .SetUpdate(UpdateType.Normal, scaler.IsIgnoringTime)
                            .Play();
            break;
        }
    }
Beispiel #26
0
        //[InlineData(TransformerType.Scriban)] Scriban cannot access dynamic Json Objects
        //[InlineData(TransformerType.ScribanDotLiquid)]
        public async Task Response_ProvideResponse_Transformer_WithBodyAsJson_ResultAsArray(TransformerType transformerType)
        {
            // Assign
            string jsonString = "{ \"a\": \"test 1\", \"b\": \"test 2\" }";
            var    bodyData   = new BodyData
            {
                BodyAsJson       = JsonConvert.DeserializeObject(jsonString),
                DetectedBodyType = BodyType.Json,
                Encoding         = Encoding.UTF8
            };
            var request = new RequestMessage(new UrlDetails("http://localhost/foo_array"), "POST", ClientIp, bodyData);

            var response = Response.Create()
                           .WithBodyAsJson(new[] { "first", "{{request.path}}", "{{request.bodyAsJson.a}}", "{{request.bodyAsJson.b}}", "last" })
                           .WithTransformer(transformerType);

            // Act
            var responseMessage = await response.ProvideResponseAsync(request, _settings);

            // Assert
            Check.That(JsonConvert.SerializeObject(responseMessage.BodyData.BodyAsJson)).Equals("[\"first\",\"/foo_array\",\"test 1\",\"test 2\",\"last\"]");
        }
Beispiel #27
0
        public async Task Response_ProvideResponse_Transformer_WithNullBody_ShouldNotThrowException(TransformerType transformerType)
        {
            // Assign
            var urlDetails = UrlUtils.Parse(new Uri("http://localhost/wiremock/a/b"), new PathString("/wiremock"));
            var request    = new RequestMessage(urlDetails, "GET", ClientIp);

            var response = Response.Create().WithTransformer(transformerType);

            // Act
            var responseMessage = await response.ProvideResponseAsync(request, _settings);

            // Assert
            responseMessage.BodyData.Should().BeNull();
        }
Beispiel #28
0
        public async Task Response_ProvideResponse_Transformer_WithBodyAsString_KeepsEncoding(TransformerType transformerType)
        {
            // Assign
            const string text     = "my-text";
            Encoding     enc      = Encoding.Unicode;
            var          bodyData = new BodyData
            {
                BodyAsString     = text,
                DetectedBodyType = BodyType.String,
                Encoding         = enc
            };
            var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);

            var response = Response.Create()
                           .WithBody("{{request.Body}}", BodyDestinationFormat.SameAsSource, enc)
                           .WithTransformer(transformerType);

            // Act
            var responseMessage = await response.ProvideResponseAsync(request, _settings);

            // Assert
            responseMessage.BodyData.BodyAsString.Should().Be(text);
            responseMessage.BodyData.Encoding.Should().Be(enc);
        }
Beispiel #29
0
        public async Task Response_ProvideResponse_Scriban_WithBodyAsJson_ResultAsTemplatedString(TransformerType transformerType)
        {
            // Assign
            string jsonString = "{ \"name\": \"WireMock\" }";
            var    bodyData   = new BodyData
            {
                BodyAsJson       = JsonConvert.DeserializeObject(jsonString),
                DetectedBodyType = BodyType.Json,
                Encoding         = Encoding.UTF8
            };
            var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);

            var response = Response.Create()
                           .WithBodyAsJson("{{{request.BodyAsJson}}}")
                           .WithTransformer(transformerType);

            // Act
            var responseMessage = await response.ProvideResponseAsync(request, _settings);

            // Assert
            Check.That(JsonConvert.SerializeObject(responseMessage.BodyData.BodyAsJson)).Equals("{\"name\":\"WireMock\"}");
        }
Beispiel #30
0
        //[InlineData(TransformerType.Scriban)] ["c:\\["1"]\\test.xml"]
        //[InlineData(TransformerType.ScribanDotLiquid)]
        public async Task Response_ProvideResponse_Transformer_WithBodyAsFile_And_TransformContentFromBodyAsFile(TransformerType transformerType)
        {
            // Assign
            var filesystemHandlerMock = new Mock <IFileSystemHandler>(MockBehavior.Strict);

            filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny <string>())).Returns("<xml MyUniqueNumber=\"{{request.query.MyUniqueNumber}}\"></xml>");

            _settings.FileSystemHandler = filesystemHandlerMock.Object;

            var request = new RequestMessage(new UrlDetails("http://localhost/foo?MyUniqueNumber=1"), "GET", ClientIp);

            var response = Response.Create()
                           .WithTransformer(transformerType, true)
                           .WithBodyFromFile(@"c:\\{{request.query.MyUniqueNumber}}\\test.xml");

            // Act
            var responseMessage = await response.ProvideResponseAsync(request, _settings);

            // Assert
            Check.That(responseMessage.BodyData.BodyAsFile).Equals(@"c:\1\test.xml");
            Check.That(responseMessage.BodyData.DetectedBodyType).Equals(BodyType.String);
            Check.That(responseMessage.BodyData.BodyAsString).Equals("<xml MyUniqueNumber=\"1\"></xml>");
        }