Skip to content

Commit

Permalink
Merge pull request #129 from natenho/feature/docs-scripting
Browse files Browse the repository at this point in the history
Improve scripting documentation
  • Loading branch information
natenho authored Mar 11, 2024
2 parents a0b00c8 + 4af7f21 commit 36c8f27
Show file tree
Hide file tree
Showing 33 changed files with 644 additions and 124 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,5 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;

namespace Mockaco.Tests.Templating.Scripting
{
Expand All @@ -16,15 +9,14 @@ public class ScriptRunnerFactoryTest
[InlineData(@"JsonConvert.SerializeObject(new DateTime(2012, 04, 23, 18, 25, 43, 511, DateTimeKind.Utc))", @"\""2012-04-23T18:25:43\.511Z\""")]
[InlineData(@"new PhoneNumbers().BrazilianPhoneNumber()", @"[0-9]+")]
[InlineData(@"new Faker().Random.Guid().ToString()", @"[a-z0-9\-]+")]
[InlineData(@"new Regex(@"".*"").IsMatch(""abc"").ToString()", @"True")]
[InlineData(@"Regex.IsMatch(""abc"", "".*"").ToString()", @"True")]
[InlineData(@"new[] {1, 2, 3, 4, 5, 6, 7}.Count().ToString()", @"7")]
public async Task Can_Run_Scripts_From_Builtin_Namespaces(string input, string regexPattern)
{
var mockLogger = Moq.Mock.Of<ILogger<ScriptRunnerFactory>>();
var mockOptions = Moq.Mock.Of<IOptionsMonitor<MockacoOptions>>(o => o.CurrentValue == new MockacoOptions());

var runner = new ScriptRunnerFactory(mockLogger, mockOptions);

var result = await runner.Invoke<string, string>("", input);

Assert.Matches(regexPattern, result);
Expand Down
33 changes: 28 additions & 5 deletions website/docs/configuration/index.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
# Configuration

The configuration for Mockaco can be easily customized using the appsettings*.json files located within the Settings folder. These files allow you to configure various options provided by ASP.NET Core.
### App Settings

The configuration for Mockaco can be easily customized using the appsettings*.json files located within the Settings folder. These files allow you to configure various options [provided by ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration).

Here are the different appsettings*.json files and their purposes:

- *appsettings.Production.json*: Use this file to customize Mockaco when running it as an executable or dotnet tool.
- *appsettings.Docker.json*: This file is specifically used to customize Mockaco when running it within a Docker container.
- *appsettings.Docker.json*: This file is specifically used to customize Mockaco when running in a Docker container.
- *appsettings.Development.json*: When running Mockaco in debug mode, such as inside Visual Studio, you can use this file to customize its behavior. This environment is typically set through the launchSettings.json file.

These appsettings*.json files provide a convenient way to adjust Mockaco's settings based on the specific environment in which it is running.
Expand All @@ -20,6 +22,22 @@ For instance you could override the default URLs Mockaco will listen to, just by
}
```

### Environment variables

You can also use **environment variables** to override the configuration. For example, you can set the `ASPNETCORE_URLS` environment variable to `http://+:8080;https://+:8443` to achieve the same result as the appsettings.json example.

Another way to set the configuration is through command line arguments.

### Command line

To pass mockaco specific options through **command line**, you can use the `--Mockaco` prefix. For example, to set the `DefaultHttpStatusCode` to `NotFound` you can use the following command:

```bash
dotnet mockaco run --Mockaco:DefaultHttpStatusCode=NotFound
```

Please refer to the [ASP.NET Core documentation](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration) for more information on how to customize the configuration.

Mockaco specific options are listed in the next topics.

## Mockaco
Expand All @@ -32,7 +50,7 @@ Mockaco specific options are listed in the next topics.
"DefaultHttpContentType": "application/json",
"References": [],
"Imports": [],
"MatchedRoutesCacheDuration": 60,
"MatchedRoutesCacheDuration": 60,
"MockacoEndpoint": "_mockaco",
"VerificationEndpointName": "verification"
}
Expand All @@ -59,13 +77,13 @@ Default: `application/json`

### `References`

A list of references to other .NET assemblies to extend scripting engine.
A list of additional references to other .NET assemblies to extend scripting engine.

Default: `[]`

### `Imports`

A list of namespaces to be imported and made available in scripting engine.
A list of additional namespaces to be imported and made available in scripting engine. It is the same as calling `using` in C#.

Default: `[]`

Expand Down Expand Up @@ -101,3 +119,8 @@ Default: `Mocks`

Configure [Serilog logger](https://github.com/serilog/serilog-settings-configuration)

Just as Mockaco options, to pass Serilog specific options through command line, you can use the `--Serilog` prefix. For example, to set the `MinimumLevel` to `Information` you can use the following command:

```bash
dotnet mockaco run --Serilog:MinimumLevel=Information
```
4 changes: 4 additions & 0 deletions website/docs/reference-scripting/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Scripting Reference",
"position": 3
}
140 changes: 140 additions & 0 deletions website/docs/reference-scripting/faker.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
# Faker

## Basic usage

A `Faker` facade object is available to generate fake data within a script.

```
{
"request": {
"method": "GET"
},
"response": {
"status": "OK",
"headers": {
"Content-Type": "application/json"
},
"body": {
"name": "<#= Faker.Name.FullName() #>",
"company": "<#= Faker.Company.CompanyName() #>",
"city": "<#= Faker.Address.City() #>"
}
}
}
```

```shell
$ curl http://localhost:5000
{
"name": "Mollie Beahan",
"company": "Ziemann, Anderson and Durgan",
"city": "Ritchiemouth"
}
```

## Generating a list of items

This example creates a list of 10 items:

```
{
"request": {
"method": "GET",
"route": "/names"
},
"response": {
"body": <#=
class Person
{
public int ID { get; set; }
public string Name { get; set; }
}
var count = 10;
var people = new Person[count];
for(var i = 0; i < count; i++ ) {
people[i] = new Person { ID = i + 1, Name = new Faker().Person.FullName };
}
return JsonConvert.SerializeObject(people);
#>
}
}
```

## Localization

To generate localized data, use the `Accept-Language` HTTP header when sending a request to Mockaco. Defaults to `en` (english) fake data.

```
{
"request": {
"method": "GET"
},
"response": {
"status": "OK",
"headers": {
"Content-Type": "application/json"
},
"body": {
"name": "<#= Faker.FullName() #>",
"company": "<#= Faker.Company.CompanyName() #>",
"city": "<#= Faker.Address.City() #>"
}
}
}
```

```shell
$ curl -X GET "http://localhost:5000" -H "Accept-Language: ru"
{
"name": "Екатерина Мельникова",
"company": "Гусев - Никонов",
"city": "Тула"
}
```

```shell
$ curl -X GET "http://localhost:5000" -H "Accept-Language: pt-BR"
{
"name": "Maitê Albuquerque",
"company": "Costa S.A.",
"city": "Santo André"
}
```

## Using Bogus extensions

To use [Bogus API Extension Methods](https://github.com/bchavez/Bogus?tab=readme-ov-file#api-extension-methods), consider the following example, using the `Bogus.Extensions.Brazil` namespace to generate brazilian CPF numbers:

```
{
"request": {
"method": "GET"
},
"response": {
"status": "OK",
"body": <#= Faker.Person.Cpf() #>
}
}
```

Use the [Imports option](/docs/configuration/#imports) to import the Bogus extension methods on Mockaco startup:

```shell
$ mockaco --urls=http://+:5000 --Mockaco:Imports:0="Bogus.Extensions.Brazil"
```

Then call the mock endpoint:

```shell
$ curl -i "http://localhost:5000"
HTTP/1.1 200 OK
Content-Type: application/json
Date: Sun, 10 Mar 2024 23:44:50 GMT
Server: Kestrel
Transfer-Encoding: chunked

"422.244.459-62"
```
81 changes: 81 additions & 0 deletions website/docs/reference-scripting/global.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# Global

The Global object is a global variable that can be used to store variables that are shared between all mock requests. Its underlying storage is a `Dictionary<string, object>` object, meaning that you can store any type of variable in it. The state is not persisted between server restarts.

## Store a variable along a mock request

```
<#
Global["my-custom-variable"] = "hello";
#>
{
"request": {
"method": "GET",
"route": "ping"
},
"response": {
"status": "OK",
"body": {
"response": "<#=Global["my-custom-variable"] #>"
}
}
}
```

```shell
$ curl http://localhost:5000/ping
{
"response": "hello"
}
```

## Store state between mock calls

The Global object is shared between all mock requests, meaning that you can store a variable in one mock and use it in another.

```
{
"request": {
"method": "GET",
"route": "store"
},
"response": {
"status": "OK",
"body": {
"response": "This request stores a variable"
}
}
<#
Global["my-custom-variable"] = "hello!";
#>
}
```

```
{
"request": {
"method": "GET",
"route": "retrieve"
},
"response": {
"status": "OK",
"body": {
"response": "The variable is <#=Global["my-custom-variable"] #>"
}
}
}
```

```shell
$ curl http://localhost:5000/store
{
"response": "This request stores a variable"
}

$ curl http://localhost:5000/retrieve
{
"response": "The variable is hello!"
}
```

This feature can be used to simulate stateful APIs behaviors. Refer to the [Stateful mocks guide](/docs/guides/mocking-stateful) for more information.
Loading

0 comments on commit 36c8f27

Please sign in to comment.