Compare commits

...

41 Commits

Author SHA1 Message Date
Stef Heyenrath
beaf93d035 Merge branch 'master' into webapp 2019-05-04 10:42:25 +02:00
Stef Heyenrath
a7fbc051c9 1.0.15.0 2019-05-04 10:41:42 +02:00
Stef Heyenrath
6e45255c9e Dynamic response handlebars templating (2) (#273)
* Dynamic response files using Handlebars templating
(#270)

* * Response templating / transformation using Handlebars and extensions

* Add unit test for JsonPath and BodyAsFile mapping (#272)

* fix merge issue
2019-05-04 10:20:36 +02:00
Stef Heyenrath
96e68ae2a0 Support Dynamic response files using Handlebars templating (#271)
* Dynamic response files using Handlebars templating
(#270)

* * Response templating / transformation using Handlebars and extensions
2019-05-04 10:02:09 +02:00
Stef Heyenrath
b151a581cc 1.0.14.0 2019-04-20 10:49:37 +02:00
Stef Heyenrath
fdb58b757b Add JmesPath matcher (#269)
* JmesPathMatcher

* netstandard1.3

* update System.Linq.Dynamic.Core

* simplyfy `double IsMatch(object input)`
2019-04-20 10:44:13 +02:00
Stef Heyenrath
dd115a69b7 1.0.13.0 2019-04-11 12:30:00 +02:00
JackCreativeCrew
12444cc11e [265] Add file upload to allow mocking of file operations (#266)
* [265] Add file upload to allow mocking of file operations

* [265] Fix failing test

* Update code + add tests

* LocalFileSystemHandlerTests

* 1.0.13

* Fixed the file post to create the mapping folder if none exists to begin with, otherwise the file upload fails with 404 (can't find the folder to upload to).

* fix tests

* add more tests for LocalFileSystemHandler

* Added the head method for files to check if a file exists without returning it as a body.

* Add a test and fix the response message (head requires no body).

* Fix newline

* Fix newline.

* Fix the number of mapping tests

* Update tests and update client-interface-api

* Cleanup "MappingConverter.cs"
2019-04-11 08:46:14 +02:00
Stef Heyenrath
10a21dbc57 webapp (work in progress) 2019-04-08 07:41:32 +02:00
Stef Heyenrath
6c32b9c31a 1.0.12.0 2019-04-05 15:15:22 +02:00
Stef Heyenrath
3d845d5be5 Proxy : also save multipart as string in mapping file (#264)
* ExactObjectMatcher

* BytesEncodingUtils

* BodyParser

* Encoding.ASCII
2019-04-05 14:51:29 +02:00
Stef Heyenrath
409d55350f 1.0.11.0 2019-03-30 09:47:28 +01:00
Alex Kursov
e7ac620721 Add ProvideResponse_WithJsonBodyAndTransform test (#262) 2019-03-30 09:34:13 +01:00
Alex Kursov
ceb6596823 Fix ResponseMessageTransformer to not replace BodyAsJson in an original message (#261)
Fix ResponseMessageTransformer to not replace BodyAsJson in an original message with transformed results
2019-03-30 09:33:49 +01:00
Stef Heyenrath
47e599214f 1.0.10.0 2019-03-27 08:34:30 +01:00
Stef Heyenrath
b99e300acf Fix Response.Delay property serialization (#260)
* Fix Response.Delay property serialization issue

* Fix Response.Delay
2019-03-27 08:26:55 +01:00
Stef Heyenrath
482b05fc4a 1.0.9.0 2019-03-25 18:26:07 +01:00
Stef Heyenrath
9e123fbbea Fixed Multi Param Match logic (#256)
* fix?

* 1.0.9

* <PackageReference Include="System.Linq.Dynamic.Core" Version="1.0.11" />

* fix tests ?

* fix

* RequestMessageParamMatcher
2019-03-25 18:00:22 +01:00
Stef Heyenrath
658f74ac61 1.0.8.0 2019-03-12 15:18:42 +01:00
Stef Heyenrath
1392119f9d RequestMessageParamMatcher supports Ignore Case for the key (#254)
* RequestMessageParamMatcher

* /o:

* 1.0.8
2019-03-12 14:42:52 +01:00
Stef Heyenrath
62550b61e8 1.0.7.0 2019-01-19 19:33:35 +01:00
Stef Heyenrath
d736745aff Fix BodyAsFile to also allow relative paths (#244)
* Read only .json files as static mapping files and fix current folder for BodyAsFile

* include .json again

* LocalFileSystemHandler_ReadResponseBodyAsFile_Throws

* Read array from static mappings folder

* xml soap example
2019-01-19 19:27:48 +01:00
Stef Heyenrath
34abd05d19 1.0.6.1 2019-01-10 11:48:42 +01:00
Stef Heyenrath
f9ab43bf58 Fixed "Content-Type multipart/form-data" (#249) 2019-01-10 11:24:58 +01:00
Alexander Paul
62823688a3 Issue 225 - Improve logging in example for WireMock as Windows Service (#247) 2018-12-26 14:08:04 +01:00
Stef Heyenrath
33f40c0e84 1.0.6 2018-12-15 09:34:58 +01:00
Stef Heyenrath
98097a033e Post multiple Mappings (#242)
* Post multiple Mappings

* 1.0.6
2018-12-15 09:28:14 +01:00
Stef Heyenrath
d654ef97dc 1.0.5 2018-12-07 09:08:39 +01:00
Stef Heyenrath
4be1483a5f Add Random Regex (using Fare) (#236)
* Xeger

* update example

* 1.0.7

* Fix tests for Handlebars_Xeger

* ReplaceNodeValue

* 1.0.5

* readme
2018-12-06 14:29:12 +01:00
Stef Heyenrath
cd200a10a4 1.0.4.21 2018-11-30 13:00:07 +01:00
Stef Heyenrath
dc36da45ec Check aggregate exception during startup (#235) 2018-11-30 12:52:21 +01:00
Stef Heyenrath
c89b3886dd Merge pull request #233 from WireMock-Net/RandomDataGenerator
RandomDataGenerator.Net 1.0.4
2018-11-21 11:59:02 +01:00
Stef Heyenrath
65734e9c3d RandomDataGenerator.Net 1.0.4 2018-11-21 08:19:39 +01:00
Stef Heyenrath
1ca7d8abb2 Merge remote-tracking branch 'origin/master' 2018-11-20 15:02:29 +01:00
Stef Heyenrath
bcb03a5a9b update /random example 2018-11-15 15:38:42 +01:00
Stef Heyenrath
c1c45801b5 Add SonarLint checks (#232) 2018-11-15 14:30:51 +00:00
Stef Heyenrath
18af7a41d4 Use RandomDataGenerator.Net 1.0.3.0 (#231)
* Include="RandomDataGenerator.Net" Version="1.0.3"

* UndefinedBindingResult
2018-11-13 09:49:46 +00:00
Stef Heyenrath
ac2ecd112f Remove GitHubReleaseNotes.exe 2018-11-09 11:47:56 +01:00
Stef Heyenrath
3df4161329 Add HandleBars Random functionality (#230 #219)
Add HandleBars Random functionality (#219)
2018-11-09 10:06:09 +00:00
Stef Heyenrath
34be065467 Fix proxy tests (#229) 2018-11-08 13:17:31 +00:00
Stef Heyenrath
ee7f939e34 Update dependencies (#221)
* update some dependencies

* update deps
2018-11-08 11:33:20 +00:00
109 changed files with 4092 additions and 447 deletions

View File

@@ -0,0 +1,14 @@
{
"ServerUri": "https://sonarcloud.io",
"Organization": {
"Key": "stefh-github",
"Name": "Stef Heyenrath (Organization)"
},
"ProjectKey": "wiremock",
"Profiles": {
"CSharp": {
"ProfileKey": "AWRupN8iowGp6EI3lYmF",
"ProfileTimestamp": "2018-09-06T11:06:47+02:00"
}
}
}

View File

@@ -0,0 +1,362 @@
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="SonarQube - wiremock Sonar way" Description="This rule set was automatically generated from SonarQube.&#xD;&#xA;https://sonarcloud.io/profiles/show?key=AWRupN8iowGp6EI3lYmF" ToolsVersion="15.0">
<Rules AnalyzerId="SonarAnalyzer.CSharp" RuleNamespace="SonarAnalyzer.CSharp">
<Rule Id="S100" Action="None" />
<Rule Id="S1006" Action="Warning" />
<Rule Id="S101" Action="Warning" />
<Rule Id="S103" Action="None" />
<Rule Id="S104" Action="None" />
<Rule Id="S1048" Action="Warning" />
<Rule Id="S105" Action="None" />
<Rule Id="S106" Action="None" />
<Rule Id="S1066" Action="Warning" />
<Rule Id="S1067" Action="None" />
<Rule Id="S107" Action="Warning" />
<Rule Id="S1075" Action="Warning" />
<Rule Id="S108" Action="Warning" />
<Rule Id="S109" Action="None" />
<Rule Id="S110" Action="Warning" />
<Rule Id="S1104" Action="Warning" />
<Rule Id="S1109" Action="None" />
<Rule Id="S1110" Action="Warning" />
<Rule Id="S1116" Action="Warning" />
<Rule Id="S1117" Action="Warning" />
<Rule Id="S1118" Action="Warning" />
<Rule Id="S112" Action="Warning" />
<Rule Id="S1121" Action="Warning" />
<Rule Id="S1123" Action="Warning" />
<Rule Id="S1125" Action="Warning" />
<Rule Id="S113" Action="None" />
<Rule Id="S1134" Action="Warning" />
<Rule Id="S1135" Action="Warning" />
<Rule Id="S1144" Action="Warning" />
<Rule Id="S1145" Action="None" />
<Rule Id="S1147" Action="None" />
<Rule Id="S1151" Action="None" />
<Rule Id="S1155" Action="Warning" />
<Rule Id="S1163" Action="Warning" />
<Rule Id="S1168" Action="Warning" />
<Rule Id="S1172" Action="Warning" />
<Rule Id="S1185" Action="Warning" />
<Rule Id="S1186" Action="Warning" />
<Rule Id="S1192" Action="None" />
<Rule Id="S1200" Action="None" />
<Rule Id="S1206" Action="Warning" />
<Rule Id="S121" Action="None" />
<Rule Id="S1210" Action="Warning" />
<Rule Id="S1215" Action="Warning" />
<Rule Id="S122" Action="None" />
<Rule Id="S1226" Action="None" />
<Rule Id="S1227" Action="None" />
<Rule Id="S1244" Action="None" />
<Rule Id="S125" Action="Warning" />
<Rule Id="S126" Action="None" />
<Rule Id="S1264" Action="Warning" />
<Rule Id="S127" Action="None" />
<Rule Id="S1301" Action="None" />
<Rule Id="S1309" Action="None" />
<Rule Id="S131" Action="None" />
<Rule Id="S1313" Action="None" />
<Rule Id="S134" Action="None" />
<Rule Id="S138" Action="None" />
<Rule Id="S1449" Action="None" />
<Rule Id="S1450" Action="Warning" />
<Rule Id="S1451" Action="None" />
<Rule Id="S1479" Action="Warning" />
<Rule Id="S1481" Action="Warning" />
<Rule Id="S1541" Action="None" />
<Rule Id="S1607" Action="Warning" />
<Rule Id="S1643" Action="Warning" />
<Rule Id="S1656" Action="Warning" />
<Rule Id="S1659" Action="None" />
<Rule Id="S1694" Action="None" />
<Rule Id="S1696" Action="None" />
<Rule Id="S1697" Action="None" />
<Rule Id="S1698" Action="None" />
<Rule Id="S1699" Action="Warning" />
<Rule Id="S1751" Action="Warning" />
<Rule Id="S1764" Action="Warning" />
<Rule Id="S1821" Action="None" />
<Rule Id="S1848" Action="Warning" />
<Rule Id="S1854" Action="Warning" />
<Rule Id="S1858" Action="None" />
<Rule Id="S1862" Action="Warning" />
<Rule Id="S1871" Action="Warning" />
<Rule Id="S1905" Action="Warning" />
<Rule Id="S1939" Action="Warning" />
<Rule Id="S1940" Action="Warning" />
<Rule Id="S1944" Action="Warning" />
<Rule Id="S1994" Action="None" />
<Rule Id="S2068" Action="Warning" />
<Rule Id="S2070" Action="None" />
<Rule Id="S2092" Action="None" />
<Rule Id="S2114" Action="Warning" />
<Rule Id="S2123" Action="Warning" />
<Rule Id="S2148" Action="None" />
<Rule Id="S2156" Action="None" />
<Rule Id="S2178" Action="Warning" />
<Rule Id="S2183" Action="Warning" />
<Rule Id="S2184" Action="Warning" />
<Rule Id="S2187" Action="Warning" />
<Rule Id="S2190" Action="Warning" />
<Rule Id="S2197" Action="None" />
<Rule Id="S2201" Action="Warning" />
<Rule Id="S2219" Action="Warning" />
<Rule Id="S2221" Action="None" />
<Rule Id="S2223" Action="Warning" />
<Rule Id="S2225" Action="Warning" />
<Rule Id="S2228" Action="None" />
<Rule Id="S2234" Action="Warning" />
<Rule Id="S2245" Action="Warning" />
<Rule Id="S2255" Action="Warning" />
<Rule Id="S2259" Action="Warning" />
<Rule Id="S2275" Action="Warning" />
<Rule Id="S2278" Action="Warning" />
<Rule Id="S2290" Action="Warning" />
<Rule Id="S2291" Action="Warning" />
<Rule Id="S2292" Action="Warning" />
<Rule Id="S2302" Action="None" />
<Rule Id="S2306" Action="Warning" />
<Rule Id="S2325" Action="None" />
<Rule Id="S2326" Action="Warning" />
<Rule Id="S2327" Action="Warning" />
<Rule Id="S2328" Action="Warning" />
<Rule Id="S2330" Action="None" />
<Rule Id="S2333" Action="None" />
<Rule Id="S2339" Action="None" />
<Rule Id="S2342" Action="Warning" />
<Rule Id="S2344" Action="Warning" />
<Rule Id="S2345" Action="Warning" />
<Rule Id="S2346" Action="Warning" />
<Rule Id="S2357" Action="None" />
<Rule Id="S2360" Action="None" />
<Rule Id="S2365" Action="Warning" />
<Rule Id="S2368" Action="Warning" />
<Rule Id="S2372" Action="Warning" />
<Rule Id="S2376" Action="Warning" />
<Rule Id="S2386" Action="Warning" />
<Rule Id="S2387" Action="None" />
<Rule Id="S2436" Action="Warning" />
<Rule Id="S2437" Action="Warning" />
<Rule Id="S2486" Action="Warning" />
<Rule Id="S2551" Action="Warning" />
<Rule Id="S2583" Action="Warning" />
<Rule Id="S2589" Action="Warning" />
<Rule Id="S2674" Action="None" />
<Rule Id="S2681" Action="Warning" />
<Rule Id="S2688" Action="Warning" />
<Rule Id="S2692" Action="Warning" />
<Rule Id="S2696" Action="Warning" />
<Rule Id="S2699" Action="None" />
<Rule Id="S2701" Action="None" />
<Rule Id="S2737" Action="Warning" />
<Rule Id="S2743" Action="Warning" />
<Rule Id="S2757" Action="Warning" />
<Rule Id="S2758" Action="Warning" />
<Rule Id="S2760" Action="None" />
<Rule Id="S2761" Action="Warning" />
<Rule Id="S2930" Action="Warning" />
<Rule Id="S2931" Action="None" />
<Rule Id="S2933" Action="Warning" />
<Rule Id="S2934" Action="Warning" />
<Rule Id="S2952" Action="None" />
<Rule Id="S2953" Action="Warning" />
<Rule Id="S2955" Action="None" />
<Rule Id="S2971" Action="Warning" />
<Rule Id="S2995" Action="Warning" />
<Rule Id="S2996" Action="Warning" />
<Rule Id="S2997" Action="Warning" />
<Rule Id="S3005" Action="Warning" />
<Rule Id="S3010" Action="Warning" />
<Rule Id="S3052" Action="None" />
<Rule Id="S3060" Action="Warning" />
<Rule Id="S3168" Action="Warning" />
<Rule Id="S3169" Action="Warning" />
<Rule Id="S3172" Action="Warning" />
<Rule Id="S3215" Action="None" />
<Rule Id="S3216" Action="None" />
<Rule Id="S3217" Action="Warning" />
<Rule Id="S3218" Action="Warning" />
<Rule Id="S3220" Action="Warning" />
<Rule Id="S3234" Action="None" />
<Rule Id="S3235" Action="None" />
<Rule Id="S3236" Action="Warning" />
<Rule Id="S3237" Action="Warning" />
<Rule Id="S3240" Action="None" />
<Rule Id="S3241" Action="Warning" />
<Rule Id="S3242" Action="None" />
<Rule Id="S3244" Action="Warning" />
<Rule Id="S3246" Action="Warning" />
<Rule Id="S3247" Action="Warning" />
<Rule Id="S3249" Action="Warning" />
<Rule Id="S3251" Action="Warning" />
<Rule Id="S3253" Action="None" />
<Rule Id="S3254" Action="None" />
<Rule Id="S3256" Action="Warning" />
<Rule Id="S3257" Action="None" />
<Rule Id="S3261" Action="Warning" />
<Rule Id="S3262" Action="Warning" />
<Rule Id="S3263" Action="Warning" />
<Rule Id="S3264" Action="Warning" />
<Rule Id="S3265" Action="Warning" />
<Rule Id="S3330" Action="None" />
<Rule Id="S3343" Action="Warning" />
<Rule Id="S3346" Action="Warning" />
<Rule Id="S3353" Action="None" />
<Rule Id="S3358" Action="Warning" />
<Rule Id="S3366" Action="None" />
<Rule Id="S3376" Action="Warning" />
<Rule Id="S3397" Action="Warning" />
<Rule Id="S3400" Action="Warning" />
<Rule Id="S3415" Action="Warning" />
<Rule Id="S3427" Action="Warning" />
<Rule Id="S3431" Action="None" />
<Rule Id="S3433" Action="Warning" />
<Rule Id="S3440" Action="Warning" />
<Rule Id="S3441" Action="None" />
<Rule Id="S3442" Action="Warning" />
<Rule Id="S3443" Action="Warning" />
<Rule Id="S3444" Action="Warning" />
<Rule Id="S3445" Action="Warning" />
<Rule Id="S3447" Action="Warning" />
<Rule Id="S3449" Action="Warning" />
<Rule Id="S3450" Action="Warning" />
<Rule Id="S3451" Action="Warning" />
<Rule Id="S3453" Action="Warning" />
<Rule Id="S3456" Action="Warning" />
<Rule Id="S3457" Action="Warning" />
<Rule Id="S3458" Action="Warning" />
<Rule Id="S3459" Action="Warning" />
<Rule Id="S3464" Action="Warning" />
<Rule Id="S3466" Action="Warning" />
<Rule Id="S3532" Action="None" />
<Rule Id="S3597" Action="Warning" />
<Rule Id="S3598" Action="Warning" />
<Rule Id="S3600" Action="Warning" />
<Rule Id="S3603" Action="Warning" />
<Rule Id="S3604" Action="Warning" />
<Rule Id="S3610" Action="Warning" />
<Rule Id="S3626" Action="Warning" />
<Rule Id="S3655" Action="Warning" />
<Rule Id="S3693" Action="Warning" />
<Rule Id="S3717" Action="None" />
<Rule Id="S3776" Action="Warning" />
<Rule Id="S3869" Action="Warning" />
<Rule Id="S3871" Action="Warning" />
<Rule Id="S3872" Action="None" />
<Rule Id="S3874" Action="None" />
<Rule Id="S3875" Action="Warning" />
<Rule Id="S3876" Action="None" />
<Rule Id="S3877" Action="Warning" />
<Rule Id="S3880" Action="None" />
<Rule Id="S3881" Action="Warning" />
<Rule Id="S3884" Action="Warning" />
<Rule Id="S3885" Action="Warning" />
<Rule Id="S3887" Action="Warning" />
<Rule Id="S3889" Action="Warning" />
<Rule Id="S3897" Action="Warning" />
<Rule Id="S3898" Action="None" />
<Rule Id="S3900" Action="None" />
<Rule Id="S3902" Action="None" />
<Rule Id="S3903" Action="Warning" />
<Rule Id="S3904" Action="Warning" />
<Rule Id="S3906" Action="None" />
<Rule Id="S3908" Action="None" />
<Rule Id="S3909" Action="None" />
<Rule Id="S3923" Action="Warning" />
<Rule Id="S3925" Action="Warning" />
<Rule Id="S3926" Action="Warning" />
<Rule Id="S3927" Action="Warning" />
<Rule Id="S3928" Action="Warning" />
<Rule Id="S3937" Action="None" />
<Rule Id="S3956" Action="None" />
<Rule Id="S3962" Action="None" />
<Rule Id="S3963" Action="Warning" />
<Rule Id="S3966" Action="Warning" />
<Rule Id="S3967" Action="None" />
<Rule Id="S3971" Action="Warning" />
<Rule Id="S3972" Action="Warning" />
<Rule Id="S3973" Action="Warning" />
<Rule Id="S3981" Action="Warning" />
<Rule Id="S3984" Action="Warning" />
<Rule Id="S3990" Action="None" />
<Rule Id="S3992" Action="None" />
<Rule Id="S3993" Action="None" />
<Rule Id="S3994" Action="None" />
<Rule Id="S3995" Action="None" />
<Rule Id="S3996" Action="None" />
<Rule Id="S3997" Action="None" />
<Rule Id="S3998" Action="Warning" />
<Rule Id="S4000" Action="None" />
<Rule Id="S4002" Action="None" />
<Rule Id="S4004" Action="None" />
<Rule Id="S4005" Action="None" />
<Rule Id="S4015" Action="Warning" />
<Rule Id="S4016" Action="Warning" />
<Rule Id="S4017" Action="None" />
<Rule Id="S4018" Action="None" />
<Rule Id="S4019" Action="Warning" />
<Rule Id="S4022" Action="None" />
<Rule Id="S4023" Action="None" />
<Rule Id="S4025" Action="None" />
<Rule Id="S4026" Action="None" />
<Rule Id="S4027" Action="None" />
<Rule Id="S4035" Action="Warning" />
<Rule Id="S4039" Action="None" />
<Rule Id="S4040" Action="None" />
<Rule Id="S4041" Action="None" />
<Rule Id="S4047" Action="None" />
<Rule Id="S4049" Action="None" />
<Rule Id="S4050" Action="None" />
<Rule Id="S4052" Action="None" />
<Rule Id="S4055" Action="None" />
<Rule Id="S4056" Action="None" />
<Rule Id="S4057" Action="None" />
<Rule Id="S4058" Action="None" />
<Rule Id="S4059" Action="None" />
<Rule Id="S4060" Action="None" />
<Rule Id="S4061" Action="Warning" />
<Rule Id="S4069" Action="None" />
<Rule Id="S4070" Action="None" />
<Rule Id="S4142" Action="None" />
<Rule Id="S4143" Action="Warning" />
<Rule Id="S4144" Action="Warning" />
<Rule Id="S4158" Action="Warning" />
<Rule Id="S4159" Action="Warning" />
<Rule Id="S4200" Action="Warning" />
<Rule Id="S4210" Action="Warning" />
<Rule Id="S4211" Action="Warning" />
<Rule Id="S4212" Action="None" />
<Rule Id="S4214" Action="Warning" />
<Rule Id="S4220" Action="Warning" />
<Rule Id="S4225" Action="None" />
<Rule Id="S4226" Action="None" />
<Rule Id="S4260" Action="Warning" />
<Rule Id="S4261" Action="None" />
<Rule Id="S4275" Action="Warning" />
<Rule Id="S4277" Action="Warning" />
<Rule Id="S4426" Action="Warning" />
<Rule Id="S4428" Action="Warning" />
<Rule Id="S4432" Action="None" />
<Rule Id="S4433" Action="Warning" />
<Rule Id="S4456" Action="Warning" />
<Rule Id="S4457" Action="Warning" />
<Rule Id="S4462" Action="None" />
<Rule Id="S4524" Action="Warning" />
<Rule Id="S4564" Action="None" />
<Rule Id="S4581" Action="Warning" />
<Rule Id="S4586" Action="Warning" />
<Rule Id="S818" Action="Warning" />
<Rule Id="S881" Action="None" />
<Rule Id="S907" Action="Warning" />
<Rule Id="S927" Action="Warning" />
</Rules>
<Rules AnalyzerId="SonarAnalyzer.Security" RuleNamespace="SonarAnalyzer.Security">
<Rule Id="S2076" Action="Warning" />
<Rule Id="S2078" Action="Warning" />
<Rule Id="S2083" Action="Warning" />
<Rule Id="S2091" Action="Warning" />
<Rule Id="S2631" Action="Warning" />
<Rule Id="S3649" Action="Warning" />
</Rules>
</RuleSet>

View File

@@ -1,3 +1,71 @@
# 1.0.15.0 (04 May 2019)
- [#271](https://github.com/WireMock-Net/WireMock.Net/pull/271) - Support Dynamic response files using Handlebars templating [bug, feature] contributed by [StefH](https://github.com/StefH)
- [#272](https://github.com/WireMock-Net/WireMock.Net/pull/272) - Add unit test for JsonPath and BodyAsFile mapping contributed by [denstorti](https://github.com/denstorti)
- [#273](https://github.com/WireMock-Net/WireMock.Net/pull/273) - Dynamic response handlebars templating (2) [bug, feature] contributed by [StefH](https://github.com/StefH)
- [#270](https://github.com/WireMock-Net/WireMock.Net/issues/270) - Dynamic response files using Handlebars templating [bug, question]
# 1.0.14.0 (20 April 2019)
- [#269](https://github.com/WireMock-Net/WireMock.Net/pull/269) - Add JmesPath matcher [feature] contributed by [StefH](https://github.com/StefH)
- [#268](https://github.com/WireMock-Net/WireMock.Net/issues/268) - Swagger UI for admin api [question]
# 1.0.13.0 (11 April 2019)
- [#266](https://github.com/WireMock-Net/WireMock.Net/pull/266) - [265] Add file upload to allow mocking of file operations contributed by [JackCreativeCrew](https://github.com/JackCreativeCrew)
- [#265](https://github.com/WireMock-Net/WireMock.Net/issues/265) - File Upload [feature]
# 1.0.12.0 (05 April 2019)
- [#264](https://github.com/WireMock-Net/WireMock.Net/pull/264) - Proxy : also save multipart as string in mapping file contributed by [StefH](https://github.com/StefH)
- [#263](https://github.com/WireMock-Net/WireMock.Net/issues/263) - Content-Type multipart/form-data is not serialized in proxy and recording mode [bug]
# 1.0.11.0 (30 March 2019)
- [#261](https://github.com/WireMock-Net/WireMock.Net/pull/261) - Fix BodyAsJson transform bug in ResponseMessageTransformer contributed by [psypilat](https://github.com/psypilat)
- [#262](https://github.com/WireMock-Net/WireMock.Net/pull/262) - Add ProvideResponse_WithJsonBodyAndTransform test contributed by [psypilat](https://github.com/psypilat)
# 1.0.10.0 (27 March 2019)
- [#260](https://github.com/WireMock-Net/WireMock.Net/pull/260) - Fix Response.Delay property serialization [bug] contributed by [StefH](https://github.com/StefH)
- [#257](https://github.com/WireMock-Net/WireMock.Net/issues/257) - Doc: Update outdated [question]
- [#258](https://github.com/WireMock-Net/WireMock.Net/issues/258) - InvalidProgramException when following running as standalone process example with dotnetcore [invalid]
# 1.0.9.0 (25 March 2019)
- [#256](https://github.com/WireMock-Net/WireMock.Net/pull/256) - Fixed Multi Param Match logic contributed by [StefH](https://github.com/StefH)
- [#255](https://github.com/WireMock-Net/WireMock.Net/issues/255) - ExactMatcher with array pattern not working? [bug]
# 1.0.8.0 (12 March 2019)
- [#254](https://github.com/WireMock-Net/WireMock.Net/pull/254) - RequestMessageParamMatcher supports Ignore Case for the key [feature] contributed by [StefH](https://github.com/StefH)
- [#251](https://github.com/WireMock-Net/WireMock.Net/issues/251) - Problem with Request Match WithBody [question]
- [#253](https://github.com/WireMock-Net/WireMock.Net/issues/253) - Request Path and query parameter keys are case-sensitive
# 1.0.7.0 (19 January 2019)
- [#244](https://github.com/WireMock-Net/WireMock.Net/pull/244) - Fix BodyAsFile to also allow relative paths [feature] contributed by [StefH](https://github.com/StefH)
- [#240](https://github.com/WireMock-Net/WireMock.Net/issues/240) - How to submit mappings for multiple request, responses [feature]
- [#243](https://github.com/WireMock-Net/WireMock.Net/issues/243) - Not able to read response from file [question]
# 1.0.6.1 (10 January 2019)
- [#247](https://github.com/WireMock-Net/WireMock.Net/pull/247) - Issue 225 improve logging in example for wire mock as windows service contributed by [paulssn](https://github.com/paulssn)
- [#249](https://github.com/WireMock-Net/WireMock.Net/pull/249) - Fixed &quot;Content-Type multipart/form-data&quot; [bug] contributed by [StefH](https://github.com/StefH)
- [#225](https://github.com/WireMock-Net/WireMock.Net/issues/225) - Feature: Improve logging in example for WireMock as Windows Service [feature]
- [#238](https://github.com/WireMock-Net/WireMock.Net/issues/238) - Localhost and free port problem [question]
- [#245](https://github.com/WireMock-Net/WireMock.Net/issues/245) - Not able to match XML request body using XPathMatcher pattern [question]
- [#248](https://github.com/WireMock-Net/WireMock.Net/issues/248) - Content-Type multipart/form-data is not seen as byte[] anymore
# 1.0.6 (15 December 2018)
- [#242](https://github.com/WireMock-Net/WireMock.Net/pull/242) - Post multiple Mappings [feature] contributed by [StefH](https://github.com/StefH)
- [#237](https://github.com/WireMock-Net/WireMock.Net/issues/237) - Port not released [question]
- [#239](https://github.com/WireMock-Net/WireMock.Net/issues/239) - Not able to hit the mock server if AllowPartialMapping is not set to true [question]
# 1.0.5 (07 December 2018)
- [#236](https://github.com/WireMock-Net/WireMock.Net/pull/236) - Add Random Regex (using Fare) [feature] contributed by [StefH](https://github.com/StefH)
# 1.0.4.21 (30 November 2018)
- [#221](https://github.com/WireMock-Net/WireMock.Net/pull/221) - Update dependencies [feature] contributed by [StefH](https://github.com/StefH)
- [#229](https://github.com/WireMock-Net/WireMock.Net/pull/229) - Fix proxy tests [test] contributed by [StefH](https://github.com/StefH)
- [#230](https://github.com/WireMock-Net/WireMock.Net/pull/230) - Add HandleBars Random functionality (#219) [feature] contributed by [StefH](https://github.com/StefH)
- [#231](https://github.com/WireMock-Net/WireMock.Net/pull/231) - Use RandomDataGenerator.Net 1.0.3.0 contributed by [StefH](https://github.com/StefH)
- [#232](https://github.com/WireMock-Net/WireMock.Net/pull/232) - Add SonarLint checks [feature] contributed by [StefH](https://github.com/StefH)
- [#233](https://github.com/WireMock-Net/WireMock.Net/pull/233) - RandomDataGenerator.Net 1.0.4 [feature] contributed by [StefH](https://github.com/StefH)
- [#235](https://github.com/WireMock-Net/WireMock.Net/pull/235) - Check aggregate exception during startup [bug] contributed by [StefH](https://github.com/StefH)
- [#219](https://github.com/WireMock-Net/WireMock.Net/issues/219) - Feature: random value helper [feature]
- [#234](https://github.com/WireMock-Net/WireMock.Net/issues/234) - Timeout Exception on VSTS Test Platform (Azure DevOps), with private build agent
# 1.0.4.20 (07 November 2018)
- [#222](https://github.com/WireMock-Net/WireMock.Net/pull/222) - Codecov contributed by [StefH](https://github.com/StefH)
- [#224](https://github.com/WireMock-Net/WireMock.Net/pull/224) - Fixed issue 223: Example for WireMock as Windows Service throws Exception because of WireMockConsoleLogger contributed by [paulssn](https://github.com/paulssn)
@@ -152,7 +220,7 @@
- [#124](https://github.com/WireMock-Net/WireMock.Net/issues/124) - Issue: Unable to get host to listen on ips other than 127.0.0.1 using StandAloneApp
# 1.0.3.15 (05 April 2018)
- [#117](https://github.com/WireMock-Net/WireMock.Net/pull/117) - Respect start timeout setting and expose exception from server startup contributed by [msft-eliang](https://github.com/msft-eliang)
- [#117](https://github.com/WireMock-Net/WireMock.Net/pull/117) - Respect start timeout setting and expose exception from server startup contributed by [evanlwj](https://github.com/evanlwj)
# 1.0.3.14 (01 April 2018)
- [#111](https://github.com/WireMock-Net/WireMock.Net/issues/111) - Question: Adding wiki documentation on how to use WireMock.Net.WebApplication project
@@ -310,4 +378,5 @@
- [#14](https://github.com/WireMock-Net/WireMock.Net/issues/14) - Allow Body as Base64
- [#16](https://github.com/WireMock-Net/WireMock.Net/issues/16) - Stub priority [feature]
- [#17](https://github.com/WireMock-Net/WireMock.Net/issues/17) - Add JsonBody to response [feature]
- [#18](https://github.com/WireMock-Net/WireMock.Net/issues/18) - Listen on more ip-address/ports [feature]
- [#18](https://github.com/WireMock-Net/WireMock.Net/issues/18) - Listen on more ip-address/ports [feature]

View File

@@ -4,7 +4,7 @@
</PropertyGroup>
<PropertyGroup>
<VersionPrefix>1.0.4.20</VersionPrefix>
<VersionPrefix>1.0.15</VersionPrefix>
</PropertyGroup>
<Choose>

Binary file not shown.

View File

@@ -1,3 +1,3 @@
https://github.com/StefH/GitHubReleaseNotes
GitHubReleaseNotes.exe . --output CHANGELOG.md --skip-empty-releases --version 1.0.4.20
GitHubReleaseNotes.exe --output CHANGELOG.md --skip-empty-releases --version 1.0.15.0

View File

@@ -5,10 +5,10 @@ A C# .NET version based on [mock4net](https://github.com/alexvictoor/mock4net) w
* HTTP response stubbing, matchable on URL/Path, headers, cookies and body content patterns
* Runs in unit tests, as a standalone process, as windows service, as Azure or IIS or as docker
* Configurable via a fluent DotNet API, JSON files and JSON over HTTP
* Record/playback of stubs
* Record/playback of stubs (proxying)
* Per-request conditional proxying
* Stateful behaviour simulation
* Configurable response delays
* Response templating / transformation using Handlebars and extensions
## Info
| | |

View File

@@ -62,6 +62,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WireMock.Net.Console.Net452
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WireMock.Net.Console.NETCoreApp2", "examples\WireMock.Net.Console.NETCoreApp2\WireMock.Net.Console.NETCoreApp2.csproj", "{83645809-9E01-4E81-8733-BA9497554ABF}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WireMock.Net.WebApp", "src\WireMock.Net.WebApp\WireMock.Net.WebApp.csproj", "{D4782470-6CC1-4454-9D17-409F6CC286CE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -136,6 +138,10 @@ Global
{83645809-9E01-4E81-8733-BA9497554ABF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{83645809-9E01-4E81-8733-BA9497554ABF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{83645809-9E01-4E81-8733-BA9497554ABF}.Release|Any CPU.Build.0 = Release|Any CPU
{D4782470-6CC1-4454-9D17-409F6CC286CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D4782470-6CC1-4454-9D17-409F6CC286CE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D4782470-6CC1-4454-9D17-409F6CC286CE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D4782470-6CC1-4454-9D17-409F6CC286CE}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -158,6 +164,7 @@ Global
{1261BB9B-A7D4-456C-8985-3CE560361B8E} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A}
{668F689E-57B4-422E-8846-C0FF643CA268} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A}
{83645809-9E01-4E81-8733-BA9497554ABF} = {F0C22C47-DF71-463C-9B04-B4E0F3B8708A}
{D4782470-6CC1-4454-9D17-409F6CC286CE} = {EF242EDF-7133-4277-9A0C-18744DE08707}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {BF428BCC-C837-433B-87D2-15C7014B73E9}

View File

@@ -10,5 +10,7 @@
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=XUA/@EntryIndexedValue">XUA</s:String>
<s:Boolean x:Key="/Default/UserDictionary/Words/=funcs/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Heyenrath/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Jmes/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=randomizer/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Stef/@EntryIndexedValue">True</s:Boolean>
</wpf:ResourceDictionary>

View File

@@ -24,7 +24,7 @@ steps:
# - https://github.com/Microsoft/vsts-tasks/issues/8291
#
- script: |
%USERPROFILE%\.dotnet\tools\dotnet-sonarscanner begin /k:"wiremock" /d:sonar.organization="stefh-github" /d:sonar.host.url="https://sonarcloud.io" /d:sonar.login="$(SONAR_TOKEN)" /v:"$(buildId)" /d:sonar.cs.opencover.reportsPaths="**\coverage.opencover.xml"
%USERPROFILE%\.dotnet\tools\dotnet-sonarscanner begin /k:"wiremock" /o:"stefh-github" /d:sonar.host.url="https://sonarcloud.io" /d:sonar.login="$(SONAR_TOKEN)" /v:"$(buildId)" /d:sonar.cs.opencover.reportsPaths="**\coverage.opencover.xml"
displayName: Begin SonarScanner
# Build source, tests and run tests for net452 and netcoreapp2.1 (with coverage)

View File

@@ -52,6 +52,12 @@ namespace WireMock.Net.Client
var scenarioStates = api.GetScenariosAsync().Result;
Console.WriteLine($"GetScenariosAsync = {JsonConvert.SerializeObject(scenarioStates)}");
var postFileResult = api.PostFileAsync("1.cs", "C# Hello").GetAwaiter().GetResult();
Console.WriteLine($"postFileResult = {JsonConvert.SerializeObject(postFileResult)}");
var getFileResult = api.GetFileAsync("1.cs").GetAwaiter().GetResult();
Console.WriteLine($"getFileResult = {getFileResult}");
Console.WriteLine("Press any key to quit");
Console.ReadKey();
}

View File

@@ -9,7 +9,7 @@
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
<PackageReference Include="RestEase" Version="1.4.4" />
<PackageReference Include="RestEase" Version="1.4.7" />
</ItemGroup>
<ItemGroup>

View File

@@ -18,6 +18,10 @@
</Content>
</ItemGroup>
<ItemGroup>
<None Remove="__admin\mappings\array.json" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\WireMock.Net\WireMock.Net.csproj" />
<PackageReference Include="log4net" Version="2.0.8" />
@@ -37,6 +41,9 @@
<None Update="__admin\mappings\791a3f31-6946-4ce7-8e6f-0237c7443275.json">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</None>
<None Update="__admin\mappings\MyXmlResponse.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,22 @@
{
"Request": {
"Path": {
"Matchers": [
{
"Name": "WildcardMatcher",
"Pattern": "/bodyasfilexmltest",
"IgnoreCase": false
}
]
},
"Methods": [
"get"
]
},
"Response": {
"StatusCode": 200,
"Headers": {"Content-Type": "application/xml"},
"BodyAsFile": "MyXmlResponse.xml",
"UseTransformer": false
}
}

View File

@@ -0,0 +1,3 @@
<xml>
<hello>world</hello>
</xml>

View File

@@ -0,0 +1,46 @@
[
{
"Title": "1",
"Request": {
"Path": {
"Matchers": [
{
"Name": "WildcardMatcher",
"Pattern": "/mappings_static_1"
}
]
},
"Methods": [
"get"
]
},
"Response": {
"BodyAsJson": { "result": "mappings static_1" },
"Headers": {
"Content-Type": "application/json"
}
}
},
{
"Title": "2",
"Request": {
"Path": {
"Matchers": [
{
"Name": "WildcardMatcher",
"Pattern": "/mappings_static_2"
}
]
},
"Methods": [
"get"
]
},
"Response": {
"BodyAsJson": { "result": "mappings static_2" },
"Headers": {
"Content-Type": "application/json"
}
}
}
]

View File

@@ -43,5 +43,45 @@ namespace WireMock.Net.ConsoleApplication
{
File.WriteAllText(path, text);
}
/// <inheritdoc cref="IFileSystemHandler.ReadResponseBodyAsFile"/>
public byte[] ReadResponseBodyAsFile(string path)
{
return File.ReadAllBytes(Path.GetFileName(path) == path ? Path.Combine(GetMappingFolder(), path) : path);
}
/// <inheritdoc cref="IFileSystemHandler.FileExists"/>
public bool FileExists(string path)
{
return File.Exists(AdjustPath(path));
}
/// <inheritdoc cref="IFileSystemHandler.WriteFile(string, byte[])"/>
public void WriteFile(string path, byte[] bytes)
{
File.WriteAllBytes(AdjustPath(path), bytes);
}
/// <inheritdoc cref="IFileSystemHandler.DeleteFile"/>
public void DeleteFile(string path)
{
File.Delete(AdjustPath(path));
}
/// <inheritdoc cref="IFileSystemHandler.ReadFile"/>
public byte[] ReadFile(string path)
{
return File.ReadAllBytes(AdjustPath(path));
}
/// <summary>
/// Adjusts the path to the MappingFolder.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>Adjusted path</returns>
private string AdjustPath(string path)
{
return Path.Combine(GetMappingFolder(), path);
}
}
}

View File

@@ -1,6 +1,7 @@
using System;
using Newtonsoft.Json;
using System;
using System.Globalization;
using System.Net;
using Newtonsoft.Json;
using WireMock.Logging;
using WireMock.Matchers;
using WireMock.RequestBuilders;
@@ -38,7 +39,7 @@ namespace WireMock.Net.ConsoleApplication
server.SetBasicAuthentication("a", "b");
server.AllowPartialMapping();
// server.AllowPartialMapping();
server
.Given(Request.Create().WithPath(p => p.Contains("x")).UsingGet())
@@ -387,14 +388,56 @@ namespace WireMock.Net.ConsoleApplication
.WithStatusCode(500)
.WithBody(requestMessage =>
{
string returnStr = JsonConvert.SerializeObject(new
return JsonConvert.SerializeObject(new
{
Message = "Test error"
});
return returnStr;
})
);
server
.Given(Request.Create().WithPath("/random"))
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/json")
.WithBodyAsJson(new
{
Xeger1 = "{{Xeger \"\\w{4}\\d{5}\"}}",
Xeger2 = "{{Xeger \"\\d{5}\"}}",
TextRegexPostcode = "{{Random Type=\"TextRegex\" Pattern=\"[1-9][0-9]{3}[A-Z]{2}\"}}",
Text = "{{Random Type=\"Text\" Min=8 Max=20}}",
TextLipsum = "{{Random Type=\"TextLipsum\"}}",
IBAN = "{{Random Type=\"IBAN\" CountryCode=\"NL\"}}",
TimeSpan1 = "{{Random Type=\"TimeSpan\" Format=\"c\" IncludeMilliseconds=false}}",
TimeSpan2 = "{{Random Type=\"TimeSpan\"}}",
DateTime1 = "{{Random Type=\"DateTime\"}}",
DateTimeNow = DateTime.Now,
DateTimeNowToString = DateTime.Now.ToString("s", CultureInfo.InvariantCulture),
Guid1 = "{{Random Type=\"Guid\" Uppercase=false}}",
Guid2 = "{{Random Type=\"Guid\"}}",
Boolean = "{{Random Type=\"Boolean\"}}",
Integer = "{{Random Type=\"Integer\" Min=1000 Max=9999}}",
Long = "{{#Random Type=\"Long\" Min=10000000 Max=99999999}}{{this}}{{/Random}}",
Double = "{{Random Type=\"Double\" Min=10 Max=99}}",
Float = "{{Random Type=\"Float\" Min=100 Max=999}}",
IP4Address = "{{Random Type=\"IPv4Address\" Min=\"10.2.3.4\"}}",
IP6Address = "{{Random Type=\"IPv6Address\"}}",
MACAddress = "{{Random Type=\"MACAddress\" Separator=\"-\"}}",
StringListValue = "{{Random Type=\"StringList\" Values=[\"a\", \"b\", \"c\"]}}"
})
.WithTransformer()
);
server
.Given(Request.Create()
.UsingPost()
.WithPath("/xpathsoap")
.WithBody(new XPathMatcher("//*[local-name() = 'getMyData']"))
)
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/xml")
.WithBody("<xml>ok</xml>")
);
System.Console.WriteLine("Press any key to stop the server");
System.Console.ReadKey();
server.Stop();

View File

@@ -46,8 +46,8 @@
<Reference Include="Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="SimMetrics.Net, Version=1.0.4.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\SimMetrics.Net.1.0.4\lib\net45\SimMetrics.Net.dll</HintPath>
<Reference Include="SimMetrics.Net, Version=1.0.5.0, Culture=neutral, PublicKeyToken=c58dc06d59f3391b, processorArchitecture=MSIL">
<HintPath>..\..\packages\SimMetrics.Net.1.0.5\lib\net45\SimMetrics.Net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />

View File

@@ -3,5 +3,5 @@
<package id="log4net" version="2.0.8" targetFramework="net452" />
<package id="Microsoft.Owin.Host.HttpListener" version="3.1.0" targetFramework="net452" />
<package id="Newtonsoft.Json" version="11.0.2" targetFramework="net452" />
<package id="SimMetrics.Net" version="1.0.4" targetFramework="net452" />
<package id="SimMetrics.Net" version="1.0.5" targetFramework="net452" />
</packages>

View File

@@ -41,8 +41,8 @@
<Reference Include="Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="SimMetrics.Net, Version=1.0.4.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\SimMetrics.Net.1.0.4\lib\net45\SimMetrics.Net.dll</HintPath>
<Reference Include="SimMetrics.Net, Version=1.0.5.0, Culture=neutral, PublicKeyToken=c58dc06d59f3391b, processorArchitecture=MSIL">
<HintPath>..\..\packages\SimMetrics.Net.1.0.5\lib\net45\SimMetrics.Net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />

View File

@@ -2,5 +2,5 @@
<packages>
<package id="log4net" version="2.0.8" targetFramework="net461" />
<package id="Newtonsoft.Json" version="11.0.2" targetFramework="net461" />
<package id="SimMetrics.Net" version="1.0.4" targetFramework="net461" />
<package id="SimMetrics.Net" version="1.0.5" targetFramework="net461" />
</packages>

View File

@@ -1,4 +1,6 @@
using Newtonsoft.Json;
using System;
using System.Net.Http;
using Newtonsoft.Json;
using WireMock.Server;
using WireMock.Settings;
@@ -8,14 +10,15 @@ namespace WireMock.Net.Console.Proxy.Net452
{
static void Main(string[] args)
{
string[] urls = { "http://localhost:9091/", "https://localhost:9443/" };
var server = FluentMockServer.Start(new FluentMockServerSettings
{
Urls = new[] { "http://localhost:9091/", "https://localhost:9443/" },
Urls = urls,
StartAdminInterface = true,
ReadStaticMappings = false,
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = "https://www.google.com",
Url = "http://postman-echo.com/post",
//ClientX509Certificate2ThumbprintOrSubjectName = "www.yourclientcertname.com OR yourcertificatethumbprint (only if the service you're proxying to requires it)",
SaveMapping = true,
SaveMappingToFile = false,
@@ -28,6 +31,13 @@ namespace WireMock.Net.Console.Proxy.Net452
System.Console.WriteLine(JsonConvert.SerializeObject(eventRecordArgs.NewItems, Formatting.Indented));
};
var uri = new Uri(urls[0]);
var form = new MultipartFormDataContent
{
{ new StringContent("data"), "test", "test.txt" }
};
new HttpClient().PostAsync(uri, form).GetAwaiter().GetResult();
System.Console.WriteLine("Press any key to stop the server");
System.Console.ReadKey();
server.Stop();

View File

@@ -1,6 +1,8 @@
using System;
using log4net.Config;
using System;
using System.IO;
using System.ServiceProcess;
using WireMock.Logging;
using WireMock.Net.Service;
using WireMock.Net.StandAlone;
using WireMock.Server;
using WireMock.Settings;
@@ -21,7 +23,7 @@ namespace Wiremock.Net.Service
protected override void OnStart(string[] args)
{
Start(new WireMockNullLogger());
Start();
}
protected override void OnStop()
@@ -35,6 +37,11 @@ namespace Wiremock.Net.Service
static void Main(string[] args)
{
//Setting the current directory explicitly is required if the application is running as Windows Service,
//as the current directory of a Windows Service is %WinDir%\System32 per default.
Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
XmlConfigurator.ConfigureAndWatch(new FileInfo("log4net.config"));
// running as service
if (!Environment.UserInteractive)
{
@@ -46,7 +53,7 @@ namespace Wiremock.Net.Service
else
{
// running as console app
Start(new WireMockConsoleLogger());
Start();
Console.WriteLine("Press any key to stop...");
Console.ReadKey(true);
@@ -55,14 +62,14 @@ namespace Wiremock.Net.Service
}
}
private static void Start(IWireMockLogger logger)
private static void Start()
{
_server = StandAloneApp.Start(new FluentMockServerSettings
{
Urls = new[] { "http://*:9091/" },
StartAdminInterface = true,
ReadStaticMappings = true,
Logger = logger
Logger = new WireMockLog4NetLogger()
});
}

View File

@@ -35,6 +35,9 @@
<Reference Include="Handlebars, Version=1.9.5.0, Culture=neutral, PublicKeyToken=22225d0bf33cd661, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.1.9.5\lib\net452\Handlebars.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\..\packages\log4net.2.0.8\lib\net45-full\log4net.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Owin, Version=2.0.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Owin.2.0.2\lib\net45\Microsoft.Owin.dll</HintPath>
</Reference>
@@ -53,11 +56,11 @@
<Reference Include="Owin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0ebd12fd5e55cc5, processorArchitecture=MSIL">
<HintPath>..\..\packages\Owin.1.0\lib\net40\Owin.dll</HintPath>
</Reference>
<Reference Include="RestEase, Version=1.4.4.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\RestEase.1.4.4\lib\net45\RestEase.dll</HintPath>
<Reference Include="RestEase, Version=1.4.7.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\RestEase.1.4.7\lib\net45\RestEase.dll</HintPath>
</Reference>
<Reference Include="SimMetrics.Net, Version=1.0.4.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\SimMetrics.Net.1.0.4\lib\net45\SimMetrics.Net.dll</HintPath>
<Reference Include="SimMetrics.Net, Version=1.0.5.0, Culture=neutral, PublicKeyToken=c58dc06d59f3391b, processorArchitecture=MSIL">
<HintPath>..\..\packages\SimMetrics.Net.1.0.5\lib\net45\SimMetrics.Net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration.Install" />
@@ -83,8 +86,8 @@
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="XPath2, Version=1.0.5.1, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\XPath2.1.0.5.1\lib\net40\XPath2.dll</HintPath>
<Reference Include="XPath2, Version=1.0.7.0, Culture=neutral, PublicKeyToken=463c6d7fb740c7e5, processorArchitecture=MSIL">
<HintPath>..\..\packages\XPath2.1.0.6.1\lib\net40\XPath2.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
@@ -96,9 +99,13 @@
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="WireMockLog4NetLogger.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="log4net.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Service-Start.bat">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>

View File

@@ -0,0 +1,39 @@
using log4net;
using Newtonsoft.Json;
using Wiremock.Net.Service;
using WireMock.Admin.Requests;
using WireMock.Logging;
namespace WireMock.Net.Service
{
internal class WireMockLog4NetLogger : IWireMockLogger
{
private static readonly ILog Log = LogManager.GetLogger(typeof(Program));
public void Debug(string formatString, params object[] args)
{
Log.DebugFormat(formatString, args);
}
public void Info(string formatString, params object[] args)
{
Log.InfoFormat(formatString, args);
}
public void Warn(string formatString, params object[] args)
{
Log.WarnFormat(formatString, args);
}
public void Error(string formatString, params object[] args)
{
Log.ErrorFormat(formatString, args);
}
public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminRequest)
{
string message = JsonConvert.SerializeObject(logEntryModel, Formatting.Indented);
Log.DebugFormat("Admin[{0}] {1}", isAdminRequest, message);
}
}
}

View File

@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
</configSections>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger{1} - %message%newline" />
</layout>
</appender>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10000KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger{1} - %message%newline" />
</layout>
</appender>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger{1} - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="RollingLogFileAppender" />
<!--<appender-ref ref="EventLogAppender" /> --> <!-- comment in if needed -->
</root>
</log4net>
</configuration>

View File

@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Handlebars.Net" version="1.9.5" targetFramework="net452" />
<package id="log4net" version="2.0.8" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Owin" version="5.2.3" targetFramework="net452" />
@@ -11,8 +12,8 @@
<package id="MimeKitLite" version="2.0.1" targetFramework="net452" />
<package id="Newtonsoft.Json" version="11.0.2" targetFramework="net452" />
<package id="Owin" version="1.0" targetFramework="net452" />
<package id="RestEase" version="1.4.4" targetFramework="net452" />
<package id="SimMetrics.Net" version="1.0.4" targetFramework="net452" />
<package id="RestEase" version="1.4.7" targetFramework="net452" />
<package id="SimMetrics.Net" version="1.0.5" targetFramework="net452" />
<package id="System.Net.Http" version="4.3.3" targetFramework="net452" />
<package id="XPath2" version="1.0.5.1" targetFramework="net452" />
<package id="XPath2" version="1.0.6.1" targetFramework="net452" />
</packages>

View File

@@ -7,7 +7,7 @@
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
<bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
@@ -15,7 +15,8 @@
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.1.2" newVersion="4.1.1.2" />
<!--<bindingRedirect oldVersion="0.0.0.0-4.1.1.2" newVersion="4.1.1.2" />-->
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
@@ -29,6 +30,42 @@
<assemblyIdentity name="Microsoft.Win32.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.4.0" newVersion="4.1.4.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Security.Cryptography.Cng" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.3.1.0" newVersion="4.3.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Linq.Dynamic.Core" publicKeyToken="0f07ec44de6ac832" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.0.12.0" newVersion="1.0.12.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.4.1" newVersion="4.0.4.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.AspNetCore.Server.Kestrel.Core" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.1.3.0" newVersion="2.1.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.AspNetCore.Server.Kestrel" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.1.3.0" newVersion="2.1.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.IO.Pipelines" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.1" newVersion="4.0.0.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Security.Principal.Windows" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.1.1" newVersion="4.1.1.1" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

View File

@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\packages\Microsoft.Extensions.Configuration.UserSecrets.2.1.1\build\netstandard2.0\Microsoft.Extensions.Configuration.UserSecrets.props" Condition="Exists('..\..\packages\Microsoft.Extensions.Configuration.UserSecrets.2.1.1\build\netstandard2.0\Microsoft.Extensions.Configuration.UserSecrets.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@@ -12,6 +13,8 @@
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetFrameworkProfile />
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
@@ -36,8 +39,152 @@
<StartupObject>WireMock.Net.StandAlone.Net461.Program</StartupObject>
</PropertyGroup>
<ItemGroup>
<Reference Include="Handlebars, Version=1.8.1.0, Culture=neutral, PublicKeyToken=22225d0bf33cd661, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.1.9.0\lib\net40\Handlebars.dll</HintPath>
<Reference Include="Handlebars, Version=1.9.5.0, Culture=neutral, PublicKeyToken=22225d0bf33cd661, processorArchitecture=MSIL">
<HintPath>..\..\packages\Handlebars.Net.1.9.5\lib\net452\Handlebars.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore, Version=2.1.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.2.1.4\lib\netstandard2.0\Microsoft.AspNetCore.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Authentication.Abstractions, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Authentication.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Authentication.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Authentication.Core, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Authentication.Core.2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Authentication.Core.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Connections.Abstractions, Version=2.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Connections.Abstractions.2.1.3\lib\netstandard2.0\Microsoft.AspNetCore.Connections.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Diagnostics, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Diagnostics.2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Diagnostics.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Diagnostics.Abstractions, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Diagnostics.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Diagnostics.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.HostFiltering, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.HostFiltering.2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.HostFiltering.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Hosting, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Hosting.2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Hosting.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Hosting.Abstractions, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Hosting.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Hosting.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Hosting.Server.Abstractions, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Hosting.Server.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Hosting.Server.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Http, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Http.2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Http.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Http.Abstractions, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Http.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Http.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Http.Extensions, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Http.Extensions.2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Http.Extensions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Http.Features, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Http.Features.2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Http.Features.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.HttpOverrides, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.HttpOverrides.2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.HttpOverrides.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Routing, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Routing.2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Routing.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Routing.Abstractions, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Routing.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Routing.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Server.IISIntegration, Version=2.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Server.IISIntegration.2.1.2\lib\netstandard2.0\Microsoft.AspNetCore.Server.IISIntegration.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Server.Kestrel, Version=2.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Server.Kestrel.2.1.3\lib\netstandard2.0\Microsoft.AspNetCore.Server.Kestrel.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Server.Kestrel.Core, Version=2.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Server.Kestrel.Core.2.1.3\lib\netstandard2.0\Microsoft.AspNetCore.Server.Kestrel.Core.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Server.Kestrel.Https, Version=2.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Server.Kestrel.Https.2.1.3\lib\netstandard2.0\Microsoft.AspNetCore.Server.Kestrel.Https.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions, Version=2.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.2.1.3\lib\netstandard2.0\Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets, Version=2.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.2.1.3\lib\netstandard2.0\Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNetCore.WebUtilities, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNetCore.WebUtilities.2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.WebUtilities.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Configuration.2.1.1\lib\netstandard2.0\Microsoft.Extensions.Configuration.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.Abstractions, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Configuration.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.Configuration.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.Binder, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Configuration.Binder.2.1.1\lib\netstandard2.0\Microsoft.Extensions.Configuration.Binder.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.CommandLine, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Configuration.CommandLine.2.1.1\lib\netstandard2.0\Microsoft.Extensions.Configuration.CommandLine.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.EnvironmentVariables, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Configuration.EnvironmentVariables.2.1.1\lib\netstandard2.0\Microsoft.Extensions.Configuration.EnvironmentVariables.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.FileExtensions, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Configuration.FileExtensions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.Configuration.FileExtensions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.Json, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Configuration.Json.2.1.1\lib\netstandard2.0\Microsoft.Extensions.Configuration.Json.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Configuration.UserSecrets, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Configuration.UserSecrets.2.1.1\lib\netstandard2.0\Microsoft.Extensions.Configuration.UserSecrets.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.DependencyInjection, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.DependencyInjection.2.1.1\lib\net461\Microsoft.Extensions.DependencyInjection.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.FileProviders.Abstractions, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.FileProviders.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.FileProviders.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.FileProviders.Physical, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.FileProviders.Physical.2.1.1\lib\netstandard2.0\Microsoft.Extensions.FileProviders.Physical.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.FileSystemGlobbing, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.FileSystemGlobbing.2.1.1\lib\netstandard2.0\Microsoft.Extensions.FileSystemGlobbing.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Hosting.Abstractions, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Hosting.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.Hosting.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Logging.2.1.1\lib\netstandard2.0\Microsoft.Extensions.Logging.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.Abstractions, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Logging.Abstractions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.Logging.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.Configuration, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Logging.Configuration.2.1.1\lib\netstandard2.0\Microsoft.Extensions.Logging.Configuration.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.Console, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Logging.Console.2.1.1\lib\netstandard2.0\Microsoft.Extensions.Logging.Console.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.Debug, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Logging.Debug.2.1.1\lib\netstandard2.0\Microsoft.Extensions.Logging.Debug.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.ObjectPool, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.ObjectPool.2.1.1\lib\netstandard2.0\Microsoft.Extensions.ObjectPool.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Options, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Options.2.1.1\lib\netstandard2.0\Microsoft.Extensions.Options.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Options.ConfigurationExtensions, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Options.ConfigurationExtensions.2.1.1\lib\netstandard2.0\Microsoft.Extensions.Options.ConfigurationExtensions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Primitives, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Extensions.Primitives.2.1.1\lib\netstandard2.0\Microsoft.Extensions.Primitives.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Net.Http.Headers, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Net.Http.Headers.2.1.1\lib\netstandard2.0\Microsoft.Net.Http.Headers.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Owin, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Owin.4.0.0\lib\net451\Microsoft.Owin.dll</HintPath>
@@ -48,32 +195,63 @@
<Reference Include="Microsoft.Owin.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.Owin.Hosting.4.0.0\lib\net451\Microsoft.Owin.Hosting.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
<Reference Include="MimeKitLite, Version=2.0.0.0, Culture=neutral, PublicKeyToken=bede1c8a46c66814, processorArchitecture=MSIL">
<HintPath>..\..\packages\MimeKitLite.2.0.7\lib\net45\MimeKitLite.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="Owin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0ebd12fd5e55cc5, processorArchitecture=MSIL">
<HintPath>..\..\packages\Owin.1.0\lib\net40\Owin.dll</HintPath>
</Reference>
<Reference Include="RestEase, Version=1.4.4.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\RestEase.1.4.4\lib\net45\RestEase.dll</HintPath>
<Reference Include="RestEase, Version=1.4.7.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\RestEase.1.4.7\lib\net45\RestEase.dll</HintPath>
</Reference>
<Reference Include="SimMetrics.Net, Version=1.0.4.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\SimMetrics.Net.1.0.4\lib\net45\SimMetrics.Net.dll</HintPath>
<Reference Include="SimMetrics.Net, Version=1.0.5.0, Culture=neutral, PublicKeyToken=c58dc06d59f3391b, processorArchitecture=MSIL">
<HintPath>..\..\packages\SimMetrics.Net.1.0.5\lib\net45\SimMetrics.Net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Buffers.4.5.0\lib\netstandard2.0\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.Collections.Immutable, Version=1.2.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Collections.Immutable.1.5.0\lib\netstandard2.0\System.Collections.Immutable.dll</HintPath>
</Reference>
<Reference Include="System.Core" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Net.Http, Version=4.1.1.2, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Net.Http.4.3.3\lib\net46\System.Net.Http.dll</HintPath>
<Reference Include="System.Diagnostics.DiagnosticSource, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Diagnostics.DiagnosticSource.4.5.0\lib\net46\System.Diagnostics.DiagnosticSource.dll</HintPath>
</Reference>
<Reference Include="System.IO.Pipelines, Version=4.0.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.IO.Pipelines.4.5.2\lib\netstandard2.0\System.IO.Pipelines.dll</HintPath>
</Reference>
<Reference Include="System.Linq.Dynamic.Core, Version=1.0.12.0, Culture=neutral, PublicKeyToken=0f07ec44de6ac832, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Linq.Dynamic.Core.1.0.12\lib\net46\System.Linq.Dynamic.Core.dll</HintPath>
</Reference>
<Reference Include="System.Memory, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Memory.4.5.1\lib\netstandard2.0\System.Memory.dll</HintPath>
</Reference>
<Reference Include="System.Net.Http.Formatting, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNet.WebApi.Client.5.2.4\lib\net45\System.Net.Http.Formatting.dll</HintPath>
</Reference>
<Reference Include="System.Net.Http.WebRequest" />
<Reference Include="System.Numerics" />
<Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
</Reference>
<Reference Include="System.Reflection.Metadata, Version=1.4.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Reflection.Metadata.1.6.0\lib\netstandard2.0\System.Reflection.Metadata.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Runtime.CompilerServices.Unsafe.4.5.2\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Security" />
<Reference Include="System.Security.Cryptography.Algorithms, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net461\System.Security.Cryptography.Algorithms.dll</HintPath>
</Reference>
<Reference Include="System.Security.Cryptography.Cng, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Security.Cryptography.Cng.4.5.0\lib\net461\System.Security.Cryptography.Cng.dll</HintPath>
</Reference>
<Reference Include="System.Security.Cryptography.Encoding, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll</HintPath>
</Reference>
@@ -83,6 +261,15 @@
<Reference Include="System.Security.Cryptography.X509Certificates, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll</HintPath>
</Reference>
<Reference Include="System.Security.Principal.Windows, Version=4.1.1.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Security.Principal.Windows.4.5.1\lib\net461\System.Security.Principal.Windows.dll</HintPath>
</Reference>
<Reference Include="System.Text.Encodings.Web, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Text.Encodings.Web.4.5.0\lib\netstandard2.0\System.Text.Encodings.Web.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\..\packages\System.Threading.Tasks.Extensions.4.5.1\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Web.Http, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\Microsoft.AspNet.WebApi.Core.5.2.4\lib\net45\System.Web.Http.dll</HintPath>
@@ -92,14 +279,14 @@
</Reference>
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
<Reference Include="WireMock.Net, Version=1.0.3.6, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\WireMock.Net.1.0.3.6\lib\net46\WireMock.Net.dll</HintPath>
<Reference Include="WireMock.Net, Version=1.0.4.20, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\WireMock.Net.1.0.4.20\lib\net461\WireMock.Net.dll</HintPath>
</Reference>
<Reference Include="WireMock.Net.StandAlone, Version=1.0.3.6, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\WireMock.Net.StandAlone.1.0.3.6\lib\net46\WireMock.Net.StandAlone.dll</HintPath>
<Reference Include="WireMock.Net.StandAlone, Version=1.0.4.20, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\WireMock.Net.StandAlone.1.0.4.20\lib\net46\WireMock.Net.StandAlone.dll</HintPath>
</Reference>
<Reference Include="XPath2, Version=1.0.5.1, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\XPath2.1.0.5.1\lib\net40\XPath2.dll</HintPath>
<Reference Include="XPath2, Version=1.0.7.0, Culture=neutral, PublicKeyToken=463c6d7fb740c7e5, processorArchitecture=MSIL">
<HintPath>..\..\packages\XPath2.1.0.6.1\lib\net40\XPath2.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
@@ -107,8 +294,20 @@
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
<None Include="App.config">
<SubType>Designer</SubType>
</None>
<None Include="packages.config">
<SubType>Designer</SubType>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\..\packages\Microsoft.Extensions.Configuration.UserSecrets.2.1.1\build\netstandard2.0\Microsoft.Extensions.Configuration.UserSecrets.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.Extensions.Configuration.UserSecrets.2.1.1\build\netstandard2.0\Microsoft.Extensions.Configuration.UserSecrets.props'))" />
<Error Condition="!Exists('..\..\packages\Microsoft.Extensions.Configuration.UserSecrets.2.1.1\build\netstandard2.0\Microsoft.Extensions.Configuration.UserSecrets.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.Extensions.Configuration.UserSecrets.2.1.1\build\netstandard2.0\Microsoft.Extensions.Configuration.UserSecrets.targets'))" />
</Target>
<Import Project="..\..\packages\Microsoft.Extensions.Configuration.UserSecrets.2.1.1\build\netstandard2.0\Microsoft.Extensions.Configuration.UserSecrets.targets" Condition="Exists('..\..\packages\Microsoft.Extensions.Configuration.UserSecrets.2.1.1\build\netstandard2.0\Microsoft.Extensions.Configuration.UserSecrets.targets')" />
</Project>

View File

@@ -1,23 +1,84 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Handlebars.Net" version="1.9.0" targetFramework="net461" />
<package id="Handlebars.Net" version="1.9.5" targetFramework="net461" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.4" targetFramework="net461" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.4" targetFramework="net461" />
<package id="Microsoft.AspNet.WebApi.Owin" version="5.2.4" targetFramework="net461" />
<package id="Microsoft.AspNet.WebApi.OwinSelfHost" version="5.2.4" targetFramework="net461" />
<package id="Microsoft.AspNetCore" version="2.1.4" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Authentication.Abstractions" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Authentication.Core" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Connections.Abstractions" version="2.1.3" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Diagnostics" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Diagnostics.Abstractions" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.AspNetCore.HostFiltering" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Hosting" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Hosting.Abstractions" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Hosting.Server.Abstractions" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Http" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Http.Abstractions" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Http.Extensions" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Http.Features" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.AspNetCore.HttpOverrides" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Routing" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Routing.Abstractions" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Server.IISIntegration" version="2.1.2" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Server.Kestrel" version="2.1.3" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Server.Kestrel.Core" version="2.1.3" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Server.Kestrel.Https" version="2.1.3" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions" version="2.1.3" targetFramework="net461" />
<package id="Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets" version="2.1.3" targetFramework="net461" />
<package id="Microsoft.AspNetCore.WebUtilities" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.Configuration" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.Configuration.Abstractions" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.Configuration.Binder" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.Configuration.CommandLine" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.Configuration.EnvironmentVariables" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.Configuration.FileExtensions" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.Configuration.Json" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.Configuration.UserSecrets" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.DependencyInjection" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.FileProviders.Abstractions" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.FileProviders.Physical" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.FileSystemGlobbing" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.Hosting.Abstractions" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.Logging" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.Logging.Abstractions" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.Logging.Configuration" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.Logging.Console" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.Logging.Debug" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.ObjectPool" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.Options" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.Options.ConfigurationExtensions" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Extensions.Primitives" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Net.Http.Headers" version="2.1.1" targetFramework="net461" />
<package id="Microsoft.Owin" version="4.0.0" targetFramework="net461" />
<package id="Microsoft.Owin.Host.HttpListener" version="4.0.0" targetFramework="net461" />
<package id="Microsoft.Owin.Hosting" version="4.0.0" targetFramework="net461" />
<package id="Newtonsoft.Json" version="10.0.3" targetFramework="net461" />
<package id="MimeKitLite" version="2.0.7" targetFramework="net461" />
<package id="Newtonsoft.Json" version="11.0.2" targetFramework="net461" />
<package id="Owin" version="1.0" targetFramework="net461" />
<package id="RestEase" version="1.4.4" targetFramework="net461" />
<package id="SimMetrics.Net" version="1.0.4" targetFramework="net461" />
<package id="System.Net.Http" version="4.3.3" targetFramework="net461" />
<package id="RestEase" version="1.4.7" targetFramework="net461" />
<package id="SimMetrics.Net" version="1.0.5" targetFramework="net461" />
<package id="System.Buffers" version="4.5.0" targetFramework="net461" />
<package id="System.Collections.Immutable" version="1.5.0" targetFramework="net461" />
<package id="System.Diagnostics.DiagnosticSource" version="4.5.0" targetFramework="net461" />
<package id="System.IO.Pipelines" version="4.5.2" targetFramework="net461" />
<package id="System.Linq.Dynamic.Core" version="1.0.12" targetFramework="net461" />
<package id="System.Memory" version="4.5.1" targetFramework="net461" />
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net461" />
<package id="System.Reflection.Metadata" version="1.6.0" targetFramework="net461" />
<package id="System.Runtime.CompilerServices.Unsafe" version="4.5.2" targetFramework="net461" />
<package id="System.Security.Cryptography.Algorithms" version="4.3.0" targetFramework="net461" />
<package id="System.Security.Cryptography.Cng" version="4.5.0" targetFramework="net461" />
<package id="System.Security.Cryptography.Encoding" version="4.3.0" targetFramework="net461" />
<package id="System.Security.Cryptography.Primitives" version="4.3.0" targetFramework="net461" />
<package id="System.Security.Cryptography.X509Certificates" version="4.3.0" targetFramework="net461" />
<package id="WireMock.Net" version="1.0.3.6" targetFramework="net461" />
<package id="WireMock.Net.StandAlone" version="1.0.3.6" targetFramework="net461" />
<package id="XPath2" version="1.0.5.1" targetFramework="net461" />
<package id="System.Security.Principal.Windows" version="4.5.1" targetFramework="net461" />
<package id="System.Text.Encodings.Web" version="4.5.0" targetFramework="net461" />
<package id="System.Threading.Tasks.Extensions" version="4.5.1" targetFramework="net461" />
<package id="WireMock.Net" version="1.0.4.20" targetFramework="net461" />
<package id="WireMock.Net.StandAlone" version="1.0.4.20" targetFramework="net461" />
<package id="XPath2" version="1.0.6.1" targetFramework="net461" />
</packages>

View File

@@ -24,6 +24,7 @@
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
<CodeAnalysisRuleSet>WireMock.Net.StandAlone.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
@@ -40,9 +41,13 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="JetBrains.Annotations" Version="10.4.0">
<PackageReference Include="JetBrains.Annotations" Version="2018.2.1">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
<PackageReference Include="SonarAnalyzer.CSharp" Version="7.8.0.7320">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="SonarQube - wiremock Sonar way" ToolsVersion="15.0">
<Include Path="..\..\.sonarlint\wiremockcsharp.ruleset" Action="Default" />
</RuleSet>

View File

@@ -0,0 +1,22 @@
using Microsoft.Extensions.Logging;
namespace WireMock.Net.WebApp
{
public class App
{
private readonly IWireMockService _service;
private readonly ILogger _logger;
public App(IWireMockService service, ILogger logger)
{
_service = service;
_logger = logger;
}
public void Run()
{
_logger.LogInformation("WireMock.Net WebApp running");
_service.Run();
}
}
}

View File

@@ -0,0 +1,7 @@
namespace WireMock.Net.WebApp
{
public interface IWireMockService
{
void Run();
}
}

View File

@@ -0,0 +1,52 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using WireMock.Logging;
using WireMock.Settings;
namespace WireMock.Net.WebApp
{
public class Program
{
public static void Main(string[] args)
{
// Create service collection
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
// Create service provider
var serviceProvider = serviceCollection.BuildServiceProvider();
// Run app
serviceProvider.GetService<App>().Run();
}
private static void ConfigureServices(IServiceCollection services)
{
// Build configuration
var configuration = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables() // <-- this is needed to to override settings via the Azure Portal App Settings
.Build();
services.AddLogging(loggingBuilder =>
{
loggingBuilder.AddConfiguration(configuration.GetSection("Logging"));
loggingBuilder.AddConsole();
});
// Add access to IFluentMockServerSettings
var settings = configuration.GetSection("FluentMockServerSettings").Get<FluentMockServerSettings>();
services.AddSingleton<IFluentMockServerSettings>(settings);
// Add services
services.AddTransient<IWireMockLogger, WireMockLogger>();
services.AddTransient<IWireMockService, WireMockService>();
// Add app
services.AddTransient<App>();
}
}
}

View File

@@ -0,0 +1,38 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iis": {
"applicationUrl": "http://localhost//wiremock",
"sslPort": 0
},
"iisExpress": {
"applicationUrl": "http://localhost:56513/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchUrl": "__admin/settings",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"WireMock.Net.WebApp": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "__admin/settings",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:56514/"
},
"IIS": {
"commandName": "IIS",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "development"
}
}
}
}

View File

@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="2.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\WireMock.Net.StandAlone\WireMock.Net.StandAlone.csproj" />
<ProjectReference Include="..\..\src\WireMock.Net\WireMock.Net.csproj" />
</ItemGroup>
<ItemGroup>
<Content Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,43 @@
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using WireMock.Admin.Requests;
using WireMock.Logging;
namespace WireMock.Net.WebApp
{
public class WireMockLogger : IWireMockLogger
{
private readonly ILogger<WireMockService> _logger;
public WireMockLogger(ILogger<WireMockService> logger)
{
_logger = logger;
}
public void Debug(string formatString, params object[] args)
{
_logger.LogDebug(formatString, args);
}
public void Info(string formatString, params object[] args)
{
_logger.LogInformation(formatString, args);
}
public void Warn(string formatString, params object[] args)
{
_logger.LogWarning(formatString, args);
}
public void Error(string formatString, params object[] args)
{
_logger.LogError(formatString, args);
}
public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminRequest)
{
string message = JsonConvert.SerializeObject(logEntryModel, Formatting.Indented);
_logger.LogDebug("Admin[{0}] {1}", isAdminRequest, message);
}
}
}

View File

@@ -0,0 +1,39 @@
using Newtonsoft.Json;
using System.Threading;
using WireMock.Logging;
using WireMock.Net.StandAlone;
using WireMock.Settings;
namespace WireMock.Net.WebApp
{
public class WireMockService : IWireMockService
{
private static int sleepTime = 30000;
private readonly IWireMockLogger _logger;
private readonly IFluentMockServerSettings _settings;
public WireMockService(IWireMockLogger logger, IFluentMockServerSettings settings)
{
_logger = logger;
_settings = settings;
_settings.Logger = logger;
}
public void Run()
{
_logger.Info("WireMock.Net server starting");
StandAloneApp.Start(_settings);
_logger.Info($"WireMock.Net server settings {JsonConvert.SerializeObject(_settings)}");
while (true)
{
_logger.Info("WireMock.Net server running");
Thread.Sleep(sleepTime);
}
}
}
}

View File

@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}

View File

@@ -0,0 +1,21 @@
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Debug"
}
},
"Console": {
"LogLevel": {
"Default": "Debug"
}
}
},
"AllowedHosts": "*",
"FluentMockServerSettings": {
"AdminUsername": "a",
"AdminPassword": "b",
"StartAdminInterface": true
}
}

View File

@@ -10,6 +10,11 @@
/// </summary>
public string Name { get; set; }
/// <summary>
/// Defines if the key should be matched using case-ignore.
/// </summary>
public bool? IgnoreCase { get; set; }
/// <summary>
/// Gets or sets the matchers.
/// </summary>

View File

@@ -58,6 +58,14 @@ namespace WireMock.Client
[Header("Content-Type", "application/json")]
Task<StatusModel> PostMappingAsync([Body] MappingModel mapping);
/// <summary>
/// Add new mappings.
/// </summary>
/// <param name="mappings">MappingModels</param>
[Post("__admin/mappings")]
[Header("Content-Type", "application/json")]
Task<StatusModel> PostMappingsAsync([Body] IList<MappingModel> mappings);
/// <summary>
/// Delete all mappings.
/// </summary>
@@ -159,5 +167,42 @@ namespace WireMock.Client
/// </summary>
[Post("__admin/scenarios")]
Task<StatusModel> ResetScenariosAsync();
/// <summary>
/// Create a new File
/// </summary>
/// <param name="filename">The filename</param>
/// <param name="body">The body</param>
[Post("__admin/files/{filename}")]
Task<StatusModel> PostFileAsync([Path] string filename, [Body] string body);
/// <summary>
/// Update an existing File
/// </summary>
/// <param name="filename">The filename</param>
/// <param name="body">The body</param>
[Put("__admin/files/{filename}")]
Task<StatusModel> PutFileAsync([Path] string filename, [Body] string body);
/// <summary>
/// Get the content of an existing File
/// </summary>
/// <param name="filename">The filename</param>
[Get("__admin/files/{filename}")]
Task<string> GetFileAsync([Path] string filename);
/// <summary>
/// Delete an existing File
/// </summary>
/// <param name="filename">The filename</param>
[Delete("__admin/files/{filename}")]
Task<StatusModel> DeleteFileAsync([Path] string filename);
/// <summary>
/// Check if a file exists
/// </summary>
/// <param name="filename">The filename</param>
[Head("__admin/files/{filename}")]
Task FileExistsAsync([Path] string filename);
}
}

View File

@@ -0,0 +1,35 @@
using System;
namespace WireMock.Exceptions
{
/// <summary>
/// WireMockException
/// </summary>
/// <seealso cref="Exception" />
public class WireMockException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="WireMockException"/> class.
/// </summary>
public WireMockException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WireMockException"/> class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public WireMockException(string message) : base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WireMockException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="inner">The inner.</param>
public WireMockException(string message, Exception inner) : base(message, inner)
{
}
}
}

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic;
using JetBrains.Annotations;
using System.Collections.Generic;
namespace WireMock.Handlers
{
@@ -10,7 +11,7 @@ namespace WireMock.Handlers
/// <summary>
/// Gets the folder where the static mappings are located. For local file system, this would be `{CurrentFolder}/__admin/mappings`.
/// </summary>
/// <returns>The foldername.</returns>
/// <returns>The folder name.</returns>
string GetMappingFolder();
/// <summary>
@@ -18,32 +19,67 @@ namespace WireMock.Handlers
/// </summary>
/// <param name="path">The path.</param>
/// <returns>true if path refers to an existing directory; false if the directory does not exist or an error occurs when trying to determine if the specified directory exists.</returns>
bool FolderExists(string path);
bool FolderExists([NotNull] string path);
/// <summary>
/// Creates all directories and subdirectories in the specified path unless they already exist.
/// </summary>
/// <param name="path">The path.</param>
void CreateFolder(string path);
void CreateFolder([NotNull] string path);
/// <summary>
/// Returns an enumerable collection of file names in a specified path.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by path.</returns>
IEnumerable<string> EnumerateFiles(string path);
IEnumerable<string> EnumerateFiles([NotNull] string path);
/// <summary>
/// Read a static mapping file as text.
/// </summary>
/// <param name="path">The path (folder + filename with .json extension).</param>
string ReadMappingFile(string path);
/// <returns>The file content as text.</returns>
string ReadMappingFile([NotNull] string path);
/// <summary>
/// Write the static mapping.
/// Write the static mapping file.
/// </summary>
/// <param name="path">The path (folder + filename with .json extension).</param>
/// <param name="text">The text.</param>
void WriteMappingFile(string path, string text);
void WriteMappingFile([NotNull] string path, [NotNull] string text);
/// <summary>
/// Read a response body file as text.
/// </summary>
/// <param name="path">The path or filename from the file to read.</param>
/// <returns>The file content as bytes.</returns>
byte[] ReadResponseBodyAsFile([NotNull] string path);
/// <summary>
/// Delete a file.
/// </summary>
/// <param name="filename">The filename.</param>
void DeleteFile([NotNull] string filename);
/// <summary>
/// Determines whether the given path refers to an existing file on disk.
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>true if path refers to an existing file; false if the file does not exist.</returns>
bool FileExists([NotNull] string filename);
/// <summary>
/// Write a file.
/// </summary>
/// <param name="filename">The filename.</param>
/// <param name="bytes">The bytes.</param>
void WriteFile([NotNull] string filename, [NotNull] byte[] bytes);
/// <summary>
/// Read a file as bytes.
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns>The file content as bytes.</returns>
byte[] ReadFile([NotNull] string filename);
}
}

View File

@@ -1,6 +1,5 @@
using System.Collections.Generic;
using System.IO;
using JetBrains.Annotations;
using WireMock.Validation;
namespace WireMock.Handlers
@@ -13,7 +12,7 @@ namespace WireMock.Handlers
private static readonly string AdminMappingsFolder = Path.Combine("__admin", "mappings");
/// <inheritdoc cref="IFileSystemHandler.FolderExists"/>
public bool FolderExists([NotNull] string path)
public bool FolderExists(string path)
{
Check.NotNullOrEmpty(path, nameof(path));
@@ -21,7 +20,7 @@ namespace WireMock.Handlers
}
/// <inheritdoc cref="IFileSystemHandler.CreateFolder"/>
public void CreateFolder([NotNull] string path)
public void CreateFolder(string path)
{
Check.NotNullOrEmpty(path, nameof(path));
@@ -29,7 +28,7 @@ namespace WireMock.Handlers
}
/// <inheritdoc cref="IFileSystemHandler.EnumerateFiles"/>
public IEnumerable<string> EnumerateFiles([NotNull] string path)
public IEnumerable<string> EnumerateFiles(string path)
{
Check.NotNullOrEmpty(path, nameof(path));
@@ -43,20 +42,73 @@ namespace WireMock.Handlers
}
/// <inheritdoc cref="IFileSystemHandler.ReadMappingFile"/>
public string ReadMappingFile([NotNull] string path)
public string ReadMappingFile(string path)
{
Check.NotNullOrEmpty(path, nameof(path));
return File.ReadAllText(path);
}
/// <inheritdoc cref="IFileSystemHandler.WriteMappingFile"/>
public void WriteMappingFile([NotNull] string path, [NotNull] string text)
/// <inheritdoc cref="IFileSystemHandler.WriteMappingFile(string, string)"/>
public void WriteMappingFile(string path, string text)
{
Check.NotNullOrEmpty(path, nameof(path));
Check.NotNull(text, nameof(text));
File.WriteAllText(path, text);
}
/// <inheritdoc cref="IFileSystemHandler.ReadResponseBodyAsFile"/>
public byte[] ReadResponseBodyAsFile(string path)
{
Check.NotNullOrEmpty(path, nameof(path));
// In case the path is a filename, the path will be adjusted to the MappingFolder.
// Else the path will just be as-is.
return File.ReadAllBytes(Path.GetFileName(path) == path ? Path.Combine(GetMappingFolder(), path) : path);
}
/// <inheritdoc cref="IFileSystemHandler.FileExists"/>
public bool FileExists(string filename)
{
Check.NotNullOrEmpty(filename, nameof(filename));
return File.Exists(AdjustPath(filename));
}
/// <inheritdoc cref="IFileSystemHandler.WriteFile(string, byte[])"/>
public void WriteFile(string filename, byte[] bytes)
{
Check.NotNullOrEmpty(filename, nameof(filename));
Check.NotNull(bytes, nameof(bytes));
File.WriteAllBytes(AdjustPath(filename), bytes);
}
/// <inheritdoc cref="IFileSystemHandler.DeleteFile"/>
public void DeleteFile(string filename)
{
Check.NotNullOrEmpty(filename, nameof(filename));
File.Delete(AdjustPath(filename));
}
/// <inheritdoc cref="IFileSystemHandler.ReadFile"/>
public byte[] ReadFile(string filename)
{
Check.NotNullOrEmpty(filename, nameof(filename));
return File.ReadAllBytes(AdjustPath(filename));
}
/// <summary>
/// Adjusts the path to the MappingFolder.
/// </summary>
/// <param name="filename">The path.</param>
/// <returns>Adjusted path</returns>
private string AdjustPath(string filename)
{
return Path.Combine(GetMappingFolder(), filename);
}
}
}

View File

@@ -39,7 +39,12 @@ namespace WireMock.Matchers
/// <inheritdoc cref="IStringMatcher.IsMatch"/>
public double IsMatch(string input)
{
return MatchBehaviourHelper.Convert(MatchBehaviour, MatchScores.ToScore(_values.Select(value => value.Equals(input))));
if (_values.Length == 1)
{
return MatchBehaviourHelper.Convert(MatchBehaviour, MatchScores.ToScore(_values[0] == input));
}
return MatchBehaviourHelper.Convert(MatchBehaviour, MatchScores.ToScore(_values.Contains(input)));
}
/// <inheritdoc cref="IStringMatcher.GetPatterns"/>

View File

@@ -1,5 +1,5 @@
using System.Linq;
using JetBrains.Annotations;
using JetBrains.Annotations;
using System.Linq;
using WireMock.Validation;
namespace WireMock.Matchers
@@ -10,8 +10,9 @@ namespace WireMock.Matchers
/// <seealso cref="IObjectMatcher" />
public class ExactObjectMatcher : IObjectMatcher
{
private readonly object _object;
private readonly byte[] _bytes;
public object ValueAsObject { get; }
public byte[] ValueAsBytes { get; }
/// <inheritdoc cref="IMatcher.MatchBehaviour"/>
public MatchBehaviour MatchBehaviour { get; }
@@ -33,7 +34,7 @@ namespace WireMock.Matchers
{
Check.NotNull(value, nameof(value));
_object = value;
ValueAsObject = value;
MatchBehaviour = matchBehaviour;
}
@@ -54,14 +55,14 @@ namespace WireMock.Matchers
{
Check.NotNull(value, nameof(value));
_bytes = value;
ValueAsBytes = value;
MatchBehaviour = matchBehaviour;
}
/// <inheritdoc cref="IObjectMatcher.IsMatch"/>
public double IsMatch(object input)
{
bool equals = _object != null ? Equals(_object, input) : _bytes.SequenceEqual((byte[])input);
bool equals = ValueAsObject != null ? Equals(ValueAsObject, input) : ValueAsBytes.SequenceEqual((byte[])input);
return MatchBehaviourHelper.Convert(MatchBehaviour, MatchScores.ToScore(equals));
}

View File

@@ -0,0 +1,83 @@
using DevLab.JmesPath;
using JetBrains.Annotations;
using Newtonsoft.Json;
using System.Linq;
using WireMock.Validation;
namespace WireMock.Matchers
{
/// <summary>
/// http://jmespath.org/
/// </summary>
public class JmesPathMatcher : IStringMatcher, IObjectMatcher
{
private readonly string[] _patterns;
/// <inheritdoc cref="IMatcher.MatchBehaviour"/>
public MatchBehaviour MatchBehaviour { get; }
/// <summary>
/// Initializes a new instance of the <see cref="JmesPathMatcher"/> class.
/// </summary>
/// <param name="patterns">The patterns.</param>
public JmesPathMatcher([NotNull] params string[] patterns) : this(MatchBehaviour.AcceptOnMatch, patterns)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JmesPathMatcher"/> class.
/// </summary>
/// <param name="matchBehaviour">The match behaviour.</param>
/// <param name="patterns">The patterns.</param>
public JmesPathMatcher(MatchBehaviour matchBehaviour, [NotNull] params string[] patterns)
{
Check.NotNull(patterns, nameof(patterns));
MatchBehaviour = matchBehaviour;
_patterns = patterns;
}
/// <inheritdoc cref="IStringMatcher.IsMatch"/>
public double IsMatch(string input)
{
double match = MatchScores.Mismatch;
if (input != null)
{
try
{
match = MatchScores.ToScore(_patterns.Select(pattern => bool.Parse(new JmesPath().Transform(input, pattern))));
}
catch (JsonException)
{
// just ignore JsonException
}
}
return MatchBehaviourHelper.Convert(MatchBehaviour, match);
}
/// <inheritdoc cref="IObjectMatcher.IsMatch"/>
public double IsMatch(object input)
{
double match = MatchScores.Mismatch;
// When input is null or byte[], return Mismatch.
if (input != null && !(input is byte[]))
{
string inputAsString = JsonConvert.SerializeObject(input);
return IsMatch(inputAsString);
}
return MatchBehaviourHelper.Convert(MatchBehaviour, match);
}
/// <inheritdoc cref="IStringMatcher.GetPatterns"/>
public string[] GetPatterns()
{
return _patterns;
}
/// <inheritdoc cref="IMatcher.Name"/>
public string Name => "JmesPathMatcher";
}
}

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace WireMock.Matchers
@@ -54,6 +55,7 @@ namespace WireMock.Matchers
/// </summary>
/// <param name="values">The values.</param>
/// <returns>average score</returns>
[SuppressMessage("ReSharper", "PossibleMultipleEnumeration")]
public static double ToScore(IEnumerable<bool> values)
{
return values.Any() ? values.Select(ToScore).Average() : Mismatch;
@@ -64,6 +66,7 @@ namespace WireMock.Matchers
/// </summary>
/// <param name="values">The values.</param>
/// <returns>average score</returns>
[SuppressMessage("ReSharper", "PossibleMultipleEnumeration")]
public static double ToScore(IEnumerable<double> values)
{
return values.Any() ? values.Average() : Mismatch;

View File

@@ -1,7 +1,7 @@
using System;
using JetBrains.Annotations;
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using WireMock.Util;
using WireMock.Validation;
@@ -24,6 +24,11 @@ namespace WireMock.Matchers.Request
/// </summary>
public string Key { get; }
/// <summary>
/// Defines if the key should be matched using case-ignore.
/// </summary>
public bool? IgnoreCase { get; private set; }
/// <summary>
/// The matchers.
/// </summary>
@@ -34,7 +39,8 @@ namespace WireMock.Matchers.Request
/// </summary>
/// <param name="matchBehaviour">The match behaviour.</param>
/// <param name="key">The key.</param>
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key) : this(matchBehaviour, key, (IStringMatcher[])null)
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key, bool ignoreCase) : this(matchBehaviour, key, ignoreCase, (IStringMatcher[])null)
{
}
@@ -43,8 +49,9 @@ namespace WireMock.Matchers.Request
/// </summary>
/// <param name="matchBehaviour">The match behaviour.</param>
/// <param name="key">The key.</param>
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
/// <param name="values">The values.</param>
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key, [CanBeNull] string[] values) : this(matchBehaviour, key, values?.Select(value => new ExactMatcher(matchBehaviour, value)).Cast<IStringMatcher>().ToArray())
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key, bool ignoreCase, [CanBeNull] string[] values) : this(matchBehaviour, key, ignoreCase, values?.Select(value => new ExactMatcher(matchBehaviour, value)).Cast<IStringMatcher>().ToArray())
{
}
@@ -53,13 +60,15 @@ namespace WireMock.Matchers.Request
/// </summary>
/// <param name="matchBehaviour">The match behaviour.</param>
/// <param name="key">The key.</param>
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
/// <param name="matchers">The matchers.</param>
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key, [CanBeNull] IStringMatcher[] matchers)
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key, bool ignoreCase, [CanBeNull] IStringMatcher[] matchers)
{
Check.NotNull(key, nameof(key));
_matchBehaviour = matchBehaviour;
Key = key;
IgnoreCase = ignoreCase;
Matchers = matchers;
}
@@ -88,7 +97,7 @@ namespace WireMock.Matchers.Request
return MatchScores.ToScore(requestMessage.Query != null && Funcs.Any(f => f(requestMessage.Query)));
}
WireMockList<string> valuesPresentInRequestMessage = requestMessage.GetParameter(Key);
WireMockList<string> valuesPresentInRequestMessage = requestMessage.GetParameter(Key, IgnoreCase ?? false);
if (valuesPresentInRequestMessage == null)
{
// Key is not present at all, just return Mismatch
@@ -97,15 +106,8 @@ namespace WireMock.Matchers.Request
if (Matchers != null && Matchers.Any())
{
// Matchers are defined, just use the matchers to calculate the match score.
var scores = new List<double>();
foreach (string valuePresentInRequestMessage in valuesPresentInRequestMessage)
{
double score = Matchers.Max(m => m.IsMatch(valuePresentInRequestMessage));
scores.Add(score);
}
return scores.Any() ? scores.Average() : MatchScores.Mismatch;
// Return the score based on Matchers and valuesPresentInRequestMessage
return CalculateScore(valuesPresentInRequestMessage);
}
if (Matchers == null || !Matchers.Any())
@@ -116,5 +118,35 @@ namespace WireMock.Matchers.Request
return MatchScores.Mismatch;
}
private double CalculateScore(WireMockList<string> valuesPresentInRequestMessage)
{
var total = new List<double>();
// If the total patterns in all matchers > values in message, use the matcher as base
if (Matchers.Sum(m => m.GetPatterns().Length) > valuesPresentInRequestMessage.Count)
{
foreach (var matcher in Matchers)
{
double score = 0d;
foreach (string valuePresentInRequestMessage in valuesPresentInRequestMessage)
{
score += matcher.IsMatch(valuePresentInRequestMessage) / matcher.GetPatterns().Length;
}
total.Add(score);
}
}
else
{
foreach (string valuePresentInRequestMessage in valuesPresentInRequestMessage)
{
double score = Matchers.Max(m => m.IsMatch(valuePresentInRequestMessage));
total.Add(score);
}
}
return total.Any() ? MatchScores.ToScore(total) : MatchScores.Mismatch;
}
}
}

View File

@@ -8,6 +8,7 @@ using JetBrains.Annotations;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using WireMock.Handlers;
using WireMock.HttpsCertificate;
using WireMock.Logging;
using WireMock.Owin.Mappers;
@@ -58,7 +59,8 @@ namespace WireMock.Owin
_host = new WebHostBuilder()
.ConfigureServices(services =>
{
services.AddSingleton<IWireMockMiddlewareOptions>(_options);
services.AddSingleton(_options.FileSystemHandler);
services.AddSingleton(_options);
services.AddSingleton<IMappingMatcher, MappingMatcher>();
services.AddSingleton<IOwinRequestMapper, OwinRequestMapper>();
services.AddSingleton<IOwinResponseMapper, OwinResponseMapper>();

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using WireMock.Handlers;
using WireMock.Logging;
using WireMock.Matchers;
#if !USE_ASPNETCORE
@@ -34,5 +35,7 @@ namespace WireMock.Owin
Action<IAppBuilder> PreWireMockMiddlewareInit { get; set; }
Action<IAppBuilder> PostWireMockMiddlewareInit { get; set; }
IFileSystemHandler FileSystemHandler { get; set; }
}
}

View File

@@ -1,12 +1,13 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using WireMock.Handlers;
using WireMock.Http;
using WireMock.Util;
using WireMock.Validation;
#if !USE_ASPNETCORE
using IResponse = Microsoft.Owin.IOwinResponse;
#else
@@ -21,6 +22,7 @@ namespace WireMock.Owin.Mappers
/// </summary>
public class OwinResponseMapper : IOwinResponseMapper
{
private readonly IFileSystemHandler _fileSystemHandler;
private readonly Encoding _utf8NoBom = new UTF8Encoding(false);
// https://msdn.microsoft.com/en-us/library/78h415ay(v=vs.110).aspx
@@ -32,6 +34,17 @@ namespace WireMock.Owin.Mappers
{ HttpKnownHeaderNames.ContentType, (r, v) => r.ContentType = v.FirstOrDefault() }
};
/// <summary>
/// Constructor
/// </summary>
/// <param name="fileSystemHandler">The IFileSystemHandler.</param>
public OwinResponseMapper(IFileSystemHandler fileSystemHandler)
{
Check.NotNull(fileSystemHandler, nameof(fileSystemHandler));
_fileSystemHandler = fileSystemHandler;
}
/// <inheritdoc cref="IOwinResponseMapper.MapAsync"/>
public async Task MapAsync(ResponseMessage responseMessage, IResponse response)
{
@@ -60,7 +73,7 @@ namespace WireMock.Owin.Mappers
break;
case BodyType.File:
bytes = File.ReadAllBytes(responseMessage.BodyData.BodyAsFile);
bytes = _fileSystemHandler.ReadResponseBodyAsFile(responseMessage.BodyData.BodyAsFile);
break;
}

View File

@@ -6,6 +6,7 @@ using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using WireMock.Handlers;
using WireMock.Logging;
using WireMock.Owin.Mappers;
using WireMock.Util;
@@ -75,7 +76,7 @@ namespace WireMock.Owin
try
{
var requestMapper = new OwinRequestMapper();
var responseMapper = new OwinResponseMapper();
var responseMapper = new OwinResponseMapper(_options.FileSystemHandler);
var matcher = new MappingMatcher(_options);
Action<IAppBuilder> startup = app =>

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using WireMock.Handlers;
using WireMock.Logging;
using WireMock.Matchers;
using WireMock.Util;
@@ -35,5 +36,8 @@ namespace WireMock.Owin
public Action<IAppBuilder> PreWireMockMiddlewareInit { get; set; }
public Action<IAppBuilder> PostWireMockMiddlewareInit { get; set; }
/// <inheritdoc cref="IWireMockMiddlewareOptions.FileSystemHandler"/>
public IFileSystemHandler FileSystemHandler { get; set; }
}
}

View File

@@ -1,6 +1,6 @@
using System;
using JetBrains.Annotations;
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using WireMock.Matchers;
using WireMock.Util;
@@ -19,6 +19,15 @@ namespace WireMock.RequestBuilders
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithParam([NotNull] string key, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
/// <summary>
/// WithParam: matching on key only.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
/// <param name="matchBehaviour">The match behaviour (optional).</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithParam([NotNull] string key, bool ignoreCase, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
/// <summary>
/// WithParam: matching on key and values.
/// </summary>
@@ -27,6 +36,15 @@ namespace WireMock.RequestBuilders
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithParam([NotNull] string key, [CanBeNull] params string[] values);
/// <summary>
/// WithParam: matching on key and values.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
/// <param name="values">The values.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithParam([NotNull] string key, bool ignoreCase, [CanBeNull] params string[] values);
/// <summary>
/// WithParam: matching on key and matchers.
/// </summary>
@@ -35,6 +53,15 @@ namespace WireMock.RequestBuilders
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithParam([NotNull] string key, [CanBeNull] params IStringMatcher[] matchers);
/// <summary>
/// WithParam: matching on key and matchers.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
/// <param name="matchers">The matchers.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithParam([NotNull] string key, bool ignoreCase, [CanBeNull] params IStringMatcher[] matchers);
/// <summary>
/// WithParam: matching on key, values and matchBehaviour.
/// </summary>
@@ -44,6 +71,16 @@ namespace WireMock.RequestBuilders
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithParam([NotNull] string key, MatchBehaviour matchBehaviour, [CanBeNull] params string[] values);
/// <summary>
/// WithParam: matching on key, values and matchBehaviour.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
/// <param name="values">The values.</param>
/// <param name="matchBehaviour">The match behaviour.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithParam([NotNull] string key, MatchBehaviour matchBehaviour, bool ignoreCase = false, [CanBeNull] params string[] values);
/// <summary>
/// WithParam: matching on key, matchers and matchBehaviour.
/// </summary>
@@ -53,6 +90,16 @@ namespace WireMock.RequestBuilders
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithParam([NotNull] string key, MatchBehaviour matchBehaviour, [CanBeNull] params IStringMatcher[] matchers);
/// <summary>
/// WithParam: matching on key, matchers and matchBehaviour.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
/// <param name="matchers">The matchers.</param>
/// <param name="matchBehaviour">The match behaviour.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithParam([NotNull] string key, MatchBehaviour matchBehaviour, bool ignoreCase = false, [CanBeNull] params IStringMatcher[] matchers);
/// <summary>
/// WithParam: matching on functions.
/// </summary>

View File

@@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using WireMock.Util;
using WireMock.Validation;
namespace WireMock.RequestBuilders
{
public partial class Request
{
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour)"/>
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
return WithParam(key, false, matchBehaviour);
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, bool, MatchBehaviour)"/>
public IRequestBuilder WithParam(string key, bool ignoreCase, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
Check.NotNull(key, nameof(key));
_requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, ignoreCase));
return this;
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, string[])"/>
public IRequestBuilder WithParam(string key, params string[] values)
{
return WithParam(key, MatchBehaviour.AcceptOnMatch, false, values);
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, bool, string[])"/>
public IRequestBuilder WithParam(string key, bool ignoreCase, params string[] values)
{
return WithParam(key, MatchBehaviour.AcceptOnMatch, ignoreCase, values);
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, IStringMatcher[])"/>
public IRequestBuilder WithParam(string key, params IStringMatcher[] matchers)
{
return WithParam(key, MatchBehaviour.AcceptOnMatch, false, matchers);
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, bool, IStringMatcher[])"/>
public IRequestBuilder WithParam(string key, bool ignoreCase, params IStringMatcher[] matchers)
{
return WithParam(key, MatchBehaviour.AcceptOnMatch, ignoreCase, matchers);
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour, string[])"/>
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, params string[] values)
{
return WithParam(key, matchBehaviour, false, values);
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour, bool, string[])"/>
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, bool ignoreCase = false, params string[] values)
{
Check.NotNull(key, nameof(key));
_requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, ignoreCase, values));
return this;
}
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, params IStringMatcher[] matchers)
{
return WithParam(key, matchBehaviour, false, matchers);
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour, bool, IStringMatcher[])"/>
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, bool ignoreCase, params IStringMatcher[] matchers)
{
Check.NotNull(key, nameof(key));
_requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, ignoreCase, matchers));
return this;
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(Func{IDictionary{string, WireMockList{T}}, bool}[])"/>
public IRequestBuilder WithParam(params Func<IDictionary<string, WireMockList<string>>, bool>[] funcs)
{
Check.NotNullOrEmpty(funcs, nameof(funcs));
_requestMatchers.Add(new RequestMessageParamMatcher(funcs));
return this;
}
}
}

View File

@@ -12,7 +12,7 @@ namespace WireMock.RequestBuilders
/// <summary>
/// The requests.
/// </summary>
public class Request : RequestMessageCompositeMatcher, IRequestBuilder
public partial class Request : RequestMessageCompositeMatcher, IRequestBuilder
{
private readonly IList<IRequestMatcher> _requestMatchers;
@@ -291,54 +291,6 @@ namespace WireMock.RequestBuilders
return this;
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour)"/>
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
{
Check.NotNull(key, nameof(key));
_requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key));
return this;
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, string[])"/>
public IRequestBuilder WithParam(string key, params string[] values)
{
return WithParam(key, MatchBehaviour.AcceptOnMatch, values);
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, IStringMatcher[])"/>
public IRequestBuilder WithParam(string key, params IStringMatcher[] matchers)
{
return WithParam(key, MatchBehaviour.AcceptOnMatch, matchers);
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour, string[])"/>
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, params string[] values)
{
Check.NotNull(key, nameof(key));
_requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, values));
return this;
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour, IStringMatcher[])"/>
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, params IStringMatcher[] matchers)
{
Check.NotNull(key, nameof(key));
_requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, matchers));
return this;
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(Func{IDictionary{string, WireMockList{string}}, bool}[])"/>
public IRequestBuilder WithParam(params Func<IDictionary<string, WireMockList<string>>, bool>[] funcs)
{
Check.NotNullOrEmpty(funcs, nameof(funcs));
_requestMatchers.Add(new RequestMessageParamMatcher(funcs));
return this;
}
/// <inheritdoc cref="IHeadersAndCookiesRequestBuilder.WithHeader(string, string, MatchBehaviour)"/>
public IRequestBuilder WithHeader(string name, string pattern, MatchBehaviour matchBehaviour)
{

View File

@@ -1,8 +1,8 @@
using System;
using JetBrains.Annotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using JetBrains.Annotations;
using WireMock.Models;
using WireMock.Util;
using WireMock.Validation;
@@ -211,15 +211,18 @@ namespace WireMock
/// Get a query parameter.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
/// <returns>The query parameter.</returns>
public WireMockList<string> GetParameter(string key)
public WireMockList<string> GetParameter(string key, bool ignoreCase = false)
{
if (Query == null)
{
return null;
}
return Query.ContainsKey(key) ? Query[key] : null;
var query = !ignoreCase ? Query : new Dictionary<string, WireMockList<string>>(Query, StringComparer.OrdinalIgnoreCase);
return query.ContainsKey(key) ? query[key] : null;
}
}
}

View File

@@ -1,13 +1,13 @@
using JetBrains.Annotations;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Newtonsoft.Json;
using WireMock.Handlers;
using WireMock.Http;
using WireMock.Settings;
using WireMock.Transformers;
@@ -21,6 +21,7 @@ namespace WireMock.ResponseBuilders
/// </summary>
public class Response : IResponseBuilder
{
private readonly IFileSystemHandler _fileSystemHandler = new LocalFileSystemHandler();
private HttpClient _httpClientForProxy;
/// <summary>
@@ -223,10 +224,10 @@ namespace WireMock.ResponseBuilders
BodyAsFileIsCached = cache
};
if (cache)
if (cache && !UseTransformer)
{
ResponseMessage.BodyData.DetectedBodyType = BodyType.Bytes;
ResponseMessage.BodyData.BodyAsBytes = File.ReadAllBytes(filename);
ResponseMessage.BodyData.BodyAsBytes = _fileSystemHandler.ReadResponseBodyAsFile(filename);
}
else
{
@@ -255,7 +256,7 @@ namespace WireMock.ResponseBuilders
{
case BodyDestinationFormat.Bytes:
ResponseMessage.BodyData.DetectedBodyType = BodyType.Bytes;
ResponseMessage.BodyData.BodyAsBytes= encoding.GetBytes(body);
ResponseMessage.BodyData.BodyAsBytes = encoding.GetBytes(body);
break;
case BodyDestinationFormat.Json:
@@ -285,7 +286,7 @@ namespace WireMock.ResponseBuilders
BodyAsJson = body,
BodyAsJsonIndented = indented
};
return this;
}

View File

@@ -9,7 +9,10 @@ namespace WireMock
internal static class ResponseMessageBuilder
{
private static string ContentTypeJson = "application/json";
private static readonly IDictionary<string, WireMockList<string>> ContentTypeJsonHeaders = new Dictionary<string, WireMockList<string>> { { HttpKnownHeaderNames.ContentType, new WireMockList<string> { ContentTypeJson } } };
private static readonly IDictionary<string, WireMockList<string>> ContentTypeJsonHeaders = new Dictionary<string, WireMockList<string>>
{
{ HttpKnownHeaderNames.ContentType, new WireMockList<string> { ContentTypeJson } }
};
internal static ResponseMessage Create(string message, int statusCode = 200, Guid? guid = null)
{
@@ -30,5 +33,13 @@ namespace WireMock
return response;
}
internal static ResponseMessage Create(int statusCode)
{
return new ResponseMessage
{
StatusCode = statusCode
};
}
}
}

View File

@@ -66,6 +66,7 @@ namespace WireMock.Serialization
Params = paramsMatchers != null && paramsMatchers.Any() ? paramsMatchers.Select(pm => new ParamModel
{
Name = pm.Key,
IgnoreCase = pm.IgnoreCase,
Matchers = MatcherMapper.Map(pm.Matchers)
}).ToList() : null,
@@ -76,7 +77,7 @@ namespace WireMock.Serialization
},
Response = new ResponseModel
{
Delay = response.Delay?.Milliseconds
Delay = (int?)response.Delay?.TotalMilliseconds
}
};

View File

@@ -1,8 +1,8 @@
using System;
using JetBrains.Annotations;
using SimMetrics.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using SimMetrics.Net;
using WireMock.Admin.Mappings;
using WireMock.Matchers;
@@ -32,6 +32,10 @@ namespace WireMock.Serialization
case "ExactMatcher":
return new ExactMatcher(matchBehaviour, stringPatterns);
case "ExactObjectMatcher":
var bytePattern = Convert.FromBase64String(stringPatterns[0]);
return new ExactObjectMatcher(matchBehaviour, bytePattern);
case "RegexMatcher":
return new RegexMatcher(matchBehaviour, stringPatterns, matcher.IgnoreCase == true);
@@ -41,6 +45,9 @@ namespace WireMock.Serialization
case "JsonPathMatcher":
return new JsonPathMatcher(matchBehaviour, stringPatterns);
case "JmesPathMatcher":
return new JmesPathMatcher(matchBehaviour, stringPatterns);
case "XPathMatcher":
return new XPathMatcher(matchBehaviour, (string)matcher.Pattern);
@@ -73,20 +80,33 @@ namespace WireMock.Serialization
return null;
}
// If the matcher is a IStringMatcher, get the patterns.
// If the matcher is a IValueMatcher, get the value (can be string or object).
// Else empty array
object[] patterns = matcher is IStringMatcher stringMatcher ?
stringMatcher.GetPatterns().Cast<object>().ToArray() :
matcher is IValueMatcher valueMatcher ? new[] { valueMatcher.Value } :
new object[0];
bool? ignorecase = matcher is IIgnoreCaseMatcher ignoreCaseMatcher ? ignoreCaseMatcher.IgnoreCase : (bool?)null;
object[] patterns = new object[0]; // Default empty array
switch (matcher)
{
// If the matcher is a IStringMatcher, get the patterns.
case IStringMatcher stringMatcher:
patterns = stringMatcher.GetPatterns().Cast<object>().ToArray();
break;
// If the matcher is a IValueMatcher, get the value (can be string or object).
case IValueMatcher valueMatcher:
patterns = new[] { valueMatcher.Value };
break;
// If the matcher is a ExactObjectMatcher, get the ValueAsObject or ValueAsBytes.
case ExactObjectMatcher exactObjectMatcher:
patterns = new[] { exactObjectMatcher.ValueAsObject ?? exactObjectMatcher.ValueAsBytes };
break;
}
bool? ignoreCase = matcher is IIgnoreCaseMatcher ignoreCaseMatcher ? ignoreCaseMatcher.IgnoreCase : (bool?)null;
bool? rejectOnMatch = matcher.MatchBehaviour == MatchBehaviour.RejectOnMatch ? true : (bool?)null;
return new MatcherModel
{
RejectOnMatch = rejectOnMatch,
IgnoreCase = ignorecase,
IgnoreCase = ignoreCase,
Name = matcher.Name,
Pattern = patterns.Length == 1 ? patterns.First() : null,
Patterns = patterns.Length > 1 ? patterns : null

View File

@@ -1,3 +1,6 @@
using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
@@ -5,9 +8,6 @@ using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WireMock.Admin.Mappings;
using WireMock.Admin.Scenarios;
using WireMock.Admin.Settings;
@@ -34,13 +34,14 @@ namespace WireMock.Server
private const int AdminPriority = int.MinValue;
private const int ProxyPriority = 1000;
private const string ContentTypeJson = "application/json";
private const string AdminFiles = "/__admin/files";
private const string AdminMappings = "/__admin/mappings";
private const string AdminRequests = "/__admin/requests";
private const string AdminSettings = "/__admin/settings";
private const string AdminScenarios = "/__admin/scenarios";
private readonly RegexMatcher _adminMappingsGuidPathMatcher = new RegexMatcher(MatchBehaviour.AcceptOnMatch, @"^\/__admin\/mappings\/(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$");
private readonly RegexMatcher _adminRequestsGuidPathMatcher = new RegexMatcher(MatchBehaviour.AcceptOnMatch, @"^\/__admin\/requests\/(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$");
private readonly RegexMatcher _adminMappingsGuidPathMatcher = new RegexMatcher(MatchBehaviour.AcceptOnMatch, @"^\/__admin\/mappings\/([0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12})$");
private readonly RegexMatcher _adminRequestsGuidPathMatcher = new RegexMatcher(MatchBehaviour.AcceptOnMatch, @"^\/__admin\/requests\/([0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12})$");
private readonly JsonSerializerSettings _settings = new JsonSerializerSettings
{
@@ -97,10 +98,17 @@ namespace WireMock.Server
// __admin/scenarios/reset
Given(Request.Create().WithPath(AdminScenarios + "/reset").UsingPost()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(ScenariosReset));
// __admin/files/{filename}
Given(Request.Create().WithPath(_adminFilesFilenamePathMatcher).UsingPost()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(FilePost));
Given(Request.Create().WithPath(_adminFilesFilenamePathMatcher).UsingPut()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(FilePut));
Given(Request.Create().WithPath(_adminFilesFilenamePathMatcher).UsingGet()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(FileGet));
Given(Request.Create().WithPath(_adminFilesFilenamePathMatcher).UsingHead()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(FileHead));
Given(Request.Create().WithPath(_adminFilesFilenamePathMatcher).UsingDelete()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(FileDelete));
}
#endregion
#region StaticMappings
#region StaticMappings
/// <summary>
/// Saves the static mappings.
/// </summary>
@@ -206,14 +214,17 @@ namespace WireMock.Server
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(path);
MappingModel mappingModel = JsonConvert.DeserializeObject<MappingModel>(_fileSystemHandler.ReadMappingFile(path));
if (Guid.TryParse(filenameWithoutExtension, out Guid guidFromFilename))
var mappingModels = DeserializeObjectToArray<MappingModel>(JsonConvert.DeserializeObject(_fileSystemHandler.ReadMappingFile(path)));
foreach (var mappingModel in mappingModels)
{
DeserializeAndAddOrUpdateMapping(mappingModel, guidFromFilename, path);
}
else
{
DeserializeAndAddOrUpdateMapping(mappingModel, null, path);
if (mappingModels.Length == 1 && Guid.TryParse(filenameWithoutExtension, out Guid guidFromFilename))
{
DeserializeAndAddOrUpdateMapping(mappingModel, guidFromFilename, path);
}
else
{
DeserializeAndAddOrUpdateMapping(mappingModel, null, path);
}
}
}
#endregion
@@ -262,7 +273,7 @@ namespace WireMock.Server
request.WithPath(requestMessage.Path);
request.UsingMethod(requestMessage.Method);
requestMessage.Query.Loop((key, value) => request.WithParam(key, value.ToArray()));
requestMessage.Query.Loop((key, value) => request.WithParam(key, false, value.ToArray()));
requestMessage.Cookies.Loop((key, value) => request.WithCookie(key, value));
var allBlackListedHeaders = new List<string>(blacklistedHeaders) { "Cookie" };
@@ -274,13 +285,19 @@ namespace WireMock.Server
}
});
if (requestMessage.BodyData?.DetectedBodyType == BodyType.Json)
switch (requestMessage.BodyData?.DetectedBodyType)
{
request.WithBody(new JsonMatcher(MatchBehaviour.AcceptOnMatch, requestMessage.BodyData.BodyAsJson));
}
else if (requestMessage.BodyData?.DetectedBodyType == BodyType.String)
{
request.WithBody(new ExactMatcher(MatchBehaviour.AcceptOnMatch, requestMessage.BodyData.BodyAsString));
case BodyType.Json:
request.WithBody(new JsonMatcher(MatchBehaviour.AcceptOnMatch, requestMessage.BodyData.BodyAsJson));
break;
case BodyType.String:
request.WithBody(new ExactMatcher(MatchBehaviour.AcceptOnMatch, requestMessage.BodyData.BodyAsString));
break;
case BodyType.Bytes:
request.WithBody(new ExactObjectMatcher(MatchBehaviour.AcceptOnMatch, requestMessage.BodyData.BodyAsBytes));
break;
}
var response = Response.Create(responseMessage);
@@ -412,11 +429,21 @@ namespace WireMock.Server
private ResponseMessage MappingsPost(RequestMessage requestMessage)
{
Guid? guid;
try
{
var mappingModel = DeserializeObject<MappingModel>(requestMessage);
guid = DeserializeAndAddOrUpdateMapping(mappingModel);
var mappingModels = DeserializeRequestMessageToArray<MappingModel>(requestMessage);
if (mappingModels.Length == 1)
{
Guid? guid = DeserializeAndAddOrUpdateMapping(mappingModels[0]);
return ResponseMessageBuilder.Create("Mapping added", 201, guid);
}
foreach (var mappingModel in mappingModels)
{
DeserializeAndAddOrUpdateMapping(mappingModel);
}
return ResponseMessageBuilder.Create("Mappings added", 201);
}
catch (ArgumentException a)
{
@@ -428,8 +455,6 @@ namespace WireMock.Server
_logger.Error("HttpStatusCode set to 500 {0}", e);
return ResponseMessageBuilder.Create(e.ToString(), 500);
}
return ResponseMessageBuilder.Create("Mapping added", 201, guid);
}
private Guid? DeserializeAndAddOrUpdateMapping(MappingModel mappingModel, Guid? guid = null, string path = null)
@@ -674,7 +699,8 @@ namespace WireMock.Server
{
foreach (var paramModel in requestModel.Params.Where(c => c.Matchers != null))
{
requestBuilder = requestBuilder.WithParam(paramModel.Name, paramModel.Matchers.Select(MatcherMapper.Map).Cast<IStringMatcher>().ToArray());
bool ignoreCase = paramModel?.IgnoreCase ?? false;
requestBuilder = requestBuilder.WithParam(paramModel.Name, ignoreCase, paramModel.Matchers.Select(MatcherMapper.Map).Cast<IStringMatcher>().ToArray());
}
}
@@ -696,6 +722,11 @@ namespace WireMock.Server
responseBuilder = responseBuilder.WithDelay(responseModel.Delay.Value);
}
if (responseModel.UseTransformer)
{
responseBuilder = responseBuilder.WithTransformer();
}
if (!string.IsNullOrEmpty(responseModel.ProxyUrl))
{
if (string.IsNullOrEmpty(responseModel.X509Certificate2ThumbprintOrSubjectName))
@@ -752,11 +783,6 @@ namespace WireMock.Server
responseBuilder = responseBuilder.WithBodyFromFile(responseModel.BodyAsFile);
}
if (responseModel.UseTransformer)
{
responseBuilder = responseBuilder.WithTransformer();
}
return responseBuilder;
}
@@ -793,5 +819,28 @@ namespace WireMock.Server
return default(T);
}
private T[] DeserializeRequestMessageToArray<T>(RequestMessage requestMessage)
{
if (requestMessage?.BodyData?.DetectedBodyType == BodyType.Json)
{
var bodyAsJson = requestMessage.BodyData.BodyAsJson;
return DeserializeObjectToArray<T>(bodyAsJson);
}
return default(T[]);
}
private T[] DeserializeObjectToArray<T>(object value)
{
if (value is JArray jArray)
{
return jArray.ToObject<T[]>();
}
var singleResult = ((JObject)value).ToObject<T>();
return new[] { singleResult };
}
}
}

View File

@@ -0,0 +1,114 @@
using System.IO;
using System.Linq;
using System.Text;
using WireMock.Matchers;
using WireMock.Util;
namespace WireMock.Server
{
public partial class FluentMockServer
{
private readonly RegexMatcher _adminFilesFilenamePathMatcher = new RegexMatcher(MatchBehaviour.AcceptOnMatch, @"^\/__admin\/files\/.*$");
private static readonly Encoding[] FileBodyIsString = { Encoding.UTF8, Encoding.ASCII };
#region Files/{filename}
private ResponseMessage FilePost(RequestMessage requestMessage)
{
string filename = GetFileNameFromRequestMessage(requestMessage);
string mappingFolder = _fileSystemHandler.GetMappingFolder();
if (!_fileSystemHandler.FolderExists(mappingFolder))
{
_fileSystemHandler.CreateFolder(mappingFolder);
}
_fileSystemHandler.WriteFile(filename, requestMessage.BodyAsBytes);
return ResponseMessageBuilder.Create("File created");
}
private ResponseMessage FilePut(RequestMessage requestMessage)
{
string filename = GetFileNameFromRequestMessage(requestMessage);
if (!_fileSystemHandler.FileExists(filename))
{
_logger.Info("The file '{0}' does not exist, updating file will be skipped.", filename);
return ResponseMessageBuilder.Create("File is not found", 404);
}
_fileSystemHandler.WriteFile(filename, requestMessage.BodyAsBytes);
return ResponseMessageBuilder.Create("File updated");
}
private ResponseMessage FileGet(RequestMessage requestMessage)
{
string filename = GetFileNameFromRequestMessage(requestMessage);
if (!_fileSystemHandler.FileExists(filename))
{
_logger.Info("The file '{0}' does not exist.", filename);
return ResponseMessageBuilder.Create("File is not found", 404);
}
byte[] bytes = _fileSystemHandler.ReadFile(filename);
var response = new ResponseMessage
{
StatusCode = 200,
BodyData = new BodyData
{
BodyAsBytes = bytes,
DetectedBodyType = BodyType.Bytes,
DetectedBodyTypeFromContentType = BodyType.None
}
};
if (BytesEncodingUtils.TryGetEncoding(bytes, out Encoding encoding) && FileBodyIsString.Select(x => x.Equals(encoding)).Any())
{
response.BodyData.DetectedBodyType = BodyType.String;
response.BodyData.BodyAsString = encoding.GetString(bytes);
}
return response;
}
/// <summary>
/// Checks if file exists.
/// Note: Response is returned with no body as a head request doesn't accept a body, only the status code.
/// </summary>
/// <param name="requestMessage">The request message.</param>
private ResponseMessage FileHead(RequestMessage requestMessage)
{
string filename = GetFileNameFromRequestMessage(requestMessage);
if (!_fileSystemHandler.FileExists(filename))
{
_logger.Info("The file '{0}' does not exist.", filename);
return ResponseMessageBuilder.Create(404);
}
return ResponseMessageBuilder.Create(204);
}
private ResponseMessage FileDelete(RequestMessage requestMessage)
{
string filename = GetFileNameFromRequestMessage(requestMessage);
if (!_fileSystemHandler.FileExists(filename))
{
_logger.Info("The file '{0}' does not exist.", filename);
return ResponseMessageBuilder.Create("File is not deleted", 404);
}
_fileSystemHandler.DeleteFile(filename);
return ResponseMessageBuilder.Create("File deleted.");
}
private string GetFileNameFromRequestMessage(RequestMessage requestMessage)
{
return Path.GetFileName(requestMessage.Path.Substring(AdminFiles.Length + 1));
}
#endregion
}
}

View File

@@ -6,6 +6,7 @@ using System.Linq;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
using WireMock.Exceptions;
using WireMock.Handlers;
using WireMock.Logging;
using WireMock.Matchers;
@@ -202,6 +203,7 @@ namespace WireMock.Server
Urls = new[] { $"{(settings.UseSSL == true ? "https" : "http")}://localhost:{port}" };
}
_options.FileSystemHandler = settings.FileSystemHandler;
_options.PreWireMockMiddlewareInit = settings.PreWireMockMiddlewareInit;
_options.PostWireMockMiddlewareInit = settings.PostWireMockMiddlewareInit;
_options.Logger = _logger;
@@ -213,21 +215,27 @@ namespace WireMock.Server
#endif
Ports = _httpServer.Ports;
_httpServer.StartAsync();
var startTask = _httpServer.StartAsync();
using (var ctsStartTimeout = new CancellationTokenSource(settings.StartTimeout))
{
while (!_httpServer.IsStarted)
{
// Throw out exception if service start fails
// Throw exception if service start fails
if (_httpServer.RunningException != null)
{
throw new Exception($"Service start failed with error: {_httpServer.RunningException.Message}", _httpServer.RunningException);
throw new WireMockException($"Service start failed with error: {_httpServer.RunningException.Message}", _httpServer.RunningException);
}
// Respect start timeout setting by throwing TimeoutException
if (ctsStartTimeout.IsCancellationRequested)
{
// In case of an aggregate exception, throw the exception.
if (startTask.Exception != null)
{
throw new WireMockException($"Service start failed with error: {startTask.Exception.Message}", startTask.Exception);
}
// Else throw TimeoutException
throw new TimeoutException($"Service start timed out after {TimeSpan.FromMilliseconds(settings.StartTimeout)}");
}

View File

@@ -1,14 +1,20 @@
namespace WireMock.Transformers
using HandlebarsDotNet;
namespace WireMock.Transformers
{
internal static class HandlebarsHelpers
{
public static void Register()
public static void Register(IHandlebars handlebarsContext)
{
HandleBarsRegex.Register();
HandleBarsRegex.Register(handlebarsContext);
HandleBarsJsonPath.Register();
HandleBarsJsonPath.Register(handlebarsContext);
HandleBarsLinq.Register();
HandleBarsLinq.Register(handlebarsContext);
HandleBarsRandom.Register(handlebarsContext);
HandleBarsXeger.Register(handlebarsContext);
}
}
}

View File

@@ -9,15 +9,15 @@ namespace WireMock.Transformers
{
internal static class HandleBarsJsonPath
{
public static void Register()
public static void Register(IHandlebars handlebarsContext)
{
Handlebars.RegisterHelper("JsonPath.SelectToken", (writer, context, arguments) =>
handlebarsContext.RegisterHelper("JsonPath.SelectToken", (writer, context, arguments) =>
{
(JObject valueToProcess, string jsonpath) = ParseArguments(arguments);
(JObject valueToProcess, string jsonPath) = ParseArguments(arguments);
try
{
var result = valueToProcess.SelectToken(jsonpath);
var result = valueToProcess.SelectToken(jsonPath);
writer.WriteSafeString(result);
}
catch (JsonException)
@@ -26,13 +26,13 @@ namespace WireMock.Transformers
}
});
Handlebars.RegisterHelper("JsonPath.SelectTokens", (writer, options, context, arguments) =>
handlebarsContext.RegisterHelper("JsonPath.SelectTokens", (writer, options, context, arguments) =>
{
(JObject valueToProcess, string jsonpath) = ParseArguments(arguments);
(JObject valueToProcess, string jsonPath) = ParseArguments(arguments);
try
{
var values = valueToProcess.SelectTokens(jsonpath);
var values = valueToProcess.SelectTokens(jsonPath);
if (values != null)
{
options.Template(writer, values.ToDictionary(value => value.Path, value => value));

View File

@@ -11,9 +11,9 @@ namespace WireMock.Transformers
{
internal static class HandleBarsLinq
{
public static void Register()
public static void Register(IHandlebars handlebarsContext)
{
Handlebars.RegisterHelper("Linq", (writer, context, arguments) =>
handlebarsContext.RegisterHelper("Linq", (writer, context, arguments) =>
{
(JToken valueToProcess, string linqStatement) = ParseArguments(arguments);
@@ -28,7 +28,7 @@ namespace WireMock.Transformers
}
});
Handlebars.RegisterHelper("Linq", (writer, options, context, arguments) =>
handlebarsContext.RegisterHelper("Linq", (writer, options, context, arguments) =>
{
(JToken valueToProcess, string linqStatement) = ParseArguments(arguments);

View File

@@ -0,0 +1,113 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using HandlebarsDotNet;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RandomDataGenerator.FieldOptions;
using RandomDataGenerator.Randomizers;
using WireMock.Validation;
namespace WireMock.Transformers
{
internal static class HandleBarsRandom
{
public static void Register(IHandlebars handlebarsContext)
{
handlebarsContext.RegisterHelper("Random", (writer, context, arguments) =>
{
object value = GetRandomValue(arguments);
writer.Write(value);
});
handlebarsContext.RegisterHelper("Random", (writer, options, context, arguments) =>
{
object value = GetRandomValue(arguments);
options.Template(writer, value);
});
}
private static object GetRandomValue(object[] arguments)
{
var fieldOptions = GetFieldOptionsFromArguments(arguments);
dynamic randomizer = RandomizerFactory.GetRandomizerAsDynamic(fieldOptions);
// Format DateTime as ISO 8601
if (fieldOptions is IFieldOptionsDateTime)
{
DateTime? date = randomizer.Generate();
return date?.ToString("s", CultureInfo.InvariantCulture);
}
// If the IFieldOptionsGuid defines Uppercase, use the 'GenerateAsString' method.
if (fieldOptions is IFieldOptionsGuid fieldOptionsGuid)
{
return fieldOptionsGuid.Uppercase ? randomizer.GenerateAsString() : randomizer.Generate();
}
return randomizer.Generate();
}
private static FieldOptionsAbstract GetFieldOptionsFromArguments(object[] arguments)
{
Check.Condition(arguments, args => args.Length > 0, nameof(arguments));
Check.NotNull(arguments[0], "arguments[0]");
var properties = (Dictionary<string, object>)arguments[0];
var newProperties = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> property in properties.Where(p => p.Key != "Type"))
{
if (property.Value.GetType().Name == "UndefinedBindingResult")
{
if (TryParseSpecialValue(property.Value, out object parsedValue))
{
newProperties.Add(property.Key, parsedValue);
}
}
else
{
newProperties.Add(property.Key, property.Value);
}
}
return FieldOptionsFactory.GetFieldOptions((string)properties["Type"], newProperties);
}
/// <summary>
/// In case it's an UndefinedBindingResult, just try to convert the value using Json
/// This logic adds functionality like parsing an array
/// </summary>
/// <param name="value">The property value</param>
/// <param name="parsedValue">The parsed value</param>
/// <returns>true in case parsing is ok, else false</returns>
private static bool TryParseSpecialValue(object value, out object parsedValue)
{
parsedValue = null;
string propertyValueAsString = value.ToString();
try
{
JToken jToken = JToken.Parse(propertyValueAsString);
switch (jToken)
{
case JArray jTokenArray:
parsedValue = jTokenArray.ToObject<string[]>().ToList(); // Just convert to a String List to enable Random StringList
break;
default:
return jToken.ToObject<dynamic>();
}
return true;
}
catch (JsonException)
{
// Ignore and don't add this value
}
return false;
}
}
}

View File

@@ -9,9 +9,9 @@ namespace WireMock.Transformers
{
internal static class HandleBarsRegex
{
public static void Register()
public static void Register(IHandlebars handlebarsContext)
{
Handlebars.RegisterHelper("Regex.Match", (writer, context, arguments) =>
handlebarsContext.RegisterHelper("Regex.Match", (writer, context, arguments) =>
{
(string stringToProcess, string regexPattern, object defaultValue) = ParseArguments(arguments);
@@ -27,7 +27,7 @@ namespace WireMock.Transformers
}
});
Handlebars.RegisterHelper("Regex.Match", (writer, options, context, arguments) =>
handlebarsContext.RegisterHelper("Regex.Match", (writer, options, context, arguments) =>
{
(string stringToProcess, string regexPattern, object defaultValue) = ParseArguments(arguments);

View File

@@ -0,0 +1,39 @@
using System;
using Fare;
using HandlebarsDotNet;
using WireMock.Validation;
namespace WireMock.Transformers
{
internal static class HandleBarsXeger
{
public static void Register(IHandlebars handlebarsContext)
{
handlebarsContext.RegisterHelper("Xeger", (writer, context, arguments) =>
{
string value = ParseArgumentAndGenerate(arguments);
writer.Write(value);
});
handlebarsContext.RegisterHelper("Xeger", (writer, options, context, arguments) =>
{
string value = ParseArgumentAndGenerate(arguments);
options.Template(writer, value);
});
}
private static string ParseArgumentAndGenerate(object[] arguments)
{
Check.Condition(arguments, args => args.Length == 1, nameof(arguments));
Check.NotNull(arguments[0], "arguments[0]");
switch (arguments[0])
{
case string pattern:
return new Xeger(pattern).Generate();
}
throw new NotSupportedException($"The value '{arguments[0]}' with type '{arguments[0]?.GetType()}' cannot be used in Handlebars Xeger.");
}
}
}

View File

@@ -1,48 +1,56 @@
using System;
using System.Collections.Generic;
using System.Linq;
using HandlebarsDotNet;
using HandlebarsDotNet;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using WireMock.Util;
namespace WireMock.Transformers
{
internal static class ResponseMessageTransformer
{
private static readonly HandlebarsConfiguration HandlebarsConfiguration = new HandlebarsConfiguration
{
UnresolvedBindingFormatter = "{0}"
};
private static readonly IHandlebars HandlebarsContext = Handlebars.Create(HandlebarsConfiguration);
static ResponseMessageTransformer()
{
HandlebarsHelpers.Register();
HandlebarsHelpers.Register(HandlebarsContext);
}
public static ResponseMessage Transform(RequestMessage requestMessage, ResponseMessage original)
{
bool bodyIsJson = original.BodyData.DetectedBodyType == BodyType.Json;
var responseMessage = new ResponseMessage { StatusCode = original.StatusCode };
if (!bodyIsJson)
{
responseMessage.BodyOriginal = original.BodyData.BodyAsString;
}
var template = new { request = requestMessage };
if (!bodyIsJson)
switch (original.BodyData.DetectedBodyType)
{
TransformBodyAsString(template, original, responseMessage);
}
else
{
TransformBodyAsJson(template, original, responseMessage);
case BodyType.Json:
TransformBodyAsJson(template, original, responseMessage);
break;
case BodyType.File:
TransformBodyAsFile(template, original, responseMessage);
break;
case BodyType.String:
responseMessage.BodyOriginal = original.BodyData.BodyAsString;
TransformBodyAsString(template, original, responseMessage);
break;
}
// Headers
var newHeaders = new Dictionary<string, WireMockList<string>>();
foreach (var header in original.Headers)
{
var templateHeaderKey = Handlebars.Compile(header.Key);
var templateHeaderKey = HandlebarsContext.Compile(header.Key);
var templateHeaderValues = header.Value
.Select(Handlebars.Compile)
.Select(HandlebarsContext.Compile)
.Select(func => func(template))
.ToArray();
@@ -60,7 +68,7 @@ namespace WireMock.Transformers
switch (original.BodyData.BodyAsJson)
{
case JObject bodyAsJObject:
jToken = bodyAsJObject;
jToken = bodyAsJObject.DeepClone();
break;
case Array bodyAsArray:
@@ -109,37 +117,60 @@ namespace WireMock.Transformers
return;
}
var templateForStringValue = Handlebars.Compile(stringValue);
var templateForStringValue = HandlebarsContext.Compile(stringValue);
string transformedString = templateForStringValue(template);
if (!string.Equals(stringValue, transformedString))
{
JToken value;
try
{
// Try to convert this string into a real JsonObject
value = JToken.Parse(transformedString);
}
catch (JsonException)
{
// Ignore JsonException and just convert to JToken
value = transformedString;
}
node.Replace(value);
ReplaceNodeValue(node, transformedString);
}
}
}
private static void ReplaceNodeValue(JToken node, string stringValue)
{
if (bool.TryParse(stringValue, out bool valueAsBoolean))
{
node.Replace(valueAsBoolean);
return;
}
JToken value;
try
{
// Try to convert this string into a JsonObject
value = JToken.Parse(stringValue);
}
catch (JsonException)
{
// Ignore JsonException and just keep string value and convert to JToken
value = stringValue;
}
node.Replace(value);
}
private static void TransformBodyAsString(object template, ResponseMessage original, ResponseMessage responseMessage)
{
var templateBody = Handlebars.Compile(original.BodyData.BodyAsString);
var templateBodyAsString = HandlebarsContext.Compile(original.BodyData.BodyAsString);
responseMessage.BodyData = new BodyData
{
DetectedBodyType = original.BodyData.DetectedBodyType,
DetectedBodyTypeFromContentType = original.BodyData.DetectedBodyTypeFromContentType,
BodyAsString = templateBody(template)
BodyAsString = templateBodyAsString(template)
};
}
private static void TransformBodyAsFile(object template, ResponseMessage original, ResponseMessage responseMessage)
{
var templateBodyAsFile = HandlebarsContext.Compile(original.BodyData.BodyAsFile);
responseMessage.BodyData = new BodyData
{
DetectedBodyType = original.BodyData.DetectedBodyType,
DetectedBodyTypeFromContentType = original.BodyData.DetectedBodyTypeFromContentType,
BodyAsFile = templateBodyAsFile(template)
};
}
}
}
}

View File

@@ -1,11 +1,11 @@
using System;
using JetBrains.Annotations;
using MimeKit;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
using MimeKit;
using Newtonsoft.Json;
using WireMock.Matchers;
using WireMock.Validation;
@@ -14,6 +14,7 @@ namespace WireMock.Util
internal static class BodyParser
{
private static readonly Encoding DefaultEncoding = Encoding.UTF8;
private static readonly Encoding[] SupportedBodyAsStringEncodingForMultipart = { Encoding.UTF8, Encoding.ASCII };
/*
HEAD - No defined body semantics.
@@ -28,6 +29,10 @@ namespace WireMock.Util
*/
private static readonly string[] AllowedBodyParseMethods = { "PUT", "POST", "OPTIONS", "PATCH" };
private static readonly IStringMatcher[] MultipartContentTypesMatchers = {
new WildcardMatcher("multipart/*", true)
};
private static readonly IStringMatcher[] JsonContentTypesMatchers = {
new WildcardMatcher("application/json", true),
new WildcardMatcher("application/vnd.*+json", true)
@@ -68,6 +73,11 @@ namespace WireMock.Util
return BodyType.Json;
}
if (MultipartContentTypesMatchers.Any(matcher => MatchScores.IsPerfect(matcher.IsMatch(contentType.MimeType))))
{
return BodyType.MultiPart;
}
return BodyType.Bytes;
}
@@ -82,6 +92,22 @@ namespace WireMock.Util
DetectedBodyTypeFromContentType = DetectBodyTypeFromContentType(contentType)
};
// In case of MultiPart: check if the BodyAsBytes is a valid UTF8 or ASCII string, in that case read as String else keep as-is
if (data.DetectedBodyTypeFromContentType == BodyType.MultiPart)
{
if (BytesEncodingUtils.TryGetEncoding(data.BodyAsBytes, out Encoding encoding) &&
SupportedBodyAsStringEncodingForMultipart.Select(x => x.Equals(encoding)).Any())
{
data.BodyAsString = encoding.GetString(data.BodyAsBytes);
data.Encoding = encoding;
data.DetectedBodyType = BodyType.String;
return data;
}
return data;
}
// Try to get the body as String
try
{

View File

@@ -28,6 +28,11 @@
/// <summary>
/// Body is a File
/// </summary>
File
File,
/// <summary>
/// Body is a MultiPart
/// </summary>
MultiPart
}
}

View File

@@ -0,0 +1,230 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WireMock.Util
{
/// <summary>
/// Based on:
/// http://utf8checker.codeplex.com
/// https://github.com/0x53A/Mvvm/blob/master/src/Mvvm/src/Utf8Checker.cs
///
/// References:
/// http://anubis.dkuug.dk/JTC1/SC2/WG2/docs/n1335
/// http://www.cl.cam.ac.uk/~mgk25/ucs/ISO-10646-UTF-8.html
/// http://www.unicode.org/versions/corrigendum1.html
/// http://www.ietf.org/rfc/rfc2279.txt
/// </summary>
public static class BytesEncodingUtils
{
/// <summary>
/// Tries the get the Encoding from an array of bytes.
/// </summary>
/// <param name="bytes">The bytes.</param>
/// <param name="encoding">The output encoding.</param>
public static bool TryGetEncoding(byte[] bytes, out Encoding encoding)
{
encoding = null;
if (bytes.All(b => b < 80))
{
encoding = Encoding.ASCII;
return true;
}
if (StartsWith(bytes, new byte[] { 0xff, 0xfe, 0x00, 0x00 }))
{
encoding = Encoding.UTF32;
return true;
}
if (StartsWith(bytes, new byte[] { 0xfe, 0xff }))
{
encoding = Encoding.BigEndianUnicode;
return true;
}
if (StartsWith(bytes, new byte[] { 0xff, 0xfe }))
{
encoding = Encoding.Unicode;
return true;
}
if (StartsWith(bytes, new byte[] { 0xef, 0xbb, 0xbf }))
{
encoding = Encoding.UTF8;
return true;
}
if (IsUtf8(bytes, bytes.Length))
{
encoding = new UTF8Encoding(false);
return true;
}
return false;
}
private static bool StartsWith(IEnumerable<byte> data, IReadOnlyCollection<byte> other)
{
byte[] arraySelf = data.Take(other.Count).ToArray();
return other.SequenceEqual(arraySelf);
}
private static bool IsUtf8(IReadOnlyList<byte> buffer, int length)
{
int position = 0;
int bytes = 0;
while (position < length)
{
if (!IsValid(buffer, position, length, ref bytes))
{
return false;
}
position += bytes;
}
return true;
}
#pragma warning disable S3776 // Cognitive Complexity of methods should not be too high
private static bool IsValid(IReadOnlyList<byte> buffer, int position, int length, ref int bytes)
{
if (length > buffer.Count)
{
throw new ArgumentException("Invalid length");
}
if (position > length - 1)
{
bytes = 0;
return true;
}
byte ch = buffer[position];
if (ch <= 0x7F)
{
bytes = 1;
return true;
}
if (ch >= 0xc2 && ch <= 0xdf)
{
if (position >= length - 2)
{
bytes = 0;
return false;
}
if (buffer[position + 1] < 0x80 || buffer[position + 1] > 0xbf)
{
bytes = 0;
return false;
}
bytes = 2;
return true;
}
if (ch == 0xe0)
{
if (position >= length - 3)
{
bytes = 0;
return false;
}
if (buffer[position + 1] < 0xa0 || buffer[position + 1] > 0xbf ||
buffer[position + 2] < 0x80 || buffer[position + 2] > 0xbf)
{
bytes = 0;
return false;
}
bytes = 3;
return true;
}
if (ch >= 0xe1 && ch <= 0xef)
{
if (position >= length - 3)
{
bytes = 0;
return false;
}
if (buffer[position + 1] < 0x80 || buffer[position + 1] > 0xbf ||
buffer[position + 2] < 0x80 || buffer[position + 2] > 0xbf)
{
bytes = 0;
return false;
}
bytes = 3;
return true;
}
if (ch == 0xf0)
{
if (position >= length - 4)
{
bytes = 0;
return false;
}
if (buffer[position + 1] < 0x90 || buffer[position + 1] > 0xbf ||
buffer[position + 2] < 0x80 || buffer[position + 2] > 0xbf ||
buffer[position + 3] < 0x80 || buffer[position + 3] > 0xbf)
{
bytes = 0;
return false;
}
bytes = 4;
return true;
}
if (ch == 0xf4)
{
if (position >= length - 4)
{
bytes = 0;
return false;
}
if (buffer[position + 1] < 0x80 || buffer[position + 1] > 0x8f ||
buffer[position + 2] < 0x80 || buffer[position + 2] > 0xbf ||
buffer[position + 3] < 0x80 || buffer[position + 3] > 0xbf)
{
bytes = 0;
return false;
}
bytes = 4;
return true;
}
if (ch >= 0xf1 && ch <= 0xf3)
{
if (position >= length - 4)
{
bytes = 0;
return false;
}
if (buffer[position + 1] < 0x80 || buffer[position + 1] > 0xbf ||
buffer[position + 2] < 0x80 || buffer[position + 2] > 0xbf ||
buffer[position + 3] < 0x80 || buffer[position + 3] > 0xbf)
{
bytes = 0;
return false;
}
bytes = 4;
return true;
}
return false;
}
}
#pragma warning restore S3776 // Cognitive Complexity of methods should not be too high
}

View File

@@ -24,6 +24,7 @@
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
<CodeAnalysisRuleSet>WireMock.Net.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
@@ -45,14 +46,32 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="JetBrains.Annotations" Version="11.1.0">
<PackageReference Include="JetBrains.Annotations" Version="2018.2.1">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
<PackageReference Include="SimMetrics.Net" Version="1.0.4" />
<PackageReference Include="RestEase" Version="1.4.4" />
<PackageReference Include="MimeKitLite" Version="2.0.1" />
<PackageReference Include="System.Linq.Dynamic.Core" Version="1.0.8.18" />
<PackageReference Include="SimMetrics.Net" Version="1.0.5" />
<PackageReference Include="RestEase" Version="1.4.7" />
<PackageReference Include="MimeKitLite" Version="2.0.7" />
<PackageReference Include="SonarAnalyzer.CSharp" Version="7.8.0.7320">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="System.Linq.Dynamic.Core" Version="1.0.12" />
<PackageReference Include="RandomDataGenerator.Net" Version="1.0.7" />
<PackageReference Include="JmesPath.Net" Version="1.0.125" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net451' ">
<PackageReference Include="Handlebars.Net" Version="1.9.0" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' != 'net451' ">
<PackageReference Include="Handlebars.Net" Version="1.9.5" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' != 'netstandard1.3' ">
<PackageReference Include="XPath2.Extensions" Version="1.0.6.1" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net451' ">
@@ -61,9 +80,6 @@
<PackageReference Include="Microsoft.AspNet.WebApi.OwinSelfHost" Version="5.2.6" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" />
<PackageReference Include="Handlebars.Net" Version="1.9.0" />
<PackageReference Include="XPath2" Version="1.0.5.1" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net452' ">
@@ -72,9 +88,6 @@
<PackageReference Include="Microsoft.AspNet.WebApi.OwinSelfHost" Version="5.2.6" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" />
<PackageReference Include="Handlebars.Net" Version="1.9.5" />
<PackageReference Include="XPath2" Version="1.0.5.1" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net46' ">
@@ -84,16 +97,10 @@
<PackageReference Include="Microsoft.Owin.Hosting" Version="4.0.0" />
<PackageReference Include="System.Net.Http" Version="4.3.3" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" />
<PackageReference Include="Handlebars.Net" Version="1.9.5" />
<PackageReference Include="XPath2" Version="1.0.5.1" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net461' ">
<PackageReference Include="Microsoft.AspNetCore" Version="2.1.2" />
<PackageReference Include="Handlebars.Net" Version="1.9.5" />
<PackageReference Include="XPath2" Version="1.0.5.1" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard1.3' ">
@@ -102,14 +109,9 @@
<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />
<PackageReference Include="System.Xml.XPath.XmlDocument" Version="4.3.0" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" />
<PackageReference Include="Handlebars.Net" Version="1.9.5" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
<PackageReference Include="Microsoft.AspNetCore" Version="2.1.2" />
<PackageReference Include="Handlebars.Net" Version="1.9.5" />
<PackageReference Include="XPath2" Version="1.0.5.1" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.1.4" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="SonarQube - wiremock Sonar way" ToolsVersion="15.0">
<Include Path="..\..\.sonarlint\wiremockcsharp.ruleset" Action="Default" />
</RuleSet>

View File

@@ -0,0 +1,215 @@
using Moq;
using NFluent;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using WireMock.Handlers;
using WireMock.Server;
using WireMock.Settings;
using Xunit;
namespace WireMock.Net.Tests
{
public class FluentMockServerAdminFilesTests
{
private readonly HttpClient _client = new HttpClient();
[Fact]
public async Task FluentMockServer_Admin_Files_Post_Ascii()
{
// Arrange
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.GetMappingFolder()).Returns("__admin/mappings");
filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny<string>())).Returns(true);
filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>()));
var server = FluentMockServer.Start(new FluentMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
var multipartFormDataContent = new MultipartFormDataContent();
multipartFormDataContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
multipartFormDataContent.Add(new StreamContent(new MemoryStream(Encoding.ASCII.GetBytes("Here's a string."))));
// Act
var httpResponseMessage = await _client.PostAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt", multipartFormDataContent);
// Assert
Check.That(httpResponseMessage.StatusCode).Equals(HttpStatusCode.OK);
Check.That(server.LogEntries.Count().Equals(1));
// Verify
filesystemHandlerMock.Verify(fs => fs.GetMappingFolder(), Times.Once);
filesystemHandlerMock.Verify(fs => fs.FolderExists(It.IsAny<string>()), Times.Once);
filesystemHandlerMock.Verify(fs => fs.WriteFile(It.Is<string>(p => p == "filename.txt"), It.IsAny<byte[]>()), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
}
[Fact]
public async Task FluentMockServer_Admin_Files_Post_MappingFolderDoesNotExistsButWillBeCreated()
{
// Arrange
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.GetMappingFolder()).Returns("x");
filesystemHandlerMock.Setup(fs => fs.CreateFolder(It.IsAny<string>()));
filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny<string>())).Returns(false);
filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>()));
var server = FluentMockServer.Start(new FluentMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
var multipartFormDataContent = new MultipartFormDataContent();
multipartFormDataContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
multipartFormDataContent.Add(new StreamContent(new MemoryStream(Encoding.ASCII.GetBytes("Here's a string."))));
// Act
var httpResponseMessage = await _client.PostAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt", multipartFormDataContent);
// Assert
Check.That(httpResponseMessage.StatusCode).Equals(HttpStatusCode.OK);
// Verify
filesystemHandlerMock.Verify(fs => fs.GetMappingFolder(), Times.Once);
filesystemHandlerMock.Verify(fs => fs.FolderExists(It.IsAny<string>()), Times.Once);
filesystemHandlerMock.Verify(fs => fs.CreateFolder(It.Is<string>(p => p == "x")), Times.Once);
filesystemHandlerMock.Verify(fs => fs.WriteFile(It.Is<string>(p => p == "filename.txt"), It.IsAny<byte[]>()), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
}
[Fact]
public async Task FluentMockServer_Admin_Files_GetAscii()
{
// Arrange
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny<string>())).Returns(Encoding.ASCII.GetBytes("Here's a string."));
var server = FluentMockServer.Start(new FluentMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
var multipartFormDataContent = new MultipartFormDataContent();
multipartFormDataContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
multipartFormDataContent.Add(new StreamContent(new MemoryStream()));
// Act
var httpResponseMessageGet = await _client.GetAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt");
// Assert
Check.That(httpResponseMessageGet.StatusCode).Equals(HttpStatusCode.OK);
Check.That(httpResponseMessageGet.Content.ReadAsStringAsync().Result).Equals("Here's a string.");
Check.That(server.LogEntries.Count().Equals(2));
// Verify
filesystemHandlerMock.Verify(fs => fs.ReadFile(It.Is<string>(p => p == "filename.txt")), Times.Once);
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
}
[Fact]
public async Task FluentMockServer_Admin_Files_GetUTF16()
{
// Arrange
byte[] symbol = Encoding.UTF32.GetBytes(char.ConvertFromUtf32(0x1D161));
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny<string>())).Returns(symbol);
var server = FluentMockServer.Start(new FluentMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
var multipartFormDataContent = new MultipartFormDataContent();
multipartFormDataContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
multipartFormDataContent.Add(new StreamContent(new MemoryStream()));
// Act
var httpResponseMessageGet = await _client.GetAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.bin");
// Assert
Check.That(httpResponseMessageGet.StatusCode).Equals(HttpStatusCode.OK);
Check.That(httpResponseMessageGet.Content.ReadAsByteArrayAsync().Result).Equals(symbol);
Check.That(server.LogEntries.Count().Equals(2));
// Verify
filesystemHandlerMock.Verify(fs => fs.ReadFile(It.Is<string>(p => p == "filename.bin")), Times.Once);
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.bin")), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
}
[Fact]
public async Task FluentMockServer_Admin_Files_Head()
{
// Arrange
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
var server = FluentMockServer.Start(new FluentMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
// Act
var requestUri = "http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt";
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Head, requestUri);
var httpResponseMessage = await _client.SendAsync(httpRequestMessage);
// Assert
Check.That(httpResponseMessage.StatusCode).Equals(HttpStatusCode.NoContent);
Check.That(server.LogEntries.Count().Equals(1));
// Verify
filesystemHandlerMock.Verify(fs => fs.FileExists(It.IsAny<string>()), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
}
[Fact]
public async Task FluentMockServer_Admin_Files_Head_FileDoesNotExistsReturns404()
{
// Arrange
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(false);
var server = FluentMockServer.Start(new FluentMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
// Act
var requestUri = "http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt";
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Head, requestUri);
var httpResponseMessage = await _client.SendAsync(httpRequestMessage);
// Assert
Check.That(httpResponseMessage.StatusCode).Equals(HttpStatusCode.NotFound);
Check.That(server.LogEntries.Count().Equals(1));
// Verify
filesystemHandlerMock.Verify(fs => fs.FileExists(It.IsAny<string>()), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
}
}
}

View File

@@ -1,12 +1,15 @@
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Moq;
using NFluent;
using RestEase;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using WireMock.Admin.Mappings;
using WireMock.Admin.Settings;
using WireMock.Client;
using WireMock.Handlers;
using WireMock.Logging;
using WireMock.Server;
using WireMock.Settings;
@@ -19,7 +22,7 @@ namespace WireMock.Net.Tests
[Fact]
public async Task IFluentMockServerAdmin_GetSettingsAsync()
{
// Assign
// Arrange
var server = FluentMockServer.StartWithAdminInterface();
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
@@ -31,7 +34,7 @@ namespace WireMock.Net.Tests
[Fact]
public async Task IFluentMockServerAdmin_PostSettingsAsync()
{
// Assign
// Arrange
var server = FluentMockServer.StartWithAdminInterface();
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
@@ -44,7 +47,7 @@ namespace WireMock.Net.Tests
[Fact]
public async Task IFluentMockServerAdmin_PutSettingsAsync()
{
// Assign
// Arrange
var server = FluentMockServer.StartWithAdminInterface();
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
@@ -57,22 +60,15 @@ namespace WireMock.Net.Tests
[Fact]
public async Task IFluentMockServerAdmin_PostMappingAsync()
{
// Assign
// Arrange
var server = FluentMockServer.StartWithAdminInterface();
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
// Act
var model = new MappingModel
{
Request = new RequestModel
{
Path = "/1"
},
Response = new ResponseModel
{
Body = "txt",
StatusCode = 200
},
Request = new RequestModel { Path = "/1" },
Response = new ResponseModel { Body = "txt", StatusCode = 200 },
Priority = 500,
Title = "test"
};
@@ -90,10 +86,41 @@ namespace WireMock.Net.Tests
server.Stop();
}
[Fact]
public async Task IFluentMockServerAdmin_PostMappingsAsync()
{
// Arrange
var server = FluentMockServer.StartWithAdminInterface();
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
// Act
var model1 = new MappingModel
{
Request = new RequestModel { Path = "/1" },
Response = new ResponseModel { Body = "txt 1" },
Title = "test 1"
};
var model2 = new MappingModel
{
Request = new RequestModel { Path = "/2" },
Response = new ResponseModel { Body = "txt 2" },
Title = "test 2"
};
var result = await api.PostMappingsAsync(new[] { model1, model2 });
// Assert
Check.That(result).IsNotNull();
Check.That(result.Status).IsNotNull();
Check.That(result.Guid).IsNull();
Check.That(server.Mappings.Where(m => !m.IsAdminInterface)).HasSize(2);
server.Stop();
}
[Fact]
public async Task IFluentMockServerAdmin_FindRequestsAsync()
{
// given
// Arrange
var server = FluentMockServer.Start(new FluentMockServerSettings
{
StartAdminInterface = true,
@@ -103,10 +130,10 @@ namespace WireMock.Net.Tests
await new HttpClient().GetAsync(serverUrl + "/foo");
var api = RestClient.For<IFluentMockServerAdmin>(serverUrl);
// when
// Act
var requests = await api.FindRequestsAsync(new RequestModel { Methods = new[] { "GET" } });
// then
// Assert
Check.That(requests).HasSize(1);
var requestLogged = requests.First();
Check.That(requestLogged.Request.Method).IsEqualTo("GET");
@@ -117,7 +144,7 @@ namespace WireMock.Net.Tests
[Fact]
public async Task IFluentMockServerAdmin_GetRequestsAsync()
{
// given
// Arrange
var server = FluentMockServer.Start(new FluentMockServerSettings
{
StartAdminInterface = true,
@@ -127,10 +154,10 @@ namespace WireMock.Net.Tests
await new HttpClient().GetAsync(serverUrl + "/foo");
var api = RestClient.For<IFluentMockServerAdmin>(serverUrl);
// when
// Act
var requests = await api.GetRequestsAsync();
// then
// Assert
Check.That(requests).HasSize(1);
var requestLogged = requests.First();
Check.That(requestLogged.Request.Method).IsEqualTo("GET");
@@ -141,7 +168,7 @@ namespace WireMock.Net.Tests
[Fact]
public async Task IFluentMockServerAdmin_GetRequestsAsync_JsonApi()
{
// given
// Arrange
var server = FluentMockServer.Start(new FluentMockServerSettings
{
StartAdminInterface = true,
@@ -159,13 +186,14 @@ namespace WireMock.Net.Tests
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(jsonApiContentType);
var response = await new HttpClient().SendAsync(request);
Check.That(response).IsNotNull();
var api = RestClient.For<IFluentMockServerAdmin>(serverUrl);
// when
// Act
var requests = await api.GetRequestsAsync();
// then
// Assert
Check.That(requests).HasSize(1);
var requestLogged = requests.First();
Check.That(requestLogged.Request.Method).IsEqualTo("POST");
@@ -176,7 +204,7 @@ namespace WireMock.Net.Tests
[Fact]
public async Task IFluentMockServerAdmin_GetRequestsAsync_Json()
{
// given
// Arrange
var server = FluentMockServer.Start(new FluentMockServerSettings
{
StartAdminInterface = true,
@@ -193,19 +221,251 @@ namespace WireMock.Net.Tests
request.Content = new StringContent(data);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(jsonApiContentType);
var response = await new HttpClient().SendAsync(request);
Check.That(response).IsNotNull();
var api = RestClient.For<IFluentMockServerAdmin>(serverUrl);
// when
// Act
var requests = await api.GetRequestsAsync();
// then
// Assert
Check.That(requests).HasSize(1);
var requestLogged = requests.First();
Check.That(requestLogged.Request.Method).IsEqualTo("POST");
Check.That(requestLogged.Request.Body).IsNotNull();
Check.That(requestLogged.Request.Body).Contains("T000001");
}
}
[Fact]
public async Task IFluentMockServerAdmin_PostFileAsync_Ascii()
{
// Arrange
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.GetMappingFolder()).Returns("__admin/mappings");
filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny<string>())).Returns(true);
filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>()));
var server = FluentMockServer.Start(new FluentMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
// Act
var request = await api.PostFileAsync("filename.txt", "abc");
// Assert
Check.That(request.Guid).IsNull();
Check.That(request.Status).Contains("File");
// Verify
filesystemHandlerMock.Verify(fs => fs.GetMappingFolder(), Times.Once);
filesystemHandlerMock.Verify(fs => fs.FolderExists(It.IsAny<string>()), Times.Once);
filesystemHandlerMock.Verify(fs => fs.WriteFile(It.Is<string>(p => p == "filename.txt"), It.IsAny<byte[]>()), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
server.Stop();
}
[Fact]
public async Task IFluentMockServerAdmin_PutFileAsync_Ascii()
{
// Arrange
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>()));
var server = FluentMockServer.Start(new FluentMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
// Act
var request = await api.PutFileAsync("filename.txt", "abc-abc");
// Assert
Check.That(request.Guid).IsNull();
Check.That(request.Status).Contains("File");
// Verify
filesystemHandlerMock.Verify(fs => fs.WriteFile(It.Is<string>(p => p == "filename.txt"), It.IsAny<byte[]>()), Times.Once);
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
server.Stop();
}
[Fact]
public void IFluentMockServerAdmin_PutFileAsync_NotFound()
{
// Arrange
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(false);
var server = FluentMockServer.Start(new FluentMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
// Act and Assert
Check.ThatAsyncCode(() => api.PutFileAsync("filename.txt", "xxx")).Throws<ApiException>();
// Verify
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
server.Stop();
}
[Fact]
public void IFluentMockServerAdmin_GetFileAsync_NotFound()
{
// Arrange
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(false);
filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny<string>())).Returns(Encoding.ASCII.GetBytes("Here's a string."));
var server = FluentMockServer.Start(new FluentMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
// Act and Assert
Check.ThatAsyncCode(() => api.GetFileAsync("filename.txt")).Throws<ApiException>();
// Verify
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
server.Stop();
}
[Fact]
public async Task IFluentMockServerAdmin_GetFileAsync_Found()
{
// Arrange
string data = "Here's a string.";
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny<string>())).Returns(Encoding.ASCII.GetBytes(data));
var server = FluentMockServer.Start(new FluentMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
// Act
string file = await api.GetFileAsync("filename.txt");
// Assert
Check.That(file).Equals(data);
// Verify
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
filesystemHandlerMock.Verify(fs => fs.ReadFile(It.Is<string>(p => p == "filename.txt")), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
server.Stop();
}
[Fact]
public async Task IFluentMockServerAdmin_DeleteFileAsync_Ok()
{
// Arrange
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
filesystemHandlerMock.Setup(fs => fs.DeleteFile(It.IsAny<string>()));
var server = FluentMockServer.Start(new FluentMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
// Act
await api.DeleteFileAsync("filename.txt");
// Verify
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
filesystemHandlerMock.Verify(fs => fs.DeleteFile(It.Is<string>(p => p == "filename.txt")), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
server.Stop();
}
[Fact]
public void IFluentMockServerAdmin_DeleteFileAsync_NotFound()
{
// Arrange
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(false);
filesystemHandlerMock.Setup(fs => fs.DeleteFile(It.IsAny<string>()));
var server = FluentMockServer.Start(new FluentMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
// Act and Assert
Check.ThatAsyncCode(() => api.DeleteFileAsync("filename.txt")).Throws<ApiException>();
// Verify
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
server.Stop();
}
[Fact]
public void IFluentMockServerAdmin_FileExistsAsync_NotFound()
{
// Arrange
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(false);
var server = FluentMockServer.Start(new FluentMockServerSettings
{
UseSSL = false,
StartAdminInterface = true,
FileSystemHandler = filesystemHandlerMock.Object
});
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
// Act and Assert
Check.ThatAsyncCode(() => api.FileExistsAsync("filename.txt")).Throws<ApiException>();
// Verify
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
filesystemHandlerMock.VerifyNoOtherCalls();
server.Stop();
}
}
}

View File

@@ -1,11 +1,11 @@
using System;
using Moq;
using Newtonsoft.Json;
using NFluent;
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Moq;
using Newtonsoft.Json;
using NFluent;
using WireMock.Handlers;
using WireMock.Logging;
using WireMock.RequestBuilders;
@@ -46,7 +46,7 @@ namespace WireMock.Net.Tests
string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings");
server.ReadStaticMappings(folder);
Check.That(server.Mappings).HasSize(3);
Check.That(server.Mappings).HasSize(5);
// Act
server.ResetMappings();
@@ -92,8 +92,8 @@ namespace WireMock.Net.Tests
var server = FluentMockServer.Start();
string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", "documentdb_root.json");
server.ReadStaticMappingAndAddOrUpdate(folder);
string path = Path.Combine(GetCurrentFolder(), "__admin", "mappings", "documentdb_root.json");
server.ReadStaticMappingAndAddOrUpdate(path);
var mappings = server.Mappings.ToArray();
Check.That(mappings).HasSize(1);
@@ -110,8 +110,8 @@ namespace WireMock.Net.Tests
string guid = "00000002-ee28-4f29-ae63-1ac9b0802d86";
var server = FluentMockServer.Start();
string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", guid + ".json");
server.ReadStaticMappingAndAddOrUpdate(folder);
string path = Path.Combine(GetCurrentFolder(), "__admin", "mappings", guid + ".json");
server.ReadStaticMappingAndAddOrUpdate(path);
var mappings = server.Mappings.ToArray();
Check.That(mappings).HasSize(1);
@@ -122,13 +122,25 @@ namespace WireMock.Net.Tests
Check.That(mappings.First().Title).IsNullOrEmpty();
}
[Fact]
public void FluentMockServer_Admin_ReadStaticMapping_WithArray()
{
var server = FluentMockServer.Start();
string path = Path.Combine(GetCurrentFolder(), "__admin", "mappings", "array.json");
server.ReadStaticMappingAndAddOrUpdate(path);
var mappings = server.Mappings.ToArray();
Check.That(mappings).HasSize(2);
}
[Fact]
public void FluentMockServer_Admin_ReadStaticMapping_WithResponseBodyFromFile()
{
string guid = "00000002-ee28-4f29-ae63-1ac9b0802d87";
string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", guid + ".json");
string json = File.ReadAllText(folder);
string path = Path.Combine(GetCurrentFolder(), "__admin", "mappings", guid + ".json");
string json = File.ReadAllText(path);
string responseBodyFilePath = Path.Combine(GetCurrentFolder(), "responsebody.json");
@@ -136,10 +148,10 @@ namespace WireMock.Net.Tests
jsonObj["Response"]["BodyAsFile"] = responseBodyFilePath;
string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
File.WriteAllText(folder, output);
File.WriteAllText(path, output);
var server = FluentMockServer.Start();
server.ReadStaticMappingAndAddOrUpdate(folder);
server.ReadStaticMappingAndAddOrUpdate(path);
var mappings = server.Mappings.ToArray();
Check.That(mappings).HasSize(1);
@@ -202,7 +214,7 @@ namespace WireMock.Net.Tests
server.ReadStaticMappings(folder);
var mappings = server.Mappings.ToArray();
Check.That(mappings).HasSize(3);
Check.That(mappings).HasSize(5);
}
[Fact]

View File

@@ -16,7 +16,6 @@ namespace WireMock.Net.Tests
{
public class FluentMockServerProxyTests
{
#if NET452
[Fact]
public async Task FluentMockServer_Proxy_Should_proxy_responses()
{
@@ -63,7 +62,7 @@ namespace WireMock.Net.Tests
};
var server = FluentMockServer.Start(settings);
// when
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
@@ -74,7 +73,7 @@ namespace WireMock.Net.Tests
requestMessage.Content.Headers.Add("bbb", "test");
await new HttpClient().SendAsync(requestMessage);
// then
// Assert
var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
Check.That(receivedRequest.BodyData.BodyAsString).IsEqualTo("stringContent");
Check.That(receivedRequest.Headers).ContainsKey("Content-Type");
@@ -92,7 +91,7 @@ namespace WireMock.Net.Tests
[Fact]
public async Task FluentMockServer_Proxy_Should_exclude_blacklisted_content_header_in_mapping()
{
// given
// Assign
string path = $"/prx_{Guid.NewGuid().ToString()}";
var serverForProxyForwarding = FluentMockServer.Start();
serverForProxyForwarding
@@ -111,7 +110,7 @@ namespace WireMock.Net.Tests
};
var server = FluentMockServer.Start(settings);
// when
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
@@ -122,7 +121,7 @@ namespace WireMock.Net.Tests
requestMessage.Headers.Add("ok", "ok-value");
await new HttpClient().SendAsync(requestMessage);
// then
// Assert
var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
Check.That(receivedRequest.Headers).Not.ContainsKey("bbb");
Check.That(receivedRequest.Headers).ContainsKey("ok");
@@ -291,6 +290,36 @@ namespace WireMock.Net.Tests
Check.That(response.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/json; charset=utf-8");
}
[Fact]
public async Task FluentMockServer_Proxy_Should_set_Body_in_multipart_proxied_response()
{
// Assign
string path = $"/prx_{Guid.NewGuid().ToString()}";
var serverForProxyForwarding = FluentMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create()
.WithBodyAsJson(new { i = 42 })
);
var server = FluentMockServer.Start();
server
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0]));
// Act
var uri = new Uri($"{server.Urls[0]}{path}");
var form = new MultipartFormDataContent
{
{ new StringContent("data"), "test", "test.txt" }
};
var response = await new HttpClient().PostAsync(uri, form);
// Assert
string content = await response.Content.ReadAsStringAsync();
Check.That(content).IsEqualTo("{\"i\":42}");
}
[Fact]
public async Task FluentMockServer_Proxy_Should_Not_overrule_AdminMappings()
{
@@ -337,6 +366,5 @@ namespace WireMock.Net.Tests
string content2 = await response2.Content.ReadAsStringAsync();
Check.That(content2).IsEqualTo("[]");
}
#endif
}
}

View File

@@ -17,15 +17,15 @@ namespace WireMock.Net.Tests
public async Task FluentMockServer_ProxyAndRecordSettings_ShouldProxy()
{
// Assign
var server = FluentMockServer.Start();
server.Given(Request.Create().UsingPost().WithHeader("prx", "1"))
.RespondWith(Response.Create().WithProxy(server.Urls[0]));
server.Given(Request.Create().UsingPost())
var serverAsProxy = FluentMockServer.Start();
serverAsProxy.Given(Request.Create().UsingPost())
.RespondWith(Response.Create().WithStatusCode(201).WithBodyAsJson(new { p = 42 }).WithHeader("Content-Type", "application/json"));
// Act
var server = FluentMockServer.Start();
server.Given(Request.Create().UsingPost().WithHeader("prx", "1"))
.RespondWith(Response.Create().WithProxy(serverAsProxy.Urls[0]));
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
@@ -41,6 +41,9 @@ namespace WireMock.Net.Tests
Check.That(content).IsEqualTo("{\"p\":42}");
Check.That(response.StatusCode).IsEqualTo(HttpStatusCode.Created);
Check.That(response.Content.Headers.GetValues("Content-Type").First()).IsEqualTo("application/json");
server.Dispose();
serverAsProxy.Dispose();
}
}
}

View File

@@ -62,7 +62,7 @@ namespace WireMock.Net.Tests
// Assert
var mappings = server.Mappings;
Check.That(mappings.Count()).IsEqualTo(19);
Check.That(mappings.Count()).IsEqualTo(24);
Check.That(mappings.All(m => m.Priority == int.MinValue)).IsTrue();
}
@@ -81,8 +81,8 @@ namespace WireMock.Net.Tests
// Assert
var mappings = server.Mappings;
Check.That(mappings.Count()).IsEqualTo(20);
Check.That(mappings.Count(m => m.Priority == int.MinValue)).IsEqualTo(19);
Check.That(mappings.Count()).IsEqualTo(25);
Check.That(mappings.Count(m => m.Priority == int.MinValue)).IsEqualTo(24);
Check.That(mappings.Count(m => m.Priority == 1000)).IsEqualTo(1);
}

View File

@@ -1,6 +1,6 @@
using System;
using NFluent;
using System;
using System.IO;
using NFluent;
using WireMock.Handlers;
using Xunit;
@@ -21,17 +21,62 @@ namespace WireMock.Net.Tests.Handlers
}
[Fact]
public void LocalFileSystemHandler_CreateFolder_Throws()
public void LocalFileSystemHandler_CreateFolder_ThrowsArgumentNullException()
{
// Act
Check.ThatCode(() => _sut.CreateFolder(null)).Throws<ArgumentNullException>();
}
[Fact]
public void LocalFileSystemHandler_WriteMappingFile_Throws()
public void LocalFileSystemHandler_WriteMappingFile_ThrowsArgumentNullException()
{
// Act
Check.ThatCode(() => _sut.WriteMappingFile(null, null)).Throws<ArgumentNullException>();
}
[Fact]
public void LocalFileSystemHandler_ReadResponseBodyAsFile_ThrowsArgumentNullException()
{
// Act
Check.ThatCode(() => _sut.ReadResponseBodyAsFile(null)).Throws<ArgumentNullException>();
}
[Fact]
public void LocalFileSystemHandler_FileExists_ReturnsFalse()
{
// Act
var result = _sut.FileExists("x.x");
// Assert
Check.That(result).IsFalse();
}
[Fact]
public void LocalFileSystemHandler_FileExists_ThrowsArgumentNullException()
{
// Act
Check.ThatCode(() => _sut.FileExists(null)).Throws<ArgumentNullException>();
}
[Fact]
public void LocalFileSystemHandler_ReadFile_ThrowsArgumentNullException()
{
// Act
Check.ThatCode(() => _sut.ReadFile(null)).Throws<ArgumentNullException>();
}
[Fact]
public void LocalFileSystemHandler_WriteFile_ThrowsArgumentNullException()
{
// Act
Check.ThatCode(() => _sut.WriteFile(null, null)).Throws<ArgumentNullException>();
}
[Fact]
public void LocalFileSystemHandler_DeleteFile_ThrowsArgumentNullException()
{
// Act
Check.ThatCode(() => _sut.DeleteFile(null)).Throws<ArgumentNullException>();
}
}
}

View File

@@ -33,7 +33,33 @@ namespace WireMock.Net.Tests.Matchers
}
[Fact]
public void ExactMatcher_IsMatch_MultiplePatterns()
public void ExactMatcher_IsMatch_WithSinglePattern_ReturnsMatch1_0()
{
// Assign
var matcher = new ExactMatcher("x");
// Act
double result = matcher.IsMatch("x");
// Assert
Check.That(result).IsEqualTo(1.0);
}
[Fact]
public void ExactMatcher_IsMatch_WithSinglePattern_ReturnsMatch0_0()
{
// Assign
var matcher = new ExactMatcher("x");
// Act
double result = matcher.IsMatch("y");
// Assert
Check.That(result).IsEqualTo(0.0);
}
[Fact]
public void ExactMatcher_IsMatch_WithMultiplePatterns_ReturnsMatch0_5()
{
// Assign
var matcher = new ExactMatcher("x", "y");
@@ -42,7 +68,7 @@ namespace WireMock.Net.Tests.Matchers
double result = matcher.IsMatch("x");
// Assert
Check.That(result).IsEqualTo(0.5d);
Check.That(result).IsEqualTo(1.0);
}
[Fact]

View File

@@ -0,0 +1,166 @@
using Newtonsoft.Json.Linq;
using NFluent;
using WireMock.Matchers;
using Xunit;
namespace WireMock.Net.Tests.Matchers
{
public class JmesPathMatcherTests
{
[Fact]
public void JmesPathMatcher_GetName()
{
// Assign
var matcher = new JmesPathMatcher("X");
// Act
string name = matcher.Name;
// Assert
Check.That(name).Equals("JmesPathMatcher");
}
[Fact]
public void JmesPathMatcher_GetPatterns()
{
// Assign
var matcher = new JmesPathMatcher("X");
// Act
string[] patterns = matcher.GetPatterns();
// Assert
Check.That(patterns).ContainsExactly("X");
}
[Fact]
public void JmesPathMatcher_IsMatch_ByteArray()
{
// Assign
var bytes = new byte[0];
var matcher = new JmesPathMatcher("");
// Act
double match = matcher.IsMatch(bytes);
// Assert
Check.That(match).IsEqualTo(0);
}
[Fact]
public void JmesPathMatcher_IsMatch_NullString()
{
// Assign
string s = null;
var matcher = new JmesPathMatcher("");
// Act
double match = matcher.IsMatch(s);
// Assert
Check.That(match).IsEqualTo(0);
}
[Fact]
public void JmesPathMatcher_IsMatch_NullObject()
{
// Assign
object o = null;
var matcher = new JmesPathMatcher("");
// Act
double match = matcher.IsMatch(o);
// Assert
Check.That(match).IsEqualTo(0);
}
[Fact]
public void JmesPathMatcher_IsMatch_String_Exception_Mismatch()
{
// Assign
var matcher = new JmesPathMatcher("xxx");
// Act
double match = matcher.IsMatch("");
// Assert
Check.That(match).IsEqualTo(0);
}
[Fact]
public void JmesPathMatcher_IsMatch_Object_Exception_Mismatch()
{
// Assign
var matcher = new JmesPathMatcher("");
// Act
double match = matcher.IsMatch("x");
// Assert
Check.That(match).IsEqualTo(0);
}
[Fact]
public void JmesPathMatcher_IsMatch_AnonymousObject()
{
// Assign
var matcher = new JmesPathMatcher("things.name == 'RequiredThing'");
// Act
double match = matcher.IsMatch(new { things = new { name = "RequiredThing" } });
// Assert
Check.That(match).IsEqualTo(1);
}
[Fact]
public void JmesPathMatcher_IsMatch_JObject()
{
// Assign
string[] patterns = { "things.x == 'RequiredThing'" };
var matcher = new JmesPathMatcher(patterns);
// Act
var sub = new JObject
{
{ "x", new JValue("RequiredThing") }
};
var jobject = new JObject
{
{ "Id", new JValue(1) },
{ "things", sub }
};
double match = matcher.IsMatch(jobject);
// Assert
Check.That(match).IsEqualTo(1);
}
[Fact]
public void JmesPathMatcher_IsMatch_JObject_Parsed()
{
// Assign
var matcher = new JmesPathMatcher("things.x == 'RequiredThing'");
// Act
double match = matcher.IsMatch(JObject.Parse("{ \"things\": { \"x\": \"RequiredThing\" } }"));
// Assert
Check.That(match).IsEqualTo(1);
}
[Fact]
public void JmesPathMatcher_IsMatch_RejectOnMatch()
{
// Assign
var matcher = new JmesPathMatcher(MatchBehaviour.RejectOnMatch, "things.x == 'RequiredThing'");
// Act
double match = matcher.IsMatch(JObject.Parse("{ \"things\": { \"x\": \"RequiredThing\" } }"));
// Assert
Check.That(match).IsEqualTo(0.0);
}
}
}

View File

@@ -4,6 +4,7 @@ using Xunit;
using Moq;
using System.Threading.Tasks;
using System.Threading;
using WireMock.Handlers;
using WireMock.Owin.Mappers;
using WireMock.Util;
#if NET452
@@ -26,6 +27,7 @@ namespace WireMock.Net.Tests.Owin.Mappers
private readonly Mock<IResponse> _responseMock;
private readonly Mock<Stream> _stream;
private readonly Mock<IHeaderDictionary> _headers;
private readonly Mock<IFileSystemHandler> _fileSystemHandlerMock;
public OwinResponseMapperTests()
{
@@ -46,20 +48,23 @@ namespace WireMock.Net.Tests.Owin.Mappers
_responseMock.SetupGet(r => r.Body).Returns(_stream.Object);
_responseMock.SetupGet(r => r.Headers).Returns(_headers.Object);
_sut = new OwinResponseMapper();
_fileSystemHandlerMock = new Mock<IFileSystemHandler>();
_fileSystemHandlerMock.SetupAllProperties();
_sut = new OwinResponseMapper(_fileSystemHandlerMock.Object);
}
[Fact]
public async void OwinResponseMapper_MapAsync_Null()
public async Task OwinResponseMapper_MapAsync_Null()
{
// Act
await _sut.MapAsync(null, _responseMock.Object);
}
[Fact]
public async void OwinResponseMapper_MapAsync_StatusCode()
public async Task OwinResponseMapper_MapAsync_StatusCode()
{
// Assign
// Arrange
var responseMessage = new ResponseMessage
{
StatusCode = 302
@@ -73,9 +78,9 @@ namespace WireMock.Net.Tests.Owin.Mappers
}
[Fact]
public async void OwinResponseMapper_MapAsync_NoBody()
public async Task OwinResponseMapper_MapAsync_NoBody()
{
// Assign
// Arrange
var responseMessage = new ResponseMessage
{
Headers = new Dictionary<string, WireMockList<string>>()
@@ -89,9 +94,9 @@ namespace WireMock.Net.Tests.Owin.Mappers
}
[Fact]
public async void OwinResponseMapper_MapAsync_Body()
public async Task OwinResponseMapper_MapAsync_Body()
{
// Assign
// Arrange
string body = "abc";
var responseMessage = new ResponseMessage
{
@@ -107,9 +112,9 @@ namespace WireMock.Net.Tests.Owin.Mappers
}
[Fact]
public async void OwinResponseMapper_MapAsync_BodyAsBytes()
public async Task OwinResponseMapper_MapAsync_BodyAsBytes()
{
// Assign
// Arrange
var bytes = new byte[] { 48, 49 };
var responseMessage = new ResponseMessage
{
@@ -125,9 +130,9 @@ namespace WireMock.Net.Tests.Owin.Mappers
}
[Fact]
public async void OwinResponseMapper_MapAsync_BodyAsJson()
public async Task OwinResponseMapper_MapAsync_BodyAsJson()
{
// Assign
// Arrange
var json = new { t = "x", i = (string)null };
var responseMessage = new ResponseMessage
{
@@ -143,9 +148,9 @@ namespace WireMock.Net.Tests.Owin.Mappers
}
[Fact]
public async void OwinResponseMapper_MapAsync_SetResponseHeaders()
public async Task OwinResponseMapper_MapAsync_SetResponseHeaders()
{
// Assign
// Arrange
var responseMessage = new ResponseMessage
{
Headers = new Dictionary<string, WireMockList<string>> { { "h", new WireMockList<string>("x", "y") } }

View File

@@ -16,7 +16,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert 1
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That((matchers[0] as RequestMessageMethodMatcher).Methods).ContainsExactly("PATCH");
}
@@ -28,7 +28,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert 1
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageMethodMatcher));
// Act
@@ -36,7 +36,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert 2
matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(0);
Check.That(matchers.Count).IsEqualTo(0);
}
}
}

View File

@@ -20,7 +20,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(((RequestMessageBodyMatcher) matchers[0]).Matcher).IsEqualTo(matcher);
}
}

View File

@@ -17,7 +17,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageCookieMatcher));
}
@@ -29,7 +29,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageCookieMatcher));
}
@@ -41,7 +41,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageCookieMatcher));
}
}

View File

@@ -17,7 +17,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher));
}
@@ -29,7 +29,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher));
}
@@ -41,7 +41,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher));
}
@@ -53,7 +53,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher));
}
@@ -65,7 +65,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher));
}
@@ -77,7 +77,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageHeaderMatcher));
}
}

View File

@@ -17,7 +17,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageParamMatcher));
}
@@ -29,7 +29,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageParamMatcher));
}
@@ -41,7 +41,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageParamMatcher));
}
@@ -53,7 +53,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageParamMatcher));
}
}

View File

@@ -17,7 +17,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher));
}
@@ -29,7 +29,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher));
}
@@ -41,7 +41,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher));
}
@@ -53,7 +53,7 @@ namespace WireMock.Net.Tests.RequestBuilders
// Assert
var matchers = requestBuilder.GetPrivateFieldValue<IList<IRequestMatcher>>("_requestMatchers");
Check.That(matchers.Count()).IsEqualTo(1);
Check.That(matchers.Count).IsEqualTo(1);
Check.That(matchers[0]).IsInstanceOfType(typeof(RequestMessageUrlMatcher));
}
}

View File

@@ -9,11 +9,11 @@ namespace WireMock.Net.Tests.RequestMatchers
public class RequestMessageParamMatcherTests
{
[Fact]
public void RequestMessageParamMatcher_GetMatchingScore_KeyWithValuesPresentInUrl_MatchExactOnStringValues()
public void RequestMessageParamMatcher_GetMatchingScore_IgnoreCaseKeyWithValuesPresentInUrl_And_With1StringValues_Returns1_0()
{
// Assign
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1,test2"), "GET", "127.0.0.1");
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", new[] { "test1", "test2" });
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1"), "GET", "127.0.0.1");
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "KeY", true, new[] { "test1" });
// Act
var result = new RequestMatchResult();
@@ -24,11 +24,71 @@ namespace WireMock.Net.Tests.RequestMatchers
}
[Fact]
public void RequestMessageParamMatcher_GetMatchingScore_KeyWithValuesPresentInUrl_MatchExactOnExactMatchers()
public void RequestMessageParamMatcher_GetMatchingScore_KeyWith1ValuePresentInUrl_And_With2Strings_Returns0_5()
{
// Assign
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1"), "GET", "127.0.0.1");
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new[] { "test1", "test2" });
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(0.5d);
}
[Fact]
public void RequestMessageParamMatcher_GetMatchingScore_KeyWith3ValuesPresentInUrl_And_With1ExactStringWith2Patterns_Returns0_66()
{
// Assign
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1,test2,test3"), "GET", "127.0.0.1");
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new IStringMatcher[] { new ExactMatcher("test1", "test2") });
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsCloseTo(0.66d, 0.1d);
}
[Fact]
public void RequestMessageParamMatcher_GetMatchingScore_KeyWith2ValuesPresentInUrl_And_With1ExactStringWith3Patterns_Returns0_66()
{
// Assign
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1,test2"), "GET", "127.0.0.1");
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", new IStringMatcher[] { new ExactMatcher("test1"), new ExactMatcher("test2") });
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new IStringMatcher[] { new ExactMatcher("test1", "test2", "test3") });
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsCloseTo(0.66d, 0.1d);
}
[Fact]
public void RequestMessageParamMatcher_GetMatchingScore_KeyWith2ValuesPresentInUrl_And_With2Strings_Returns1_0()
{
// Assign
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1,test2"), "GET", "127.0.0.1");
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new[] { "test1", "test2" });
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1.0d);
}
[Fact]
public void RequestMessageParamMatcher_GetMatchingScore_KeyWith2ValuesPresentInUrl_And_With2ExactStringMatchers_Returns1_0()
{
// Assign
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test1,test2"), "GET", "127.0.0.1");
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new IStringMatcher[] { new ExactMatcher("test1"), new ExactMatcher("test2") });
// Act
var result = new RequestMatchResult();
@@ -43,7 +103,7 @@ namespace WireMock.Net.Tests.RequestMatchers
{
// Assign
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=test0,test2"), "GET", "127.0.0.1");
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", new[] { "test1", "test2" });
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new[] { "test1", "test2" });
// Act
var result = new RequestMatchResult();
@@ -58,7 +118,7 @@ namespace WireMock.Net.Tests.RequestMatchers
{
// Assign
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key"), "GET", "127.0.0.1");
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", new[] { "test1", "test2" });
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new[] { "test1", "test2" });
// Act
var result = new RequestMatchResult();
@@ -73,7 +133,7 @@ namespace WireMock.Net.Tests.RequestMatchers
{
// Assign
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key"), "GET", "127.0.0.1");
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key");
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false);
// Act
var result = new RequestMatchResult();
@@ -88,7 +148,7 @@ namespace WireMock.Net.Tests.RequestMatchers
{
// Assign
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key"), "GET", "127.0.0.1");
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", new string[] { });
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false, new string[] { });
// Act
var result = new RequestMatchResult();
@@ -103,7 +163,7 @@ namespace WireMock.Net.Tests.RequestMatchers
{
// Assign
var requestMessage = new RequestMessage(new UrlDetails("http://localhost?key=frank@contoso.com"), "GET", "127.0.0.1");
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key");
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", false);
// Act
var result = new RequestMatchResult();

View File

@@ -39,6 +39,16 @@ namespace WireMock.Net.Tests
Check.That(request.GetParameter("foo")).ContainsExactly("bar");
}
[Fact]
public void RequestMessage_ParseQuery_SingleKey_SingleValue_WithIgnoreCase()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost?foo=bar"), "POST", ClientIp);
// Assert
Check.That(request.GetParameter("FoO", true)).ContainsExactly("bar");
}
[Fact]
public void RequestMessage_ParseQuery_MultipleKeys_MultipleValues()
{
@@ -50,6 +60,18 @@ namespace WireMock.Net.Tests
Check.That(request.GetParameter("key")).Contains("2");
}
[Fact]
public void RequestMessage_ParseQuery_SingleKey_MultipleValuesCommaSeparated()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost?key=1,2,3"), "POST", ClientIp);
// Assert
Check.That(request.GetParameter("key")).Contains("1");
Check.That(request.GetParameter("key")).Contains("2");
Check.That(request.GetParameter("key")).Contains("3");
}
[Fact]
public void RequestMessage_ParseQuery_SingleKey_MultipleValues()
{

View File

@@ -1,10 +1,12 @@
using System.Text;
using System;
using System.Text;
using System.Threading.Tasks;
using NFluent;
using WireMock.Models;
using WireMock.ResponseBuilders;
using WireMock.Util;
using Xunit;
using Newtonsoft.Json.Linq;
namespace WireMock.Net.Tests.ResponseBuilders
{
@@ -199,5 +201,84 @@ namespace WireMock.Net.Tests.ResponseBuilders
Check.That(responseMessage.Headers["H1"].ToString()).IsEqualTo("X1");
Check.That(responseMessage.Headers["H2"].ToString()).IsEqualTo("X2");
}
[Fact]
public async Task Response_ProvideResponse_WithJsonBodyAndTransform_Func()
{
// Assign
const int request1Id = 1;
const int request2Id = 2;
var request1 = new RequestMessage(new UrlDetails($"http://localhost/test?id={request1Id}"), "GET", ClientIp);
var request2 = new RequestMessage(new UrlDetails($"http://localhost/test?id={request2Id}"), "GET", ClientIp);
var response = Response.Create()
.WithStatusCode(200)
.WithBodyAsJson(JObject.Parse("{ \"id\": \"{{request.query.id}}\" }"))
.WithTransformer();
// Act
var response1Message = await response.ProvideResponseAsync(request1);
var response2Message = await response.ProvideResponseAsync(request2);
// Assert
Check.That(((JToken)response1Message.BodyData.BodyAsJson).SelectToken("id")?.Value<int>()).IsEqualTo(request1Id);
Check.That(response1Message.BodyData.BodyAsBytes).IsNull();
Check.That(response1Message.BodyData.BodyAsString).IsNull();
Check.That(response1Message.StatusCode).IsEqualTo(200);
Check.That(((JToken)response2Message.BodyData.BodyAsJson).SelectToken("id")?.Value<int>()).IsEqualTo(request2Id);
Check.That(response2Message.BodyData.BodyAsBytes).IsNull();
Check.That(response2Message.BodyData.BodyAsString).IsNull();
Check.That(response2Message.StatusCode).IsEqualTo(200);
}
[Fact]
public async Task Response_ProvideResponse_WithBodyAsFile()
{
var fileContents = "testFileContents" + Guid.NewGuid();
var bodyDataAsFile = new BodyData {BodyAsFile = fileContents};
var request1 = new RequestMessage(new UrlDetails("http://localhost/__admin/files/filename.txt"), "PUT", ClientIp, bodyDataAsFile);
var response = Response.Create().WithStatusCode(200).WithBody(fileContents);
var provideResponseAsync = await response.ProvideResponseAsync(request1);
Check.That(provideResponseAsync.StatusCode).IsEqualTo(200);
Check.That(provideResponseAsync.BodyData.BodyAsString).Contains(fileContents);
}
[Fact]
public async Task Response_ProvideResponse_WithResponseAsFile()
{
var fileContents = "testFileContents" + Guid.NewGuid();
var bodyDataAsFile = new BodyData { BodyAsFile = fileContents };
var request1 = new RequestMessage(new UrlDetails("http://localhost/__admin/files/filename.txt"), "GET", ClientIp, bodyDataAsFile);
var response = Response.Create().WithStatusCode(200).WithBody(fileContents);
var provideResponseAsync = await response.ProvideResponseAsync(request1);
Check.That(provideResponseAsync.StatusCode).IsEqualTo(200);
Check.That(provideResponseAsync.BodyData.BodyAsString).Contains(fileContents);
}
[Fact]
public async Task Response_ProvideResponse_WithResponseDeleted()
{
var fileContents = "testFileContents" + Guid.NewGuid();
var bodyDataAsFile = new BodyData { BodyAsFile = fileContents };
var request1 = new RequestMessage(new UrlDetails("http://localhost/__admin/files/filename.txt"), "DELETE", ClientIp, bodyDataAsFile);
var response = Response.Create().WithStatusCode(200).WithBody("File deleted.");
var provideResponseAsync = await response.ProvideResponseAsync(request1);
Check.That(provideResponseAsync.StatusCode).IsEqualTo(200);
Check.That(provideResponseAsync.BodyData.BodyAsString).Contains("File deleted.");
}
}
}
}

View File

@@ -0,0 +1,131 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using NFluent;
using WireMock.Models;
using WireMock.ResponseBuilders;
using Xunit;
namespace WireMock.Net.Tests.ResponseBuilders
{
public class ResponseWithHandlebarsRandomTests
{
private const string ClientIp = "::1";
[Fact]
public async Task Response_ProvideResponseAsync_Handlebars_Random1()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
var response = Response.Create()
.WithBodyAsJson(new
{
Text = "{{Random Type=\"Text\" Min=8 Max=20}}",
DateTime = "{{Random Type=\"DateTime\"}}",
Integer = "{{Random Type=\"Integer\" Min=1000 Max=1000}}",
Long = "{{Random Type=\"Long\" Min=77777777 Max=99999999}}"
})
.WithTransformer();
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
Check.That(j["Text"].Value<string>()).IsNotEmpty();
Check.That(j["Integer"].Value<int>()).IsEqualTo(1000);
Check.That(j["Long"].Value<long>()).IsStrictlyGreaterThan(77777777).And.IsStrictlyLessThan(99999999);
}
[Fact]
public async Task Response_ProvideResponseAsync_Handlebars_Random1_Boolean()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
var response = Response.Create()
.WithBodyAsJson(new
{
Value = "{{Random Type=\"Boolean\"}}"
})
.WithTransformer();
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
Check.That(j["Value"].Type).IsEqualTo(JTokenType.Boolean);
}
[Fact]
public async Task Response_ProvideResponseAsync_Handlebars_Random1_Guid()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
var response = Response.Create()
.WithBodyAsJson(new
{
Guid1 = "{{Random Type=\"Guid\" Uppercase=false}}",
Guid2 = "{{Random Type=\"Guid\"}}"
})
.WithTransformer();
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
string guid1 = j["Guid1"].Value<string>();
Check.That(guid1.ToUpper()).IsNotEqualTo(guid1);
string guid2 = j["Guid2"].Value<string>();
Check.That(guid2.ToUpper()).IsEqualTo(guid2);
}
[Fact]
public async Task Response_ProvideResponseAsync_Handlebars_Random1_StringList()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
var response = Response.Create()
.WithBodyAsJson(new
{
StringValue = "{{Random Type=\"StringList\" Values=[\"a\", \"b\", \"c\"]}}"
})
.WithTransformer();
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
string value = j["StringValue"].Value<string>();
Check.That(new[] { "a", "b", "c" }.Contains(value)).IsTrue();
}
[Fact]
public async Task Response_ProvideResponseAsync_Handlebars_Random2()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
var response = Response.Create()
.WithBodyAsJson(new
{
Integer = "{{#Random Type=\"Integer\" Min=10000000 Max=99999999}}{{this}}{{/Random}}",
})
.WithTransformer();
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
Check.That(j["Integer"].Value<int>()).IsStrictlyGreaterThan(10000000).And.IsStrictlyLessThan(99999999);
}
}
}

Some files were not shown because too many files have changed in this diff Show More