mirror of
https://github.com/aykhans/dodo.git
synced 2025-07-18 15:14:01 +00:00
Compare commits
26 Commits
v0.6.1
...
3368cc0d10
Author | SHA1 | Date | |
---|---|---|---|
3368cc0d10 | |||
35263f1dd6 | |||
930e173a6a | |||
bea2a81afa | |||
53ed486b23 | |||
0b9c32a09d | |||
42d5617e3f | |||
e80ae9ab24 | |||
![]() |
86a6f7814b | ||
09034b5f9e | |||
f1ca2041c3 | |||
f5a29a2657 | |||
439f66eb87 | |||
415d0130ce | |||
abaa8e90b2 | |||
046ce74cd9 | |||
681cafc213 | |||
7e05cf4f6b | |||
934cd0ad33 | |||
69c4841a05 | |||
3cc165cbf4 | |||
59f40ad825 | |||
a170588574 | |||
2a0ac390d8 | |||
11bb8b3fb0 | |||
1aadc3419a |
4
.github/workflows/golangci-lint.yml
vendored
4
.github/workflows/golangci-lint.yml
vendored
@@ -19,7 +19,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
go-version: stable
|
go-version: stable
|
||||||
- name: golangci-lint
|
- name: golangci-lint
|
||||||
uses: golangci/golangci-lint-action@v6
|
uses: golangci/golangci-lint-action@v7
|
||||||
with:
|
with:
|
||||||
version: v1.64
|
version: v2.0.2
|
||||||
args: --timeout=10m --config=.golangci.yml
|
args: --timeout=10m --config=.golangci.yml
|
||||||
|
@@ -1,16 +1,16 @@
|
|||||||
|
version: "2"
|
||||||
|
|
||||||
run:
|
run:
|
||||||
go: "1.24"
|
go: "1.24"
|
||||||
concurrency: 8
|
concurrency: 8
|
||||||
timeout: 10m
|
timeout: 10m
|
||||||
|
|
||||||
linters:
|
linters:
|
||||||
disable-all: true
|
default: none
|
||||||
enable:
|
enable:
|
||||||
- asasalint
|
- asasalint
|
||||||
- asciicheck
|
- asciicheck
|
||||||
- errcheck
|
- errcheck
|
||||||
- gofmt
|
|
||||||
- goimports
|
|
||||||
- gomodguard
|
- gomodguard
|
||||||
- goprintffuncname
|
- goprintffuncname
|
||||||
- govet
|
- govet
|
||||||
@@ -21,7 +21,19 @@ linters:
|
|||||||
- prealloc
|
- prealloc
|
||||||
- reassign
|
- reassign
|
||||||
- staticcheck
|
- staticcheck
|
||||||
- typecheck
|
|
||||||
- unconvert
|
- unconvert
|
||||||
- unused
|
- unused
|
||||||
- whitespace
|
- whitespace
|
||||||
|
|
||||||
|
settings:
|
||||||
|
staticcheck:
|
||||||
|
checks:
|
||||||
|
- "all"
|
||||||
|
- "-S1002"
|
||||||
|
- "-ST1000"
|
||||||
|
|
||||||
|
exclusions:
|
||||||
|
rules:
|
||||||
|
- path: _test\.go
|
||||||
|
linters:
|
||||||
|
- errcheck
|
||||||
|
9
Makefile
9
Makefile
@@ -1,9 +0,0 @@
|
|||||||
lint:
|
|
||||||
golangci-lint run
|
|
||||||
|
|
||||||
build:
|
|
||||||
go build -ldflags "-s -w" -o "./dodo"
|
|
||||||
|
|
||||||
build-all:
|
|
||||||
rm -rf ./binaries
|
|
||||||
./build.sh
|
|
45
README.md
45
README.md
@@ -45,51 +45,35 @@ Download the latest binaries from the [releases](https://github.com/aykhans/dodo
|
|||||||
|
|
||||||
### Building from Source
|
### Building from Source
|
||||||
|
|
||||||
To build Dodo from source, ensure you have [Go 1.24+](https://golang.org/dl/) installed. Then follow these steps:
|
To build Dodo from source, ensure you have [Go 1.24+](https://golang.org/dl/) installed.
|
||||||
|
|
||||||
1. **Clone the repository:**
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
git clone https://github.com/aykhans/dodo.git
|
go install -ldflags "-s -w" github.com/aykhans/dodo@latest
|
||||||
```
|
```
|
||||||
|
|
||||||
2. **Navigate to the project directory:**
|
|
||||||
|
|
||||||
```sh
|
|
||||||
cd dodo
|
|
||||||
```
|
|
||||||
|
|
||||||
3. **Build the project:**
|
|
||||||
|
|
||||||
```sh
|
|
||||||
go build -ldflags "-s -w" -o dodo
|
|
||||||
```
|
|
||||||
|
|
||||||
This will generate an executable named `dodo` in the project directory.
|
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
Dodo supports CLI arguments, configuration files (JSON/YAML), or a combination of both. If both are used, CLI arguments take precedence.
|
Dodo supports CLI arguments, configuration files (JSON/YAML), or a combination of both. If both are used, CLI arguments take precedence.
|
||||||
|
|
||||||
### 1. CLI Usage
|
### 1. CLI Usage
|
||||||
|
|
||||||
Send 1000 GET requests to https://example.com with 10 parallel dodos (threads) and a timeout of 2 seconds:
|
Send 1000 GET requests to https://example.com with 10 parallel dodos (threads), each with a timeout of 2 seconds, within a maximum duration of 1 minute:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
dodo -u https://example.com -m GET -d 10 -r 1000 -t 2s
|
dodo -u https://example.com -m GET -d 10 -r 1000 -o 1m -t 2s
|
||||||
```
|
```
|
||||||
|
|
||||||
With Docker:
|
With Docker:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
docker run --rm -i aykhans/dodo -u https://example.com -m GET -d 10 -r 1000 -t 2s
|
docker run --rm -i aykhans/dodo -u https://example.com -m GET -d 10 -r 1000 -o 1m -t 2s
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. Config File Usage
|
### 2. Config File Usage
|
||||||
|
|
||||||
#### 2.1 JSON Example
|
Send 1000 GET requests to https://example.com with 10 parallel dodos (threads), each with a timeout of 800 milliseconds, within a maximum duration of 250 seconds:
|
||||||
|
|
||||||
Send 1000 GET requests to https://example.com with 10 parallel dodos (threads) and a timeout of 800 milliseconds:
|
#### 2.1 JSON Example
|
||||||
|
|
||||||
```jsonc
|
```jsonc
|
||||||
{
|
{
|
||||||
@@ -99,6 +83,7 @@ Send 1000 GET requests to https://example.com with 10 parallel dodos (threads) a
|
|||||||
"timeout": "800ms",
|
"timeout": "800ms",
|
||||||
"dodos": 10,
|
"dodos": 10,
|
||||||
"requests": 1000,
|
"requests": 1000,
|
||||||
|
"duration": "250s",
|
||||||
|
|
||||||
"params": [
|
"params": [
|
||||||
// A random value will be selected from the list for first "key1" param on each request
|
// A random value will be selected from the list for first "key1" param on each request
|
||||||
@@ -176,6 +161,7 @@ yes: false
|
|||||||
timeout: "800ms"
|
timeout: "800ms"
|
||||||
dodos: 10
|
dodos: 10
|
||||||
requests: 1000
|
requests: 1000
|
||||||
|
duration: "250s"
|
||||||
|
|
||||||
params:
|
params:
|
||||||
# A random value will be selected from the list for first "key1" param on each request
|
# A random value will be selected from the list for first "key1" param on each request
|
||||||
@@ -247,28 +233,29 @@ docker run --rm -i aykhans/dodo -f https://example.com/config.yaml
|
|||||||
CLI arguments override config file values:
|
CLI arguments override config file values:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
dodo -f /path/to/config.yaml -u https://example.com -m GET -d 10 -r 1000 -t 5s
|
dodo -f /path/to/config.yaml -u https://example.com -m GET -d 10 -r 1000 -o 1m -t 5s
|
||||||
```
|
```
|
||||||
|
|
||||||
With Docker:
|
With Docker:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
docker run --rm -i -v /path/to/config.json:/config.json aykhans/dodo -f /config.json -u https://example.com -m GET -d 10 -r 1000 -t 5s
|
docker run --rm -i -v /path/to/config.json:/config.json aykhans/dodo -f /config.json -u https://example.com -m GET -d 10 -r 1000 -o 1m -t 5s
|
||||||
```
|
```
|
||||||
|
|
||||||
## Config Parameters Reference
|
## Config Parameters Reference
|
||||||
|
|
||||||
If `Headers`, `Params`, `Cookies`, `Body`, or `Proxy` fields have multiple values, each request will choose a random value from the list.
|
If `Headers`, `Params`, `Cookies`, `Body`, or `Proxy` fields have multiple values, each request will choose a random value from the list.
|
||||||
|
|
||||||
| Parameter | JSON config file | CLI Flag | CLI Short Flag | Type | Description | Default |
|
| Parameter | config file | CLI Flag | CLI Short Flag | Type | Description | Default |
|
||||||
| --------------- | ---------------- | ------------ | -------------- | ------------------------------ | --------------------------------------------------------------- | ------- |
|
| --------------- | ----------- | ------------ | -------------- | ------------------------------ | ----------------------------------------------------------- | ------- |
|
||||||
| Config file | - | -config-file | -f | String | Path to local config file or http(s) URL of the config file | - |
|
| Config file | - | -config-file | -f | String | Path to local config file or http(s) URL of the config file | - |
|
||||||
| Yes | yes | -yes | -y | Boolean | Answer yes to all questions | false |
|
| Yes | yes | -yes | -y | Boolean | Answer yes to all questions | false |
|
||||||
| URL | url | -url | -u | String | URL to send the request to | - |
|
| URL | url | -url | -u | String | URL to send the request to | - |
|
||||||
| Method | method | -method | -m | String | HTTP method | GET |
|
| Method | method | -method | -m | String | HTTP method | GET |
|
||||||
| Requests | requests | -requests | -r | UnsignedInteger | Total number of requests to send | 1000 |
|
|
||||||
| Dodos (Threads) | dodos | -dodos | -d | UnsignedInteger | Number of dodos (threads) to send requests in parallel | 1 |
|
| Dodos (Threads) | dodos | -dodos | -d | UnsignedInteger | Number of dodos (threads) to send requests in parallel | 1 |
|
||||||
| Timeout | timeout | -timeout | -t | Duration | Timeout for canceling each request | 10s |
|
| Requests | requests | -requests | -r | UnsignedInteger | Total number of requests to send | - |
|
||||||
|
| Duration | duration | -duration | -o | Time | Maximum duration for the test | - |
|
||||||
|
| Timeout | timeout | -timeout | -t | Time | Timeout for canceling each request | 10s |
|
||||||
| Params | params | -param | -p | [{String: String OR [String]}] | Request parameters | - |
|
| Params | params | -param | -p | [{String: String OR [String]}] | Request parameters | - |
|
||||||
| Headers | headers | -header | -H | [{String: String OR [String]}] | Request headers | - |
|
| Headers | headers | -header | -H | [{String: String OR [String]}] | Request headers | - |
|
||||||
| Cookies | cookies | -cookie | -c | [{String: String OR [String]}] | Request cookies | - |
|
| Cookies | cookies | -cookie | -c | [{String: String OR [String]}] | Request cookies | - |
|
||||||
|
45
Taskfile.yaml
Normal file
45
Taskfile.yaml
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
# https://taskfile.dev
|
||||||
|
|
||||||
|
version: "3"
|
||||||
|
|
||||||
|
vars:
|
||||||
|
PLATFORMS:
|
||||||
|
- os: darwin
|
||||||
|
archs: [amd64, arm64]
|
||||||
|
- os: freebsd
|
||||||
|
archs: [386, amd64, arm]
|
||||||
|
- os: linux
|
||||||
|
archs: [386, amd64, arm, arm64]
|
||||||
|
- os: netbsd
|
||||||
|
archs: [386, amd64, arm]
|
||||||
|
- os: openbsd
|
||||||
|
archs: [386, amd64, arm, arm64]
|
||||||
|
- os: windows
|
||||||
|
archs: [386, amd64, arm64]
|
||||||
|
|
||||||
|
tasks:
|
||||||
|
run: go run main.go
|
||||||
|
|
||||||
|
fmt: gofmt -w -d .
|
||||||
|
|
||||||
|
lint: golangci-lint run
|
||||||
|
|
||||||
|
build: go build -ldflags "-s -w" -o "dodo"
|
||||||
|
|
||||||
|
build-all:
|
||||||
|
silent: true
|
||||||
|
cmds:
|
||||||
|
- rm -rf binaries
|
||||||
|
- |
|
||||||
|
{{ $ext := "" }}
|
||||||
|
{{- range $platform := .PLATFORMS }}
|
||||||
|
{{- if eq $platform.os "windows" }}
|
||||||
|
{{ $ext = ".exe" }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
|
{{- range $arch := $platform.archs }}
|
||||||
|
echo "Building for {{$platform.os}}/{{$arch}}"
|
||||||
|
GOOS={{$platform.os}} GOARCH={{$arch}} go build -ldflags "-s -w" -o "./binaries/dodo-{{$platform.os}}-{{$arch}}{{$ext}}"
|
||||||
|
{{- end }}
|
||||||
|
{{- end }}
|
||||||
|
- echo -e "\033[32m*** Build completed ***\033[0m"
|
32
build.sh
32
build.sh
@@ -1,32 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
platforms=(
|
|
||||||
"darwin,amd64"
|
|
||||||
"darwin,arm64"
|
|
||||||
"freebsd,386"
|
|
||||||
"freebsd,amd64"
|
|
||||||
"freebsd,arm"
|
|
||||||
"linux,386"
|
|
||||||
"linux,amd64"
|
|
||||||
"linux,arm"
|
|
||||||
"linux,arm64"
|
|
||||||
"netbsd,386"
|
|
||||||
"netbsd,amd64"
|
|
||||||
"netbsd,arm"
|
|
||||||
"openbsd,386"
|
|
||||||
"openbsd,amd64"
|
|
||||||
"openbsd,arm"
|
|
||||||
"openbsd,arm64"
|
|
||||||
"windows,386"
|
|
||||||
"windows,amd64"
|
|
||||||
"windows,arm64"
|
|
||||||
)
|
|
||||||
|
|
||||||
for platform in "${platforms[@]}"; do
|
|
||||||
IFS=',' read -r build_os build_arch <<< "$platform"
|
|
||||||
ext=""
|
|
||||||
if [ "$build_os" == "windows" ]; then
|
|
||||||
ext=".exe"
|
|
||||||
fi
|
|
||||||
GOOS="$build_os" GOARCH="$build_arch" go build -ldflags "-s -w" -o "./binaries/dodo-$build_os-$build_arch$ext"
|
|
||||||
done
|
|
@@ -5,6 +5,7 @@
|
|||||||
"timeout": "5s",
|
"timeout": "5s",
|
||||||
"dodos": 8,
|
"dodos": 8,
|
||||||
"requests": 1000,
|
"requests": 1000,
|
||||||
|
"duration": "10s",
|
||||||
|
|
||||||
"params": [
|
"params": [
|
||||||
{ "key1": ["value1", "value2", "value3", "value4"] },
|
{ "key1": ["value1", "value2", "value3", "value4"] },
|
||||||
|
@@ -4,6 +4,7 @@ yes: false
|
|||||||
timeout: "5s"
|
timeout: "5s"
|
||||||
dodos: 8
|
dodos: 8
|
||||||
requests: 1000
|
requests: 1000
|
||||||
|
duration: "10s"
|
||||||
|
|
||||||
params:
|
params:
|
||||||
- key1: ["value1", "value2", "value3", "value4"]
|
- key1: ["value1", "value2", "value3", "value4"]
|
||||||
|
@@ -16,8 +16,8 @@ const cliUsageText = `Usage:
|
|||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
|
|
||||||
Simple usage only with URL:
|
Simple usage:
|
||||||
dodo -u https://example.com
|
dodo -u https://example.com -o 1m
|
||||||
|
|
||||||
Usage with config file:
|
Usage with config file:
|
||||||
dodo -f /path/to/config/file/config.json
|
dodo -f /path/to/config/file/config.json
|
||||||
@@ -25,7 +25,7 @@ Usage with config file:
|
|||||||
Usage with all flags:
|
Usage with all flags:
|
||||||
dodo -f /path/to/config/file/config.json \
|
dodo -f /path/to/config/file/config.json \
|
||||||
-u https://example.com -m POST \
|
-u https://example.com -m POST \
|
||||||
-d 10 -r 1000 -t 3s \
|
-d 10 -r 1000 -o 3m -t 3s \
|
||||||
-b "body1" -body "body2" \
|
-b "body1" -body "body2" \
|
||||||
-H "header1:value1" -header "header2:value2" \
|
-H "header1:value1" -header "header2:value2" \
|
||||||
-p "param1=value1" -param "param2=value2" \
|
-p "param1=value1" -param "param2=value2" \
|
||||||
@@ -39,8 +39,9 @@ Flags:
|
|||||||
-y, -yes bool Answer yes to all questions (default %v)
|
-y, -yes bool Answer yes to all questions (default %v)
|
||||||
-f, -config-file string Path to the local config file or http(s) URL of the config file
|
-f, -config-file string Path to the local config file or http(s) URL of the config file
|
||||||
-d, -dodos uint Number of dodos(threads) (default %d)
|
-d, -dodos uint Number of dodos(threads) (default %d)
|
||||||
-r, -requests uint Number of total requests (default %d)
|
-r, -requests uint Number of total requests
|
||||||
-t, -timeout Duration Timeout for each request (e.g. 400ms, 15s, 1m10s) (default %v)
|
-o, -duration Time Maximum duration for the test (e.g. 30s, 1m, 5h)
|
||||||
|
-t, -timeout Time Timeout for each request (e.g. 400ms, 15s, 1m10s) (default %v)
|
||||||
-u, -url string URL for stress testing
|
-u, -url string URL for stress testing
|
||||||
-m, -method string HTTP Method for the request (default %s)
|
-m, -method string HTTP Method for the request (default %s)
|
||||||
-b, -body [string] Body for the request (e.g. "body text")
|
-b, -body [string] Body for the request (e.g. "body text")
|
||||||
@@ -55,7 +56,6 @@ func (config *Config) ReadCLI() (types.ConfigFile, error) {
|
|||||||
cliUsageText+"\n",
|
cliUsageText+"\n",
|
||||||
DefaultYes,
|
DefaultYes,
|
||||||
DefaultDodosCount,
|
DefaultDodosCount,
|
||||||
DefaultRequestCount,
|
|
||||||
DefaultTimeout,
|
DefaultTimeout,
|
||||||
DefaultMethod,
|
DefaultMethod,
|
||||||
)
|
)
|
||||||
@@ -70,6 +70,7 @@ func (config *Config) ReadCLI() (types.ConfigFile, error) {
|
|||||||
dodosCount = uint(0)
|
dodosCount = uint(0)
|
||||||
requestCount = uint(0)
|
requestCount = uint(0)
|
||||||
timeout time.Duration
|
timeout time.Duration
|
||||||
|
duration time.Duration
|
||||||
)
|
)
|
||||||
|
|
||||||
{
|
{
|
||||||
@@ -94,6 +95,9 @@ func (config *Config) ReadCLI() (types.ConfigFile, error) {
|
|||||||
flag.UintVar(&requestCount, "requests", 0, "Number of total requests")
|
flag.UintVar(&requestCount, "requests", 0, "Number of total requests")
|
||||||
flag.UintVar(&requestCount, "r", 0, "Number of total requests")
|
flag.UintVar(&requestCount, "r", 0, "Number of total requests")
|
||||||
|
|
||||||
|
flag.DurationVar(&duration, "duration", 0, "Maximum duration of the test")
|
||||||
|
flag.DurationVar(&duration, "o", 0, "Maximum duration of the test")
|
||||||
|
|
||||||
flag.DurationVar(&timeout, "timeout", 0, "Timeout for each request (e.g. 400ms, 15s, 1m10s)")
|
flag.DurationVar(&timeout, "timeout", 0, "Timeout for each request (e.g. 400ms, 15s, 1m10s)")
|
||||||
flag.DurationVar(&timeout, "t", 0, "Timeout for each request (e.g. 400ms, 15s, 1m10s)")
|
flag.DurationVar(&timeout, "t", 0, "Timeout for each request (e.g. 400ms, 15s, 1m10s)")
|
||||||
|
|
||||||
@@ -139,6 +143,8 @@ func (config *Config) ReadCLI() (types.ConfigFile, error) {
|
|||||||
config.DodosCount = utils.ToPtr(dodosCount)
|
config.DodosCount = utils.ToPtr(dodosCount)
|
||||||
case "requests", "r":
|
case "requests", "r":
|
||||||
config.RequestCount = utils.ToPtr(requestCount)
|
config.RequestCount = utils.ToPtr(requestCount)
|
||||||
|
case "duration", "o":
|
||||||
|
config.Duration = &types.Duration{Duration: duration}
|
||||||
case "timeout", "t":
|
case "timeout", "t":
|
||||||
config.Timeout = &types.Timeout{Duration: timeout}
|
config.Timeout = &types.Timeout{Duration: timeout}
|
||||||
case "yes", "y":
|
case "yes", "y":
|
||||||
|
181
config/cli_test.go
Normal file
181
config/cli_test.go
Normal file
@@ -0,0 +1,181 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"flag"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/aykhans/dodo/types"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestReadCLI(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
args []string
|
||||||
|
expectFile types.ConfigFile
|
||||||
|
expectError bool
|
||||||
|
expectedConfig *Config
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "simple url and duration",
|
||||||
|
args: []string{"-u", "https://example.com", "-o", "1m"},
|
||||||
|
expectFile: "",
|
||||||
|
expectError: false,
|
||||||
|
expectedConfig: &Config{
|
||||||
|
URL: &types.RequestURL{},
|
||||||
|
Duration: &types.Duration{Duration: time.Minute},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "config file only",
|
||||||
|
args: []string{"-f", "/path/to/config.json"},
|
||||||
|
expectFile: "/path/to/config.json",
|
||||||
|
expectError: false,
|
||||||
|
expectedConfig: &Config{},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "all flags",
|
||||||
|
args: []string{"-f", "/path/to/config.json", "-u", "https://example.com", "-m", "POST", "-d", "10", "-r", "1000", "-o", "3m", "-t", "3s", "-b", "body1", "-H", "header1:value1", "-p", "param1=value1", "-c", "cookie1=value1", "-x", "http://proxy.example.com:8080", "-y"},
|
||||||
|
expectFile: "/path/to/config.json",
|
||||||
|
expectError: false,
|
||||||
|
expectedConfig: &Config{
|
||||||
|
Method: stringPtr("POST"),
|
||||||
|
URL: &types.RequestURL{},
|
||||||
|
DodosCount: uintPtr(10),
|
||||||
|
RequestCount: uintPtr(1000),
|
||||||
|
Duration: &types.Duration{Duration: 3 * time.Minute},
|
||||||
|
Timeout: &types.Timeout{Duration: 3 * time.Second},
|
||||||
|
Yes: boolPtr(true),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unexpected arguments",
|
||||||
|
args: []string{"-u", "https://example.com", "extraArg"},
|
||||||
|
expectFile: "",
|
||||||
|
expectError: true,
|
||||||
|
expectedConfig: &Config{},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save original command-line arguments
|
||||||
|
origArgs := os.Args
|
||||||
|
origFlagCommandLine := flag.CommandLine
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
// Reset flag.CommandLine to its original state
|
||||||
|
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
|
||||||
|
|
||||||
|
// Override os.Args for the test
|
||||||
|
os.Args = append([]string{"dodo"}, tt.args...)
|
||||||
|
|
||||||
|
// Initialize a new config
|
||||||
|
config := NewConfig()
|
||||||
|
|
||||||
|
// Mock URL to avoid actual URL parsing issues in tests
|
||||||
|
if tt.expectedConfig.URL != nil {
|
||||||
|
urlObj := types.RequestURL{}
|
||||||
|
urlObj.Set("https://example.com")
|
||||||
|
tt.expectedConfig.URL = &urlObj
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call the function being tested
|
||||||
|
file, err := config.ReadCLI()
|
||||||
|
|
||||||
|
// Reset os.Args after test
|
||||||
|
os.Args = origArgs
|
||||||
|
|
||||||
|
// Assert expected results
|
||||||
|
assert.Equal(t, tt.expectFile, file)
|
||||||
|
if tt.expectError {
|
||||||
|
assert.Error(t, err)
|
||||||
|
} else {
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
// Check expected config values if URL is set
|
||||||
|
if tt.expectedConfig.URL != nil {
|
||||||
|
assert.NotNil(t, config.URL)
|
||||||
|
assert.Equal(t, "https://example.com", config.URL.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check duration if expected
|
||||||
|
if tt.expectedConfig.Duration != nil {
|
||||||
|
assert.NotNil(t, config.Duration)
|
||||||
|
assert.Equal(t, tt.expectedConfig.Duration.Duration, config.Duration.Duration)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check other values as needed
|
||||||
|
if tt.expectedConfig.Method != nil {
|
||||||
|
assert.Equal(t, *tt.expectedConfig.Method, *config.Method)
|
||||||
|
}
|
||||||
|
if tt.expectedConfig.DodosCount != nil {
|
||||||
|
assert.Equal(t, *tt.expectedConfig.DodosCount, *config.DodosCount)
|
||||||
|
}
|
||||||
|
if tt.expectedConfig.RequestCount != nil {
|
||||||
|
assert.Equal(t, *tt.expectedConfig.RequestCount, *config.RequestCount)
|
||||||
|
}
|
||||||
|
if tt.expectedConfig.Timeout != nil {
|
||||||
|
assert.Equal(t, tt.expectedConfig.Timeout.Duration, config.Timeout.Duration)
|
||||||
|
}
|
||||||
|
if tt.expectedConfig.Yes != nil {
|
||||||
|
assert.Equal(t, *tt.expectedConfig.Yes, *config.Yes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restore original flag.CommandLine
|
||||||
|
flag.CommandLine = origFlagCommandLine
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip the prompt tests as they require interactive input/output handling
|
||||||
|
// which is difficult to test reliably in unit tests
|
||||||
|
func TestCLIYesOrNoReaderBasic(t *testing.T) {
|
||||||
|
// We're just going to verify the function exists and returns the default value
|
||||||
|
// when called with "\n" as input (which should trigger the default path)
|
||||||
|
result := func() bool {
|
||||||
|
// Save original standard input
|
||||||
|
origStdin := os.Stdin
|
||||||
|
origStdout := os.Stdout
|
||||||
|
|
||||||
|
// Create a pipe to mock standard input
|
||||||
|
r, w, _ := os.Pipe()
|
||||||
|
os.Stdin = r
|
||||||
|
|
||||||
|
// Redirect stdout to null device
|
||||||
|
devNull, _ := os.Open(os.DevNull)
|
||||||
|
os.Stdout = devNull
|
||||||
|
|
||||||
|
// Write newline to mock stdin (should trigger default behavior)
|
||||||
|
io.WriteString(w, "\n")
|
||||||
|
w.Close()
|
||||||
|
|
||||||
|
// Call the function being tested with default=true
|
||||||
|
result := CLIYesOrNoReader("Test message", true)
|
||||||
|
|
||||||
|
// Restore original stdin and stdout
|
||||||
|
os.Stdin = origStdin
|
||||||
|
os.Stdout = origStdout
|
||||||
|
|
||||||
|
return result
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Default value should be returned
|
||||||
|
assert.True(t, result)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper types and functions for testing
|
||||||
|
func stringPtr(s string) *string {
|
||||||
|
return &s
|
||||||
|
}
|
||||||
|
|
||||||
|
func uintPtr(u uint) *uint {
|
||||||
|
return &u
|
||||||
|
}
|
||||||
|
|
||||||
|
func boolPtr(b bool) *bool {
|
||||||
|
return &b
|
||||||
|
}
|
@@ -15,12 +15,13 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
VERSION string = "0.6.1"
|
VERSION string = "0.6.3"
|
||||||
DefaultUserAgent string = "Dodo/" + VERSION
|
DefaultUserAgent string = "Dodo/" + VERSION
|
||||||
DefaultMethod string = "GET"
|
DefaultMethod string = "GET"
|
||||||
DefaultTimeout time.Duration = time.Second * 10
|
DefaultTimeout time.Duration = time.Second * 10
|
||||||
DefaultDodosCount uint = 1
|
DefaultDodosCount uint = 1
|
||||||
DefaultRequestCount uint = 1
|
DefaultRequestCount uint = 0
|
||||||
|
DefaultDuration time.Duration = 0
|
||||||
DefaultYes bool = false
|
DefaultYes bool = false
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -32,6 +33,7 @@ type RequestConfig struct {
|
|||||||
Timeout time.Duration
|
Timeout time.Duration
|
||||||
DodosCount uint
|
DodosCount uint
|
||||||
RequestCount uint
|
RequestCount uint
|
||||||
|
Duration time.Duration
|
||||||
Yes bool
|
Yes bool
|
||||||
Params types.Params
|
Params types.Params
|
||||||
Headers types.Headers
|
Headers types.Headers
|
||||||
@@ -47,6 +49,7 @@ func NewRequestConfig(conf *Config) *RequestConfig {
|
|||||||
Timeout: conf.Timeout.Duration,
|
Timeout: conf.Timeout.Duration,
|
||||||
DodosCount: *conf.DodosCount,
|
DodosCount: *conf.DodosCount,
|
||||||
RequestCount: *conf.RequestCount,
|
RequestCount: *conf.RequestCount,
|
||||||
|
Duration: conf.Duration.Duration,
|
||||||
Yes: *conf.Yes,
|
Yes: *conf.Yes,
|
||||||
Params: conf.Params,
|
Params: conf.Params,
|
||||||
Headers: conf.Headers,
|
Headers: conf.Headers,
|
||||||
@@ -57,6 +60,9 @@ func NewRequestConfig(conf *Config) *RequestConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (rc *RequestConfig) GetValidDodosCountForRequests() uint {
|
func (rc *RequestConfig) GetValidDodosCountForRequests() uint {
|
||||||
|
if rc.RequestCount == 0 {
|
||||||
|
return rc.DodosCount
|
||||||
|
}
|
||||||
return min(rc.DodosCount, rc.RequestCount)
|
return min(rc.DodosCount, rc.RequestCount)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,7 +101,17 @@ func (rc *RequestConfig) Print() {
|
|||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Dodos", rc.DodosCount})
|
t.AppendRow(table.Row{"Dodos", rc.DodosCount})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
|
if rc.RequestCount > 0 {
|
||||||
t.AppendRow(table.Row{"Requests", rc.RequestCount})
|
t.AppendRow(table.Row{"Requests", rc.RequestCount})
|
||||||
|
} else {
|
||||||
|
t.AppendRow(table.Row{"Requests"})
|
||||||
|
}
|
||||||
|
t.AppendSeparator()
|
||||||
|
if rc.Duration > 0 {
|
||||||
|
t.AppendRow(table.Row{"Duration", rc.Duration})
|
||||||
|
} else {
|
||||||
|
t.AppendRow(table.Row{"Duration"})
|
||||||
|
}
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
t.AppendRow(table.Row{"Params", rc.Params.String()})
|
t.AppendRow(table.Row{"Params", rc.Params.String()})
|
||||||
t.AppendSeparator()
|
t.AppendSeparator()
|
||||||
@@ -116,6 +132,7 @@ type Config struct {
|
|||||||
Timeout *types.Timeout `json:"timeout" yaml:"timeout"`
|
Timeout *types.Timeout `json:"timeout" yaml:"timeout"`
|
||||||
DodosCount *uint `json:"dodos" yaml:"dodos"`
|
DodosCount *uint `json:"dodos" yaml:"dodos"`
|
||||||
RequestCount *uint `json:"requests" yaml:"requests"`
|
RequestCount *uint `json:"requests" yaml:"requests"`
|
||||||
|
Duration *types.Duration `json:"duration" yaml:"duration"`
|
||||||
Yes *bool `json:"yes" yaml:"yes"`
|
Yes *bool `json:"yes" yaml:"yes"`
|
||||||
Params types.Params `json:"params" yaml:"params"`
|
Params types.Params `json:"params" yaml:"params"`
|
||||||
Headers types.Headers `json:"headers" yaml:"headers"`
|
Headers types.Headers `json:"headers" yaml:"headers"`
|
||||||
@@ -128,20 +145,20 @@ func NewConfig() *Config {
|
|||||||
return &Config{}
|
return &Config{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Config) Validate() []error {
|
func (config *Config) Validate() []error {
|
||||||
var errs []error
|
var errs []error
|
||||||
if utils.IsNilOrZero(c.URL) {
|
if utils.IsNilOrZero(config.URL) {
|
||||||
errs = append(errs, errors.New("request URL is required"))
|
errs = append(errs, errors.New("request URL is required"))
|
||||||
} else {
|
} else {
|
||||||
if c.URL.Scheme == "" {
|
if config.URL.Scheme == "" {
|
||||||
c.URL.Scheme = "http"
|
config.URL.Scheme = "http"
|
||||||
}
|
}
|
||||||
if c.URL.Scheme != "http" && c.URL.Scheme != "https" {
|
if config.URL.Scheme != "http" && config.URL.Scheme != "https" {
|
||||||
errs = append(errs, errors.New("request URL scheme must be http or https"))
|
errs = append(errs, errors.New("request URL scheme must be http or https"))
|
||||||
}
|
}
|
||||||
|
|
||||||
urlParams := types.Params{}
|
urlParams := types.Params{}
|
||||||
for key, values := range c.URL.Query() {
|
for key, values := range config.URL.Query() {
|
||||||
for _, value := range values {
|
for _, value := range values {
|
||||||
urlParams = append(urlParams, types.KeyValue[string, []string]{
|
urlParams = append(urlParams, types.KeyValue[string, []string]{
|
||||||
Key: key,
|
Key: key,
|
||||||
@@ -149,24 +166,24 @@ func (c *Config) Validate() []error {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c.Params = append(urlParams, c.Params...)
|
config.Params = append(urlParams, config.Params...)
|
||||||
c.URL.RawQuery = ""
|
config.URL.RawQuery = ""
|
||||||
}
|
}
|
||||||
|
|
||||||
if utils.IsNilOrZero(c.Method) {
|
if utils.IsNilOrZero(config.Method) {
|
||||||
errs = append(errs, errors.New("request method is required"))
|
errs = append(errs, errors.New("request method is required"))
|
||||||
}
|
}
|
||||||
if utils.IsNilOrZero(c.Timeout) {
|
if utils.IsNilOrZero(config.Timeout) {
|
||||||
errs = append(errs, errors.New("request timeout must be greater than 0"))
|
errs = append(errs, errors.New("request timeout must be greater than 0"))
|
||||||
}
|
}
|
||||||
if utils.IsNilOrZero(c.DodosCount) {
|
if utils.IsNilOrZero(config.DodosCount) {
|
||||||
errs = append(errs, errors.New("dodos count must be greater than 0"))
|
errs = append(errs, errors.New("dodos count must be greater than 0"))
|
||||||
}
|
}
|
||||||
if utils.IsNilOrZero(c.RequestCount) {
|
if utils.IsNilOrZero(config.Duration) && utils.IsNilOrZero(config.RequestCount) {
|
||||||
errs = append(errs, errors.New("request count must be greater than 0"))
|
errs = append(errs, errors.New("you should provide at least one of duration or request count"))
|
||||||
}
|
}
|
||||||
|
|
||||||
for i, proxy := range c.Proxies {
|
for i, proxy := range config.Proxies {
|
||||||
if proxy.String() == "" {
|
if proxy.String() == "" {
|
||||||
errs = append(errs, fmt.Errorf("proxies[%d]: proxy cannot be empty", i))
|
errs = append(errs, fmt.Errorf("proxies[%d]: proxy cannot be empty", i))
|
||||||
} else if schema := proxy.Scheme; !slices.Contains(SupportedProxySchemes, schema) {
|
} else if schema := proxy.Scheme; !slices.Contains(SupportedProxySchemes, schema) {
|
||||||
@@ -197,6 +214,9 @@ func (config *Config) MergeConfig(newConfig *Config) {
|
|||||||
if newConfig.RequestCount != nil {
|
if newConfig.RequestCount != nil {
|
||||||
config.RequestCount = newConfig.RequestCount
|
config.RequestCount = newConfig.RequestCount
|
||||||
}
|
}
|
||||||
|
if newConfig.Duration != nil {
|
||||||
|
config.Duration = newConfig.Duration
|
||||||
|
}
|
||||||
if newConfig.Yes != nil {
|
if newConfig.Yes != nil {
|
||||||
config.Yes = newConfig.Yes
|
config.Yes = newConfig.Yes
|
||||||
}
|
}
|
||||||
@@ -230,7 +250,11 @@ func (config *Config) SetDefaults() {
|
|||||||
if config.RequestCount == nil {
|
if config.RequestCount == nil {
|
||||||
config.RequestCount = utils.ToPtr(DefaultRequestCount)
|
config.RequestCount = utils.ToPtr(DefaultRequestCount)
|
||||||
}
|
}
|
||||||
|
if config.Duration == nil {
|
||||||
|
config.Duration = &types.Duration{Duration: DefaultDuration}
|
||||||
|
}
|
||||||
if config.Yes == nil {
|
if config.Yes == nil {
|
||||||
config.Yes = utils.ToPtr(DefaultYes)
|
config.Yes = utils.ToPtr(DefaultYes)
|
||||||
}
|
}
|
||||||
|
config.Headers.SetIfNotExists("User-Agent", DefaultUserAgent)
|
||||||
}
|
}
|
||||||
|
514
config/config_test.go
Normal file
514
config/config_test.go
Normal file
@@ -0,0 +1,514 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/aykhans/dodo/types"
|
||||||
|
"github.com/aykhans/dodo/utils"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNewConfig(t *testing.T) {
|
||||||
|
config := NewConfig()
|
||||||
|
assert.NotNil(t, config)
|
||||||
|
assert.IsType(t, &Config{}, config)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewRequestConfig(t *testing.T) {
|
||||||
|
// Create a sample Config object
|
||||||
|
urlObj := types.RequestURL{}
|
||||||
|
urlObj.Set("https://example.com")
|
||||||
|
|
||||||
|
conf := &Config{
|
||||||
|
Method: utils.ToPtr("GET"),
|
||||||
|
URL: &urlObj,
|
||||||
|
Timeout: &types.Timeout{Duration: 5 * time.Second},
|
||||||
|
DodosCount: utils.ToPtr(uint(10)),
|
||||||
|
RequestCount: utils.ToPtr(uint(100)),
|
||||||
|
Duration: &types.Duration{Duration: 1 * time.Minute},
|
||||||
|
Yes: utils.ToPtr(true),
|
||||||
|
Params: types.Params{{Key: "key1", Value: []string{"value1"}}},
|
||||||
|
Headers: types.Headers{{Key: "User-Agent", Value: []string{"TestAgent"}}},
|
||||||
|
Cookies: types.Cookies{{Key: "session", Value: []string{"123"}}},
|
||||||
|
Body: types.Body{"test body"},
|
||||||
|
Proxies: types.Proxies{url.URL{Scheme: "http", Host: "proxy.example.com:8080"}},
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call the function being tested
|
||||||
|
rc := NewRequestConfig(conf)
|
||||||
|
|
||||||
|
// Assert the fields are correctly mapped
|
||||||
|
assert.Equal(t, "GET", rc.Method)
|
||||||
|
assert.Equal(t, "https://example.com", rc.URL.String())
|
||||||
|
assert.Equal(t, 5*time.Second, rc.Timeout)
|
||||||
|
assert.Equal(t, uint(10), rc.DodosCount)
|
||||||
|
assert.Equal(t, uint(100), rc.RequestCount)
|
||||||
|
assert.Equal(t, 1*time.Minute, rc.Duration)
|
||||||
|
assert.True(t, rc.Yes)
|
||||||
|
assert.Equal(t, types.Params{{Key: "key1", Value: []string{"value1"}}}, rc.Params)
|
||||||
|
assert.Equal(t, types.Headers{{Key: "User-Agent", Value: []string{"TestAgent"}}}, rc.Headers)
|
||||||
|
assert.Equal(t, types.Cookies{{Key: "session", Value: []string{"123"}}}, rc.Cookies)
|
||||||
|
assert.Equal(t, types.Body{"test body"}, rc.Body)
|
||||||
|
assert.Equal(t, types.Proxies{url.URL{Scheme: "http", Host: "proxy.example.com:8080"}}, rc.Proxies)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetValidDodosCountForRequests(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
dodosCount uint
|
||||||
|
requestCount uint
|
||||||
|
expected uint
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "no request count limit",
|
||||||
|
dodosCount: 10,
|
||||||
|
requestCount: 0,
|
||||||
|
expected: 10,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "dodos count less than request count",
|
||||||
|
dodosCount: 5,
|
||||||
|
requestCount: 100,
|
||||||
|
expected: 5,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "dodos count greater than request count",
|
||||||
|
dodosCount: 100,
|
||||||
|
requestCount: 10,
|
||||||
|
expected: 10,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "dodos count equal to request count",
|
||||||
|
dodosCount: 50,
|
||||||
|
requestCount: 50,
|
||||||
|
expected: 50,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
rc := &RequestConfig{
|
||||||
|
DodosCount: tt.dodosCount,
|
||||||
|
RequestCount: tt.requestCount,
|
||||||
|
}
|
||||||
|
result := rc.GetValidDodosCountForRequests()
|
||||||
|
assert.Equal(t, tt.expected, result)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetMaxConns(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
dodosCount uint
|
||||||
|
requestCount uint
|
||||||
|
minConns uint
|
||||||
|
expected uint
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "min connections higher than valid dodos count",
|
||||||
|
dodosCount: 10,
|
||||||
|
requestCount: 0,
|
||||||
|
minConns: 20,
|
||||||
|
expected: 30, // 20 * 150%
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "min connections lower than valid dodos count",
|
||||||
|
dodosCount: 30,
|
||||||
|
requestCount: 0,
|
||||||
|
minConns: 10,
|
||||||
|
expected: 45, // 30 * 150%
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "request count limits dodos count",
|
||||||
|
dodosCount: 100,
|
||||||
|
requestCount: 20,
|
||||||
|
minConns: 5,
|
||||||
|
expected: 30, // 20 * 150%
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
rc := &RequestConfig{
|
||||||
|
DodosCount: tt.dodosCount,
|
||||||
|
RequestCount: tt.requestCount,
|
||||||
|
}
|
||||||
|
result := rc.GetMaxConns(tt.minConns)
|
||||||
|
assert.Equal(t, tt.expected, result)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip the Print test as it's mainly a formatting function
|
||||||
|
// that uses external table rendering library
|
||||||
|
func TestRequestConfigPrint(t *testing.T) {
|
||||||
|
// Create a sample RequestConfig
|
||||||
|
rc := &RequestConfig{
|
||||||
|
Method: "GET",
|
||||||
|
URL: url.URL{Scheme: "https", Host: "example.com"},
|
||||||
|
Timeout: 5 * time.Second,
|
||||||
|
DodosCount: 10,
|
||||||
|
RequestCount: 100,
|
||||||
|
Duration: 1 * time.Minute,
|
||||||
|
Params: types.Params{{Key: "param1", Value: []string{"value1"}}},
|
||||||
|
Headers: types.Headers{{Key: "User-Agent", Value: []string{"TestAgent"}}},
|
||||||
|
Cookies: types.Cookies{{Key: "session", Value: []string{"123"}}},
|
||||||
|
Body: types.Body{"test body"},
|
||||||
|
Proxies: types.Proxies{url.URL{Scheme: "http", Host: "proxy.example.com:8080"}},
|
||||||
|
}
|
||||||
|
|
||||||
|
// We'll just call the function to ensure it doesn't panic
|
||||||
|
// Redirect output to /dev/null
|
||||||
|
origStdout := os.Stdout
|
||||||
|
devNull, _ := os.Open(os.DevNull)
|
||||||
|
os.Stdout = devNull
|
||||||
|
|
||||||
|
// Call the function
|
||||||
|
rc.Print()
|
||||||
|
|
||||||
|
// Restore stdout
|
||||||
|
os.Stdout = origStdout
|
||||||
|
|
||||||
|
// No assertions needed, we're just checking that it doesn't panic
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigValidate(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
config *Config
|
||||||
|
expectedErrors int
|
||||||
|
expectURLQuery bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "valid config",
|
||||||
|
config: &Config{
|
||||||
|
Method: utils.ToPtr("GET"),
|
||||||
|
URL: func() *types.RequestURL { u := &types.RequestURL{}; u.Set("https://example.com"); return u }(),
|
||||||
|
Timeout: &types.Timeout{Duration: 5 * time.Second},
|
||||||
|
DodosCount: utils.ToPtr(uint(10)),
|
||||||
|
RequestCount: utils.ToPtr(uint(100)),
|
||||||
|
Duration: &types.Duration{Duration: 1 * time.Minute},
|
||||||
|
},
|
||||||
|
expectedErrors: 0,
|
||||||
|
expectURLQuery: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "missing URL",
|
||||||
|
config: &Config{
|
||||||
|
Method: utils.ToPtr("GET"),
|
||||||
|
URL: nil,
|
||||||
|
Timeout: &types.Timeout{Duration: 5 * time.Second},
|
||||||
|
DodosCount: utils.ToPtr(uint(10)),
|
||||||
|
RequestCount: utils.ToPtr(uint(100)),
|
||||||
|
Duration: &types.Duration{Duration: 1 * time.Minute},
|
||||||
|
},
|
||||||
|
expectedErrors: 1,
|
||||||
|
expectURLQuery: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "missing method",
|
||||||
|
config: &Config{
|
||||||
|
Method: nil,
|
||||||
|
URL: func() *types.RequestURL { u := &types.RequestURL{}; u.Set("https://example.com"); return u }(),
|
||||||
|
Timeout: &types.Timeout{Duration: 5 * time.Second},
|
||||||
|
DodosCount: utils.ToPtr(uint(10)),
|
||||||
|
RequestCount: utils.ToPtr(uint(100)),
|
||||||
|
Duration: &types.Duration{Duration: 1 * time.Minute},
|
||||||
|
},
|
||||||
|
expectedErrors: 1,
|
||||||
|
expectURLQuery: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid URL scheme",
|
||||||
|
config: &Config{
|
||||||
|
Method: utils.ToPtr("GET"),
|
||||||
|
URL: func() *types.RequestURL { u := &types.RequestURL{}; u.Scheme = "ftp"; u.Host = "example.com"; return u }(),
|
||||||
|
Timeout: &types.Timeout{Duration: 5 * time.Second},
|
||||||
|
DodosCount: utils.ToPtr(uint(10)),
|
||||||
|
RequestCount: utils.ToPtr(uint(100)),
|
||||||
|
Duration: &types.Duration{Duration: 1 * time.Minute},
|
||||||
|
},
|
||||||
|
expectedErrors: 1,
|
||||||
|
expectURLQuery: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "missing both duration and request count",
|
||||||
|
config: &Config{
|
||||||
|
Method: utils.ToPtr("GET"),
|
||||||
|
URL: func() *types.RequestURL { u := &types.RequestURL{}; u.Set("https://example.com"); return u }(),
|
||||||
|
Timeout: &types.Timeout{Duration: 5 * time.Second},
|
||||||
|
DodosCount: utils.ToPtr(uint(10)),
|
||||||
|
RequestCount: utils.ToPtr(uint(0)),
|
||||||
|
Duration: &types.Duration{Duration: 0},
|
||||||
|
},
|
||||||
|
expectedErrors: 1,
|
||||||
|
expectURLQuery: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "URL with query parameters",
|
||||||
|
config: &Config{
|
||||||
|
Method: utils.ToPtr("GET"),
|
||||||
|
URL: func() *types.RequestURL {
|
||||||
|
u := &types.RequestURL{}
|
||||||
|
u.Set("https://example.com?param1=value1¶m2=value2")
|
||||||
|
return u
|
||||||
|
}(),
|
||||||
|
Timeout: &types.Timeout{Duration: 5 * time.Second},
|
||||||
|
DodosCount: utils.ToPtr(uint(10)),
|
||||||
|
RequestCount: utils.ToPtr(uint(100)),
|
||||||
|
Duration: &types.Duration{Duration: 1 * time.Minute},
|
||||||
|
},
|
||||||
|
expectedErrors: 0,
|
||||||
|
expectURLQuery: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid proxy scheme",
|
||||||
|
config: &Config{
|
||||||
|
Method: utils.ToPtr("GET"),
|
||||||
|
URL: func() *types.RequestURL { u := &types.RequestURL{}; u.Set("https://example.com"); return u }(),
|
||||||
|
Timeout: &types.Timeout{Duration: 5 * time.Second},
|
||||||
|
DodosCount: utils.ToPtr(uint(10)),
|
||||||
|
RequestCount: utils.ToPtr(uint(100)),
|
||||||
|
Duration: &types.Duration{Duration: 1 * time.Minute},
|
||||||
|
Proxies: types.Proxies{url.URL{Scheme: "invalid", Host: "proxy.example.com:8080"}},
|
||||||
|
},
|
||||||
|
expectedErrors: 1,
|
||||||
|
expectURLQuery: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
errors := tt.config.Validate()
|
||||||
|
|
||||||
|
// Check number of errors
|
||||||
|
assert.Len(t, errors, tt.expectedErrors)
|
||||||
|
|
||||||
|
// Check if URL query parameters are extracted properly
|
||||||
|
if tt.expectURLQuery {
|
||||||
|
assert.Empty(t, tt.config.URL.RawQuery)
|
||||||
|
assert.NotEmpty(t, tt.config.Params)
|
||||||
|
found := false
|
||||||
|
for _, param := range tt.config.Params {
|
||||||
|
if param.Key == "param1" && len(param.Value) > 0 && param.Value[0] == "value1" {
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert.True(t, found, "Expected param1=value1 in Params but not found")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeConfig(t *testing.T) {
|
||||||
|
baseURL := func() *types.RequestURL { u := &types.RequestURL{}; u.Set("https://example.com"); return u }()
|
||||||
|
newURL := func() *types.RequestURL { u := &types.RequestURL{}; u.Set("https://new-example.com"); return u }()
|
||||||
|
|
||||||
|
baseConfig := &Config{
|
||||||
|
Method: utils.ToPtr("GET"),
|
||||||
|
URL: baseURL,
|
||||||
|
Timeout: &types.Timeout{Duration: 5 * time.Second},
|
||||||
|
DodosCount: utils.ToPtr(uint(10)),
|
||||||
|
RequestCount: utils.ToPtr(uint(100)),
|
||||||
|
Duration: &types.Duration{Duration: 1 * time.Minute},
|
||||||
|
Yes: utils.ToPtr(false),
|
||||||
|
Params: types.Params{{Key: "base-param", Value: []string{"base-value"}}},
|
||||||
|
Headers: types.Headers{{Key: "base-header", Value: []string{"base-value"}}},
|
||||||
|
Cookies: types.Cookies{{Key: "base-cookie", Value: []string{"base-value"}}},
|
||||||
|
Body: types.Body{"base-body"},
|
||||||
|
Proxies: types.Proxies{url.URL{Scheme: "http", Host: "base-proxy.example.com:8080"}},
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
newConfig *Config
|
||||||
|
assertions func(t *testing.T, result *Config)
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "merge all fields",
|
||||||
|
newConfig: &Config{
|
||||||
|
Method: utils.ToPtr("POST"),
|
||||||
|
URL: newURL,
|
||||||
|
Timeout: &types.Timeout{Duration: 10 * time.Second},
|
||||||
|
DodosCount: utils.ToPtr(uint(20)),
|
||||||
|
RequestCount: utils.ToPtr(uint(200)),
|
||||||
|
Duration: &types.Duration{Duration: 2 * time.Minute},
|
||||||
|
Yes: utils.ToPtr(true),
|
||||||
|
Params: types.Params{{Key: "new-param", Value: []string{"new-value"}}},
|
||||||
|
Headers: types.Headers{{Key: "new-header", Value: []string{"new-value"}}},
|
||||||
|
Cookies: types.Cookies{{Key: "new-cookie", Value: []string{"new-value"}}},
|
||||||
|
Body: types.Body{"new-body"},
|
||||||
|
Proxies: types.Proxies{url.URL{Scheme: "http", Host: "new-proxy.example.com:8080"}},
|
||||||
|
},
|
||||||
|
assertions: func(t *testing.T, result *Config) {
|
||||||
|
assert.Equal(t, "POST", *result.Method)
|
||||||
|
assert.Equal(t, "https://new-example.com", result.URL.String())
|
||||||
|
assert.Equal(t, 10*time.Second, result.Timeout.Duration)
|
||||||
|
assert.Equal(t, uint(20), *result.DodosCount)
|
||||||
|
assert.Equal(t, uint(200), *result.RequestCount)
|
||||||
|
assert.Equal(t, 2*time.Minute, result.Duration.Duration)
|
||||||
|
assert.True(t, *result.Yes)
|
||||||
|
assert.Equal(t, types.Params{{Key: "new-param", Value: []string{"new-value"}}}, result.Params)
|
||||||
|
assert.Equal(t, types.Headers{{Key: "new-header", Value: []string{"new-value"}}}, result.Headers)
|
||||||
|
assert.Equal(t, types.Cookies{{Key: "new-cookie", Value: []string{"new-value"}}}, result.Cookies)
|
||||||
|
assert.Equal(t, types.Body{"new-body"}, result.Body)
|
||||||
|
assert.Equal(t, types.Proxies{url.URL{Scheme: "http", Host: "new-proxy.example.com:8080"}}, result.Proxies)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "merge only specified fields",
|
||||||
|
newConfig: &Config{
|
||||||
|
Method: utils.ToPtr("POST"),
|
||||||
|
URL: newURL,
|
||||||
|
Yes: utils.ToPtr(true),
|
||||||
|
},
|
||||||
|
assertions: func(t *testing.T, result *Config) {
|
||||||
|
assert.Equal(t, "POST", *result.Method)
|
||||||
|
assert.Equal(t, "https://new-example.com", result.URL.String())
|
||||||
|
assert.Equal(t, 5*time.Second, result.Timeout.Duration) // unchanged
|
||||||
|
assert.Equal(t, uint(10), *result.DodosCount) // unchanged
|
||||||
|
assert.Equal(t, uint(100), *result.RequestCount) // unchanged
|
||||||
|
assert.Equal(t, 1*time.Minute, result.Duration.Duration) // unchanged
|
||||||
|
assert.True(t, *result.Yes) // changed
|
||||||
|
assert.Equal(t, types.Params{{Key: "base-param", Value: []string{"base-value"}}}, result.Params) // unchanged
|
||||||
|
assert.Equal(t, types.Headers{{Key: "base-header", Value: []string{"base-value"}}}, result.Headers) // unchanged
|
||||||
|
assert.Equal(t, types.Cookies{{Key: "base-cookie", Value: []string{"base-value"}}}, result.Cookies) // unchanged
|
||||||
|
assert.Equal(t, types.Body{"base-body"}, result.Body) // unchanged
|
||||||
|
assert.Equal(t, types.Proxies{url.URL{Scheme: "http", Host: "base-proxy.example.com:8080"}}, result.Proxies) // unchanged
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "merge empty config",
|
||||||
|
newConfig: &Config{},
|
||||||
|
assertions: func(t *testing.T, result *Config) {
|
||||||
|
// All fields should remain unchanged
|
||||||
|
assert.Equal(t, "GET", *result.Method)
|
||||||
|
assert.Equal(t, "https://example.com", result.URL.String())
|
||||||
|
assert.Equal(t, 5*time.Second, result.Timeout.Duration)
|
||||||
|
assert.Equal(t, uint(10), *result.DodosCount)
|
||||||
|
assert.Equal(t, uint(100), *result.RequestCount)
|
||||||
|
assert.Equal(t, 1*time.Minute, result.Duration.Duration)
|
||||||
|
assert.False(t, *result.Yes)
|
||||||
|
assert.Equal(t, types.Params{{Key: "base-param", Value: []string{"base-value"}}}, result.Params)
|
||||||
|
assert.Equal(t, types.Headers{{Key: "base-header", Value: []string{"base-value"}}}, result.Headers)
|
||||||
|
assert.Equal(t, types.Cookies{{Key: "base-cookie", Value: []string{"base-value"}}}, result.Cookies)
|
||||||
|
assert.Equal(t, types.Body{"base-body"}, result.Body)
|
||||||
|
assert.Equal(t, types.Proxies{url.URL{Scheme: "http", Host: "base-proxy.example.com:8080"}}, result.Proxies)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
// Create a copy of the base config for each test
|
||||||
|
baseURL := func() *types.RequestURL { u := &types.RequestURL{}; u.Set("https://example.com"); return u }()
|
||||||
|
testConfig := &Config{
|
||||||
|
Method: utils.ToPtr(*baseConfig.Method),
|
||||||
|
URL: baseURL,
|
||||||
|
Timeout: &types.Timeout{Duration: baseConfig.Timeout.Duration},
|
||||||
|
DodosCount: utils.ToPtr(*baseConfig.DodosCount),
|
||||||
|
RequestCount: utils.ToPtr(*baseConfig.RequestCount),
|
||||||
|
Duration: &types.Duration{Duration: baseConfig.Duration.Duration},
|
||||||
|
Yes: utils.ToPtr(*baseConfig.Yes),
|
||||||
|
Params: append(types.Params{}, baseConfig.Params...),
|
||||||
|
Headers: append(types.Headers{}, baseConfig.Headers...),
|
||||||
|
Cookies: append(types.Cookies{}, baseConfig.Cookies...),
|
||||||
|
Body: append(types.Body{}, baseConfig.Body...),
|
||||||
|
Proxies: append(types.Proxies{}, baseConfig.Proxies...),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call the function being tested
|
||||||
|
testConfig.MergeConfig(tt.newConfig)
|
||||||
|
|
||||||
|
// Run assertions
|
||||||
|
tt.assertions(t, testConfig)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetDefaults(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
config *Config
|
||||||
|
validate func(t *testing.T, config *Config)
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "empty config",
|
||||||
|
config: &Config{},
|
||||||
|
validate: func(t *testing.T, config *Config) {
|
||||||
|
assert.Equal(t, DefaultMethod, *config.Method)
|
||||||
|
assert.Equal(t, DefaultTimeout, config.Timeout.Duration)
|
||||||
|
assert.Equal(t, DefaultDodosCount, *config.DodosCount)
|
||||||
|
assert.Equal(t, DefaultRequestCount, *config.RequestCount)
|
||||||
|
assert.Equal(t, DefaultDuration, config.Duration.Duration)
|
||||||
|
assert.Equal(t, DefaultYes, *config.Yes)
|
||||||
|
assert.True(t, config.Headers.Has("User-Agent"))
|
||||||
|
userAgent := config.Headers.GetValue("User-Agent")
|
||||||
|
assert.NotNil(t, userAgent)
|
||||||
|
assert.Contains(t, (*userAgent)[0], DefaultUserAgent)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "partial config",
|
||||||
|
config: &Config{
|
||||||
|
Method: utils.ToPtr("POST"),
|
||||||
|
Timeout: &types.Timeout{Duration: 30 * time.Second},
|
||||||
|
Headers: types.Headers{{Key: "Custom-Header", Value: []string{"value"}}},
|
||||||
|
},
|
||||||
|
validate: func(t *testing.T, config *Config) {
|
||||||
|
assert.Equal(t, "POST", *config.Method) // should keep existing value
|
||||||
|
assert.Equal(t, 30*time.Second, config.Timeout.Duration) // should keep existing value
|
||||||
|
assert.Equal(t, DefaultDodosCount, *config.DodosCount) // should set default
|
||||||
|
assert.Equal(t, DefaultRequestCount, *config.RequestCount) // should set default
|
||||||
|
assert.Equal(t, DefaultDuration, config.Duration.Duration) // should set default
|
||||||
|
assert.Equal(t, DefaultYes, *config.Yes) // should set default
|
||||||
|
assert.True(t, config.Headers.Has("Custom-Header")) // should keep existing header
|
||||||
|
assert.True(t, config.Headers.Has("User-Agent")) // should add User-Agent
|
||||||
|
userAgent := config.Headers.GetValue("User-Agent")
|
||||||
|
assert.NotNil(t, userAgent)
|
||||||
|
assert.Contains(t, (*userAgent)[0], DefaultUserAgent)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "complete config",
|
||||||
|
config: &Config{
|
||||||
|
Method: utils.ToPtr("DELETE"),
|
||||||
|
URL: func() *types.RequestURL { u := &types.RequestURL{}; u.Set("https://example.com"); return u }(),
|
||||||
|
Timeout: &types.Timeout{Duration: 15 * time.Second},
|
||||||
|
DodosCount: utils.ToPtr(uint(5)),
|
||||||
|
RequestCount: utils.ToPtr(uint(500)),
|
||||||
|
Duration: &types.Duration{Duration: 5 * time.Minute},
|
||||||
|
Yes: utils.ToPtr(true),
|
||||||
|
Headers: types.Headers{{Key: "User-Agent", Value: []string{"CustomAgent"}}},
|
||||||
|
},
|
||||||
|
validate: func(t *testing.T, config *Config) {
|
||||||
|
assert.Equal(t, "DELETE", *config.Method)
|
||||||
|
assert.Equal(t, 15*time.Second, config.Timeout.Duration)
|
||||||
|
assert.Equal(t, uint(5), *config.DodosCount)
|
||||||
|
assert.Equal(t, uint(500), *config.RequestCount)
|
||||||
|
assert.Equal(t, 5*time.Minute, config.Duration.Duration)
|
||||||
|
assert.True(t, *config.Yes)
|
||||||
|
assert.True(t, config.Headers.Has("User-Agent"))
|
||||||
|
userAgent := config.Headers.GetValue("User-Agent")
|
||||||
|
assert.NotNil(t, userAgent)
|
||||||
|
assert.Equal(t, "CustomAgent", (*userAgent)[0]) // should keep custom user agent
|
||||||
|
assert.NotEqual(t, DefaultUserAgent, (*userAgent)[0]) // should not overwrite
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
// Call the function being tested
|
||||||
|
tt.config.SetDefaults()
|
||||||
|
|
||||||
|
// Validate the result
|
||||||
|
tt.validate(t, tt.config)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
@@ -34,7 +34,7 @@ func (config *Config) ReadFile(filePath types.ConfigFile) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to fetch config file from %s", filePath)
|
return fmt.Errorf("failed to fetch config file from %s", filePath)
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer func() { _ = resp.Body.Close() }()
|
||||||
|
|
||||||
data, err = io.ReadAll(io.Reader(resp.Body))
|
data, err = io.ReadAll(io.Reader(resp.Body))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -47,9 +47,10 @@ func (config *Config) ReadFile(filePath types.ConfigFile) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if fileExt == "json" {
|
switch fileExt {
|
||||||
|
case "json":
|
||||||
return parseJSONConfig(data, config)
|
return parseJSONConfig(data, config)
|
||||||
} else if fileExt == "yml" || fileExt == "yaml" {
|
case "yml", "yaml":
|
||||||
return parseYAMLConfig(data, config)
|
return parseYAMLConfig(data, config)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
350
config/file_test.go
Normal file
350
config/file_test.go
Normal file
@@ -0,0 +1,350 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/aykhans/dodo/types"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestReadFile(t *testing.T) {
|
||||||
|
// Create temporary files for testing
|
||||||
|
tempDir := t.TempDir()
|
||||||
|
|
||||||
|
// Create a valid JSON config file
|
||||||
|
validJSONFile := filepath.Join(tempDir, "valid.json")
|
||||||
|
jsonContent := `{
|
||||||
|
"method": "POST",
|
||||||
|
"url": "https://example.com",
|
||||||
|
"timeout": "5s",
|
||||||
|
"dodos": 5,
|
||||||
|
"requests": 100,
|
||||||
|
"duration": "1m",
|
||||||
|
"yes": true,
|
||||||
|
"headers": [{"Content-Type": "application/json"}]
|
||||||
|
}`
|
||||||
|
err := os.WriteFile(validJSONFile, []byte(jsonContent), 0644)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
// Create a valid YAML config file
|
||||||
|
validYAMLFile := filepath.Join(tempDir, "valid.yaml")
|
||||||
|
yamlContent := `
|
||||||
|
method: POST
|
||||||
|
url: https://example.com
|
||||||
|
timeout: 5s
|
||||||
|
dodos: 5
|
||||||
|
requests: 100
|
||||||
|
duration: 1m
|
||||||
|
yes: true
|
||||||
|
headers:
|
||||||
|
- Content-Type: application/json
|
||||||
|
`
|
||||||
|
err = os.WriteFile(validYAMLFile, []byte(yamlContent), 0644)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
// Create an invalid JSON config file
|
||||||
|
invalidJSONFile := filepath.Join(tempDir, "invalid.json")
|
||||||
|
invalidJSONContent := `{
|
||||||
|
"method": "POST",
|
||||||
|
"url": "https://example.com",
|
||||||
|
syntax error
|
||||||
|
}`
|
||||||
|
err = os.WriteFile(invalidJSONFile, []byte(invalidJSONContent), 0644)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
// Create a file with unsupported extension
|
||||||
|
unsupportedFile := filepath.Join(tempDir, "config.txt")
|
||||||
|
err = os.WriteFile(unsupportedFile, []byte("some content"), 0644)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
// Setup HTTP test server for remote config
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.URL.Path {
|
||||||
|
case "/valid.json":
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
io.WriteString(w, jsonContent)
|
||||||
|
case "/invalid.json":
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
io.WriteString(w, invalidJSONContent)
|
||||||
|
case "/valid.yaml":
|
||||||
|
w.Header().Set("Content-Type", "application/yaml")
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
io.WriteString(w, yamlContent)
|
||||||
|
default:
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
filePath types.ConfigFile
|
||||||
|
expectErr bool
|
||||||
|
validate func(t *testing.T, config *Config)
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "valid local JSON file",
|
||||||
|
filePath: types.ConfigFile(validJSONFile),
|
||||||
|
expectErr: false,
|
||||||
|
validate: func(t *testing.T, config *Config) {
|
||||||
|
assert.Equal(t, "POST", *config.Method)
|
||||||
|
assert.Equal(t, "https://example.com", config.URL.String())
|
||||||
|
assert.Equal(t, int64(5000000000), config.Timeout.Nanoseconds())
|
||||||
|
assert.Equal(t, uint(5), *config.DodosCount)
|
||||||
|
assert.Equal(t, uint(100), *config.RequestCount)
|
||||||
|
assert.Equal(t, int64(60000000000), config.Duration.Nanoseconds())
|
||||||
|
assert.True(t, *config.Yes)
|
||||||
|
assert.Equal(t, 1, len(config.Headers))
|
||||||
|
assert.Equal(t, "Content-Type", config.Headers[0].Key)
|
||||||
|
assert.Equal(t, "application/json", config.Headers[0].Value[0])
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid local YAML file",
|
||||||
|
filePath: types.ConfigFile(validYAMLFile),
|
||||||
|
expectErr: false,
|
||||||
|
validate: func(t *testing.T, config *Config) {
|
||||||
|
assert.Equal(t, "POST", *config.Method)
|
||||||
|
assert.Equal(t, "https://example.com", config.URL.String())
|
||||||
|
assert.Equal(t, int64(5000000000), config.Timeout.Nanoseconds())
|
||||||
|
assert.Equal(t, uint(5), *config.DodosCount)
|
||||||
|
assert.Equal(t, uint(100), *config.RequestCount)
|
||||||
|
assert.Equal(t, int64(60000000000), config.Duration.Nanoseconds())
|
||||||
|
assert.True(t, *config.Yes)
|
||||||
|
assert.Equal(t, 1, len(config.Headers))
|
||||||
|
assert.Equal(t, "Content-Type", config.Headers[0].Key)
|
||||||
|
assert.Equal(t, "application/json", config.Headers[0].Value[0])
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid local JSON file",
|
||||||
|
filePath: types.ConfigFile(invalidJSONFile),
|
||||||
|
expectErr: true,
|
||||||
|
validate: func(t *testing.T, config *Config) {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unsupported file extension",
|
||||||
|
filePath: types.ConfigFile(unsupportedFile),
|
||||||
|
expectErr: true,
|
||||||
|
validate: func(t *testing.T, config *Config) {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "non-existent file",
|
||||||
|
filePath: types.ConfigFile(filepath.Join(tempDir, "nonexistent.json")),
|
||||||
|
expectErr: true,
|
||||||
|
validate: func(t *testing.T, config *Config) {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid remote JSON file",
|
||||||
|
filePath: types.ConfigFile(server.URL + "/valid.json"),
|
||||||
|
expectErr: false,
|
||||||
|
validate: func(t *testing.T, config *Config) {
|
||||||
|
assert.Equal(t, "POST", *config.Method)
|
||||||
|
assert.Equal(t, "https://example.com", config.URL.String())
|
||||||
|
assert.Equal(t, int64(5000000000), config.Timeout.Nanoseconds())
|
||||||
|
assert.Equal(t, uint(5), *config.DodosCount)
|
||||||
|
assert.Equal(t, uint(100), *config.RequestCount)
|
||||||
|
assert.Equal(t, int64(60000000000), config.Duration.Nanoseconds())
|
||||||
|
assert.True(t, *config.Yes)
|
||||||
|
assert.Equal(t, 1, len(config.Headers))
|
||||||
|
assert.Equal(t, "Content-Type", config.Headers[0].Key)
|
||||||
|
assert.Equal(t, "application/json", config.Headers[0].Value[0])
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid remote YAML file",
|
||||||
|
filePath: types.ConfigFile(server.URL + "/valid.yaml"),
|
||||||
|
expectErr: false,
|
||||||
|
validate: func(t *testing.T, config *Config) {
|
||||||
|
assert.Equal(t, "POST", *config.Method)
|
||||||
|
assert.Equal(t, "https://example.com", config.URL.String())
|
||||||
|
assert.Equal(t, int64(5000000000), config.Timeout.Nanoseconds())
|
||||||
|
assert.Equal(t, uint(5), *config.DodosCount)
|
||||||
|
assert.Equal(t, uint(100), *config.RequestCount)
|
||||||
|
assert.Equal(t, int64(60000000000), config.Duration.Nanoseconds())
|
||||||
|
assert.True(t, *config.Yes)
|
||||||
|
assert.Equal(t, 1, len(config.Headers))
|
||||||
|
assert.Equal(t, "Content-Type", config.Headers[0].Key)
|
||||||
|
assert.Equal(t, "application/json", config.Headers[0].Value[0])
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid remote JSON file",
|
||||||
|
filePath: types.ConfigFile(server.URL + "/invalid.json"),
|
||||||
|
expectErr: true,
|
||||||
|
validate: func(t *testing.T, config *Config) {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "non-existent remote file",
|
||||||
|
filePath: types.ConfigFile(server.URL + "/nonexistent.json"),
|
||||||
|
expectErr: true,
|
||||||
|
validate: func(t *testing.T, config *Config) {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid URL",
|
||||||
|
filePath: types.ConfigFile("http://nonexistent.example.com/config.json"),
|
||||||
|
expectErr: true,
|
||||||
|
validate: func(t *testing.T, config *Config) {},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
config := NewConfig()
|
||||||
|
err := config.ReadFile(tt.filePath)
|
||||||
|
|
||||||
|
if tt.expectErr {
|
||||||
|
assert.Error(t, err)
|
||||||
|
} else {
|
||||||
|
assert.NoError(t, err)
|
||||||
|
tt.validate(t, config)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseJSONConfig(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
jsonData string
|
||||||
|
expectErr bool
|
||||||
|
validate func(t *testing.T, config *Config)
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "valid JSON config",
|
||||||
|
jsonData: `{
|
||||||
|
"method": "POST",
|
||||||
|
"url": "https://example.com",
|
||||||
|
"timeout": "5s",
|
||||||
|
"dodos": 5,
|
||||||
|
"requests": 100
|
||||||
|
}`,
|
||||||
|
expectErr: false,
|
||||||
|
validate: func(t *testing.T, config *Config) {
|
||||||
|
assert.Equal(t, "POST", *config.Method)
|
||||||
|
assert.Equal(t, "https://example.com", config.URL.String())
|
||||||
|
assert.Equal(t, int64(5000000000), config.Timeout.Nanoseconds())
|
||||||
|
assert.Equal(t, uint(5), *config.DodosCount)
|
||||||
|
assert.Equal(t, uint(100), *config.RequestCount)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid JSON syntax",
|
||||||
|
jsonData: `{
|
||||||
|
"method": "POST",
|
||||||
|
"url": "https://example.com",
|
||||||
|
syntax error
|
||||||
|
}`,
|
||||||
|
expectErr: true,
|
||||||
|
validate: func(t *testing.T, config *Config) {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid type for field",
|
||||||
|
jsonData: `{
|
||||||
|
"method": "POST",
|
||||||
|
"url": "https://example.com",
|
||||||
|
"dodos": "not-a-number"
|
||||||
|
}`,
|
||||||
|
expectErr: true,
|
||||||
|
validate: func(t *testing.T, config *Config) {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "empty JSON object",
|
||||||
|
jsonData: `{}`,
|
||||||
|
expectErr: false,
|
||||||
|
validate: func(t *testing.T, config *Config) {
|
||||||
|
assert.Nil(t, config.Method)
|
||||||
|
assert.Nil(t, config.URL)
|
||||||
|
assert.Nil(t, config.Timeout)
|
||||||
|
assert.Nil(t, config.DodosCount)
|
||||||
|
assert.Nil(t, config.RequestCount)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
config := NewConfig()
|
||||||
|
err := parseJSONConfig([]byte(tt.jsonData), config)
|
||||||
|
|
||||||
|
if tt.expectErr {
|
||||||
|
assert.Error(t, err)
|
||||||
|
} else {
|
||||||
|
assert.NoError(t, err)
|
||||||
|
tt.validate(t, config)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseYAMLConfig(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
yamlData string
|
||||||
|
expectErr bool
|
||||||
|
validate func(t *testing.T, config *Config)
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "valid YAML config",
|
||||||
|
yamlData: `
|
||||||
|
method: POST
|
||||||
|
url: https://example.com
|
||||||
|
timeout: 5s
|
||||||
|
dodos: 5
|
||||||
|
requests: 100
|
||||||
|
`,
|
||||||
|
expectErr: false,
|
||||||
|
validate: func(t *testing.T, config *Config) {
|
||||||
|
assert.Equal(t, "POST", *config.Method)
|
||||||
|
assert.Equal(t, "https://example.com", config.URL.String())
|
||||||
|
assert.Equal(t, int64(5000000000), config.Timeout.Nanoseconds())
|
||||||
|
assert.Equal(t, uint(5), *config.DodosCount)
|
||||||
|
assert.Equal(t, uint(100), *config.RequestCount)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid YAML syntax",
|
||||||
|
yamlData: `
|
||||||
|
method: POST
|
||||||
|
url: https://example.com
|
||||||
|
dodos: 5
|
||||||
|
invalid indentation
|
||||||
|
`,
|
||||||
|
expectErr: true,
|
||||||
|
validate: func(t *testing.T, config *Config) {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "empty YAML",
|
||||||
|
yamlData: ``,
|
||||||
|
expectErr: false,
|
||||||
|
validate: func(t *testing.T, config *Config) {
|
||||||
|
assert.Nil(t, config.Method)
|
||||||
|
assert.Nil(t, config.URL)
|
||||||
|
assert.Nil(t, config.Timeout)
|
||||||
|
assert.Nil(t, config.DodosCount)
|
||||||
|
assert.Nil(t, config.RequestCount)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
config := NewConfig()
|
||||||
|
err := parseYAMLConfig([]byte(tt.yamlData), config)
|
||||||
|
|
||||||
|
if tt.expectErr {
|
||||||
|
assert.Error(t, err)
|
||||||
|
} else {
|
||||||
|
assert.NoError(t, err)
|
||||||
|
tt.validate(t, config)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
15
go.mod
15
go.mod
@@ -4,18 +4,21 @@ go 1.24.0
|
|||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/jedib0t/go-pretty/v6 v6.6.7
|
github.com/jedib0t/go-pretty/v6 v6.6.7
|
||||||
github.com/valyala/fasthttp v1.59.0
|
github.com/stretchr/testify v1.10.0
|
||||||
|
github.com/valyala/fasthttp v1.60.0
|
||||||
gopkg.in/yaml.v3 v3.0.1
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/andybalholm/brotli v1.1.1 // indirect
|
github.com/andybalholm/brotli v1.1.1 // indirect
|
||||||
github.com/klauspost/compress v1.17.11 // indirect
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
|
github.com/klauspost/compress v1.18.0 // indirect
|
||||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
github.com/rivo/uniseg v0.4.7 // indirect
|
github.com/rivo/uniseg v0.4.7 // indirect
|
||||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||||
golang.org/x/net v0.36.0 // indirect
|
golang.org/x/net v0.38.0 // indirect
|
||||||
golang.org/x/sys v0.30.0 // indirect
|
golang.org/x/sys v0.31.0 // indirect
|
||||||
golang.org/x/term v0.29.0 // indirect
|
golang.org/x/term v0.30.0 // indirect
|
||||||
golang.org/x/text v0.22.0 // indirect
|
golang.org/x/text v0.23.0 // indirect
|
||||||
)
|
)
|
||||||
|
24
go.sum
24
go.sum
@@ -4,8 +4,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
|
|||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/jedib0t/go-pretty/v6 v6.6.7 h1:m+LbHpm0aIAPLzLbMfn8dc3Ht8MW7lsSO4MPItz/Uuo=
|
github.com/jedib0t/go-pretty/v6 v6.6.7 h1:m+LbHpm0aIAPLzLbMfn8dc3Ht8MW7lsSO4MPItz/Uuo=
|
||||||
github.com/jedib0t/go-pretty/v6 v6.6.7/go.mod h1:YwC5CE4fJ1HFUDeivSV1r//AmANFHyqczZk+U6BDALU=
|
github.com/jedib0t/go-pretty/v6 v6.6.7/go.mod h1:YwC5CE4fJ1HFUDeivSV1r//AmANFHyqczZk+U6BDALU=
|
||||||
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
|
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
||||||
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
|
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
|
||||||
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||||
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
@@ -17,18 +17,18 @@ github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOf
|
|||||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||||
github.com/valyala/fasthttp v1.59.0 h1:Qu0qYHfXvPk1mSLNqcFtEk6DpxgA26hy6bmydotDpRI=
|
github.com/valyala/fasthttp v1.60.0 h1:kBRYS0lOhVJ6V+bYN8PqAHELKHtXqwq9zNMLKx1MBsw=
|
||||||
github.com/valyala/fasthttp v1.59.0/go.mod h1:GTxNb9Bc6r2a9D0TWNSPwDz78UxnTGBViY3xZNEqyYU=
|
github.com/valyala/fasthttp v1.60.0/go.mod h1:iY4kDgV3Gc6EqhRZ8icqcmlG6bqhcDXfuHgTO4FXCvc=
|
||||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||||
golang.org/x/net v0.36.0 h1:vWF2fRbw4qslQsQzgFqZff+BItCvGFQqKzKIzx1rmoA=
|
golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
|
||||||
golang.org/x/net v0.36.0/go.mod h1:bFmbeoIPfrw4sMHNhb4J9f6+tPziuGjq7Jk/38fxi1I=
|
golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
|
||||||
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
|
||||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||||
golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU=
|
golang.org/x/term v0.30.0 h1:PQ39fJZ+mfadBm0y5WlL4vlM7Sx1Hgf13sMIY2+QS9Y=
|
||||||
golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s=
|
golang.org/x/term v0.30.0/go.mod h1:NYYFdzHoI5wRh/h5tDMdMqCqPJZEuNqVR5xJLd/n67g=
|
||||||
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
|
golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
|
||||||
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
|
golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
@@ -72,11 +72,12 @@ func getClients(
|
|||||||
func getDialFunc(proxy *url.URL, timeout time.Duration) (fasthttp.DialFunc, error) {
|
func getDialFunc(proxy *url.URL, timeout time.Duration) (fasthttp.DialFunc, error) {
|
||||||
var dialer fasthttp.DialFunc
|
var dialer fasthttp.DialFunc
|
||||||
|
|
||||||
if proxy.Scheme == "socks5" || proxy.Scheme == "socks5h" {
|
switch proxy.Scheme {
|
||||||
|
case "socks5", "socks5h":
|
||||||
dialer = fasthttpproxy.FasthttpSocksDialerDualStack(proxy.String())
|
dialer = fasthttpproxy.FasthttpSocksDialerDualStack(proxy.String())
|
||||||
} else if proxy.Scheme == "http" {
|
case "http":
|
||||||
dialer = fasthttpproxy.FasthttpHTTPDialerDualStackTimeout(proxy.String(), timeout)
|
dialer = fasthttpproxy.FasthttpHTTPDialerDualStackTimeout(proxy.String(), timeout)
|
||||||
} else {
|
default:
|
||||||
return nil, errors.New("unsupported proxy scheme")
|
return nil, errors.New("unsupported proxy scheme")
|
||||||
}
|
}
|
||||||
return dialer, nil
|
return dialer, nil
|
||||||
|
@@ -17,7 +17,7 @@ import (
|
|||||||
func streamProgress(
|
func streamProgress(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
wg *sync.WaitGroup,
|
wg *sync.WaitGroup,
|
||||||
total int64,
|
total uint,
|
||||||
message string,
|
message string,
|
||||||
increase <-chan int64,
|
increase <-chan int64,
|
||||||
) {
|
) {
|
||||||
@@ -27,21 +27,26 @@ func streamProgress(
|
|||||||
pw.SetStyle(progress.StyleBlocks)
|
pw.SetStyle(progress.StyleBlocks)
|
||||||
pw.SetTrackerLength(40)
|
pw.SetTrackerLength(40)
|
||||||
pw.SetUpdateFrequency(time.Millisecond * 250)
|
pw.SetUpdateFrequency(time.Millisecond * 250)
|
||||||
|
if total == 0 {
|
||||||
|
pw.Style().Visibility.Percentage = false
|
||||||
|
}
|
||||||
go pw.Render()
|
go pw.Render()
|
||||||
dodosTracker := progress.Tracker{
|
dodosTracker := progress.Tracker{
|
||||||
Message: message,
|
Message: message,
|
||||||
Total: total,
|
Total: int64(total),
|
||||||
}
|
}
|
||||||
pw.AppendTracker(&dodosTracker)
|
pw.AppendTracker(&dodosTracker)
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
if ctx.Err() != context.Canceled {
|
if err := ctx.Err(); err == context.Canceled || err == context.DeadlineExceeded {
|
||||||
|
dodosTracker.MarkAsDone()
|
||||||
|
} else {
|
||||||
dodosTracker.MarkAsErrored()
|
dodosTracker.MarkAsErrored()
|
||||||
}
|
}
|
||||||
|
time.Sleep(time.Millisecond * 300)
|
||||||
fmt.Printf("\r")
|
fmt.Printf("\r")
|
||||||
time.Sleep(time.Millisecond * 500)
|
|
||||||
pw.Stop()
|
|
||||||
return
|
return
|
||||||
|
|
||||||
case value := <-increase:
|
case value := <-increase:
|
||||||
|
@@ -166,9 +166,6 @@ func setRequestHeaders(req *fasthttp.Request, headers []types.KeyValue[string, s
|
|||||||
for _, header := range headers {
|
for _, header := range headers {
|
||||||
req.Header.Add(header.Key, header.Value)
|
req.Header.Add(header.Key, header.Value)
|
||||||
}
|
}
|
||||||
if req.Header.UserAgent() == nil {
|
|
||||||
req.Header.SetUserAgent(config.DefaultUserAgent)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// setRequestCookies adds the cookies of the given request with the provided key-value pairs.
|
// setRequestCookies adds the cookies of the given request with the provided key-value pairs.
|
||||||
|
@@ -20,6 +20,9 @@ import (
|
|||||||
// - ctx: The context for managing request lifecycle and cancellation.
|
// - ctx: The context for managing request lifecycle and cancellation.
|
||||||
// - requestConfig: The configuration for the request, including timeout, proxies, and other settings.
|
// - requestConfig: The configuration for the request, including timeout, proxies, and other settings.
|
||||||
func Run(ctx context.Context, requestConfig *config.RequestConfig) (Responses, error) {
|
func Run(ctx context.Context, requestConfig *config.RequestConfig) (Responses, error) {
|
||||||
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
clients := getClients(
|
clients := getClients(
|
||||||
ctx,
|
ctx,
|
||||||
requestConfig.Timeout,
|
requestConfig.Timeout,
|
||||||
@@ -31,6 +34,10 @@ func Run(ctx context.Context, requestConfig *config.RequestConfig) (Responses, e
|
|||||||
return nil, types.ErrInterrupt
|
return nil, types.ErrInterrupt
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if requestConfig.Duration > 0 {
|
||||||
|
time.AfterFunc(requestConfig.Duration, func() { cancel() })
|
||||||
|
}
|
||||||
|
|
||||||
responses := releaseDodos(ctx, requestConfig, clients)
|
responses := releaseDodos(ctx, requestConfig, clients)
|
||||||
if ctx.Err() != nil && len(responses) == 0 {
|
if ctx.Err() != nil && len(responses) == 0 {
|
||||||
return nil, types.ErrInterrupt
|
return nil, types.ErrInterrupt
|
||||||
@@ -58,18 +65,29 @@ func releaseDodos(
|
|||||||
wg sync.WaitGroup
|
wg sync.WaitGroup
|
||||||
streamWG sync.WaitGroup
|
streamWG sync.WaitGroup
|
||||||
requestCountPerDodo uint
|
requestCountPerDodo uint
|
||||||
dodosCount uint = requestConfig.GetValidDodosCountForRequests()
|
dodosCount = requestConfig.GetValidDodosCountForRequests()
|
||||||
dodosCountInt int = int(dodosCount)
|
|
||||||
responses = make([][]*Response, dodosCount)
|
responses = make([][]*Response, dodosCount)
|
||||||
increase = make(chan int64, requestConfig.RequestCount)
|
increase = make(chan int64, requestConfig.RequestCount)
|
||||||
)
|
)
|
||||||
|
|
||||||
wg.Add(dodosCountInt)
|
wg.Add(int(dodosCount))
|
||||||
streamWG.Add(1)
|
streamWG.Add(1)
|
||||||
streamCtx, streamCtxCancel := context.WithCancel(context.Background())
|
streamCtx, streamCtxCancel := context.WithCancel(context.Background())
|
||||||
|
|
||||||
go streamProgress(streamCtx, &streamWG, int64(requestConfig.RequestCount), "Dodos Working🔥", increase)
|
go streamProgress(streamCtx, &streamWG, requestConfig.RequestCount, "Dodos Working🔥", increase)
|
||||||
|
|
||||||
|
if requestConfig.RequestCount == 0 {
|
||||||
|
for i := range dodosCount {
|
||||||
|
go sendRequest(
|
||||||
|
ctx,
|
||||||
|
newRequest(*requestConfig, clients, int64(i)),
|
||||||
|
requestConfig.Timeout,
|
||||||
|
&responses[i],
|
||||||
|
increase,
|
||||||
|
&wg,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
for i := range dodosCount {
|
for i := range dodosCount {
|
||||||
if i+1 == dodosCount {
|
if i+1 == dodosCount {
|
||||||
requestCountPerDodo = requestConfig.RequestCount - (i * requestConfig.RequestCount / dodosCount)
|
requestCountPerDodo = requestConfig.RequestCount - (i * requestConfig.RequestCount / dodosCount)
|
||||||
@@ -78,7 +96,7 @@ func releaseDodos(
|
|||||||
(i * requestConfig.RequestCount / dodosCount)
|
(i * requestConfig.RequestCount / dodosCount)
|
||||||
}
|
}
|
||||||
|
|
||||||
go sendRequest(
|
go sendRequestByCount(
|
||||||
ctx,
|
ctx,
|
||||||
newRequest(*requestConfig, clients, int64(i)),
|
newRequest(*requestConfig, clients, int64(i)),
|
||||||
requestConfig.Timeout,
|
requestConfig.Timeout,
|
||||||
@@ -88,17 +106,19 @@ func releaseDodos(
|
|||||||
&wg,
|
&wg,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
streamCtxCancel()
|
streamCtxCancel()
|
||||||
streamWG.Wait()
|
streamWG.Wait()
|
||||||
return utils.Flatten(responses)
|
return utils.Flatten(responses)
|
||||||
}
|
}
|
||||||
|
|
||||||
// sendRequest sends a specified number of HTTP requests concurrently with a given timeout.
|
// sendRequestByCount sends a specified number of HTTP requests concurrently with a given timeout.
|
||||||
// It appends the responses to the provided responseData slice and sends the count of completed requests
|
// It appends the responses to the provided responseData slice and sends the count of completed requests
|
||||||
// to the increase channel. The function terminates early if the context is canceled or if a custom
|
// to the increase channel. The function terminates early if the context is canceled or if a custom
|
||||||
// interrupt error is encountered.
|
// interrupt error is encountered.
|
||||||
func sendRequest(
|
func sendRequestByCount(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
request *Request,
|
request *Request,
|
||||||
timeout time.Duration,
|
timeout time.Duration,
|
||||||
@@ -142,3 +162,50 @@ func sendRequest(
|
|||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// sendRequest continuously sends HTTP requests until the context is canceled.
|
||||||
|
// It records the response status code or error message along with the response time,
|
||||||
|
// and signals each completed request through the increase channel.
|
||||||
|
func sendRequest(
|
||||||
|
ctx context.Context,
|
||||||
|
request *Request,
|
||||||
|
timeout time.Duration,
|
||||||
|
responseData *[]*Response,
|
||||||
|
increase chan<- int64,
|
||||||
|
wg *sync.WaitGroup,
|
||||||
|
) {
|
||||||
|
defer wg.Done()
|
||||||
|
|
||||||
|
for {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func() {
|
||||||
|
startTime := time.Now()
|
||||||
|
response, err := request.Send(ctx, timeout)
|
||||||
|
completedTime := time.Since(startTime)
|
||||||
|
if response != nil {
|
||||||
|
defer fasthttp.ReleaseResponse(response)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
if err == types.ErrInterrupt {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
*responseData = append(*responseData, &Response{
|
||||||
|
Response: err.Error(),
|
||||||
|
Time: completedTime,
|
||||||
|
})
|
||||||
|
increase <- 1
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
*responseData = append(*responseData, &Response{
|
||||||
|
Response: strconv.Itoa(response.StatusCode()),
|
||||||
|
Time: completedTime,
|
||||||
|
})
|
||||||
|
increase <- 1
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@@ -13,12 +13,12 @@ type Body []string
|
|||||||
func (body Body) String() string {
|
func (body Body) String() string {
|
||||||
var buffer bytes.Buffer
|
var buffer bytes.Buffer
|
||||||
if len(body) == 0 {
|
if len(body) == 0 {
|
||||||
return string(buffer.Bytes())
|
return buffer.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(body) == 1 {
|
if len(body) == 1 {
|
||||||
buffer.WriteString(body[0])
|
buffer.WriteString(body[0])
|
||||||
return string(buffer.Bytes())
|
return buffer.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
buffer.WriteString(text.FgBlue.Sprint("Random") + "[\n")
|
buffer.WriteString(text.FgBlue.Sprint("Random") + "[\n")
|
||||||
@@ -41,7 +41,7 @@ func (body Body) String() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
buffer.WriteString("\n]")
|
buffer.WriteString("\n]")
|
||||||
return string(buffer.Bytes())
|
return buffer.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (body *Body) UnmarshalJSON(b []byte) error {
|
func (body *Body) UnmarshalJSON(b []byte) error {
|
||||||
|
@@ -14,7 +14,7 @@ type Cookies []KeyValue[string, []string]
|
|||||||
func (cookies Cookies) String() string {
|
func (cookies Cookies) String() string {
|
||||||
var buffer bytes.Buffer
|
var buffer bytes.Buffer
|
||||||
if len(cookies) == 0 {
|
if len(cookies) == 0 {
|
||||||
return string(buffer.Bytes())
|
return buffer.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
indent := " "
|
indent := " "
|
||||||
@@ -53,7 +53,7 @@ func (cookies Cookies) String() string {
|
|||||||
buffer.WriteString(",\n" + text.FgGreen.Sprintf("+%d cookies", remainingPairs))
|
buffer.WriteString(",\n" + text.FgGreen.Sprintf("+%d cookies", remainingPairs))
|
||||||
}
|
}
|
||||||
|
|
||||||
return string(buffer.Bytes())
|
return buffer.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cookies *Cookies) AppendByKey(key, value string) {
|
func (cookies *Cookies) AppendByKey(key, value string) {
|
||||||
|
@@ -6,52 +6,52 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Timeout struct {
|
type Duration struct {
|
||||||
time.Duration
|
time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
func (timeout *Timeout) UnmarshalJSON(b []byte) error {
|
func (duration *Duration) UnmarshalJSON(b []byte) error {
|
||||||
var v any
|
var v any
|
||||||
if err := json.Unmarshal(b, &v); err != nil {
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
switch value := v.(type) {
|
switch value := v.(type) {
|
||||||
case float64:
|
case float64:
|
||||||
timeout.Duration = time.Duration(value)
|
duration.Duration = time.Duration(value)
|
||||||
return nil
|
return nil
|
||||||
case string:
|
case string:
|
||||||
var err error
|
var err error
|
||||||
timeout.Duration, err = time.ParseDuration(value)
|
duration.Duration, err = time.ParseDuration(value)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)")
|
return errors.New("Duration is invalid (e.g. 400ms, 1s, 5m, 1h)")
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
default:
|
default:
|
||||||
return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)")
|
return errors.New("Duration is invalid (e.g. 400ms, 1s, 5m, 1h)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (timeout Timeout) MarshalJSON() ([]byte, error) {
|
func (duration Duration) MarshalJSON() ([]byte, error) {
|
||||||
return json.Marshal(timeout.Duration.String())
|
return json.Marshal(duration.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (timeout *Timeout) UnmarshalYAML(unmarshal func(interface{}) error) error {
|
func (duration *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {
|
||||||
var v any
|
var v any
|
||||||
if err := unmarshal(&v); err != nil {
|
if err := unmarshal(&v); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
switch value := v.(type) {
|
switch value := v.(type) {
|
||||||
case float64:
|
case float64:
|
||||||
timeout.Duration = time.Duration(value)
|
duration.Duration = time.Duration(value)
|
||||||
return nil
|
return nil
|
||||||
case string:
|
case string:
|
||||||
var err error
|
var err error
|
||||||
timeout.Duration, err = time.ParseDuration(value)
|
duration.Duration, err = time.ParseDuration(value)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)")
|
return errors.New("Duration is invalid (e.g. 400ms, 1s, 5m, 1h)")
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
default:
|
default:
|
||||||
return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)")
|
return errors.New("Duration is invalid (e.g. 400ms, 1s, 5m, 1h)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -14,7 +14,7 @@ type Headers []KeyValue[string, []string]
|
|||||||
func (headers Headers) String() string {
|
func (headers Headers) String() string {
|
||||||
var buffer bytes.Buffer
|
var buffer bytes.Buffer
|
||||||
if len(headers) == 0 {
|
if len(headers) == 0 {
|
||||||
return string(buffer.Bytes())
|
return buffer.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
indent := " "
|
indent := " "
|
||||||
@@ -53,7 +53,7 @@ func (headers Headers) String() string {
|
|||||||
buffer.WriteString(",\n" + text.FgGreen.Sprintf("+%d headers", remainingPairs))
|
buffer.WriteString(",\n" + text.FgGreen.Sprintf("+%d headers", remainingPairs))
|
||||||
}
|
}
|
||||||
|
|
||||||
return string(buffer.Bytes())
|
return buffer.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (headers *Headers) AppendByKey(key, value string) {
|
func (headers *Headers) AppendByKey(key, value string) {
|
||||||
@@ -73,6 +73,15 @@ func (headers Headers) GetValue(key string) *[]string {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (headers Headers) Has(key string) bool {
|
||||||
|
for i := range headers {
|
||||||
|
if headers[i].Key == key {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
func (headers *Headers) UnmarshalJSON(b []byte) error {
|
func (headers *Headers) UnmarshalJSON(b []byte) error {
|
||||||
var data []map[string]any
|
var data []map[string]any
|
||||||
if err := json.Unmarshal(b, &data); err != nil {
|
if err := json.Unmarshal(b, &data); err != nil {
|
||||||
@@ -137,3 +146,11 @@ func (headers *Headers) Set(value string) error {
|
|||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (headers *Headers) SetIfNotExists(key string, value string) bool {
|
||||||
|
if headers.Has(key) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
*headers = append(*headers, KeyValue[string, []string]{Key: key, Value: []string{value}})
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
@@ -14,7 +14,7 @@ type Params []KeyValue[string, []string]
|
|||||||
func (params Params) String() string {
|
func (params Params) String() string {
|
||||||
var buffer bytes.Buffer
|
var buffer bytes.Buffer
|
||||||
if len(params) == 0 {
|
if len(params) == 0 {
|
||||||
return string(buffer.Bytes())
|
return buffer.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
indent := " "
|
indent := " "
|
||||||
@@ -53,7 +53,7 @@ func (params Params) String() string {
|
|||||||
buffer.WriteString(",\n" + text.FgGreen.Sprintf("+%d params", remainingPairs))
|
buffer.WriteString(",\n" + text.FgGreen.Sprintf("+%d params", remainingPairs))
|
||||||
}
|
}
|
||||||
|
|
||||||
return string(buffer.Bytes())
|
return buffer.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (params *Params) AppendByKey(key, value string) {
|
func (params *Params) AppendByKey(key, value string) {
|
||||||
|
@@ -14,12 +14,12 @@ type Proxies []url.URL
|
|||||||
func (proxies Proxies) String() string {
|
func (proxies Proxies) String() string {
|
||||||
var buffer bytes.Buffer
|
var buffer bytes.Buffer
|
||||||
if len(proxies) == 0 {
|
if len(proxies) == 0 {
|
||||||
return string(buffer.Bytes())
|
return buffer.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(proxies) == 1 {
|
if len(proxies) == 1 {
|
||||||
buffer.WriteString(proxies[0].String())
|
buffer.WriteString(proxies[0].String())
|
||||||
return string(buffer.Bytes())
|
return buffer.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
buffer.WriteString(text.FgBlue.Sprint("Random") + "[\n")
|
buffer.WriteString(text.FgBlue.Sprint("Random") + "[\n")
|
||||||
@@ -42,7 +42,7 @@ func (proxies Proxies) String() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
buffer.WriteString("\n]")
|
buffer.WriteString("\n]")
|
||||||
return string(buffer.Bytes())
|
return buffer.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (proxies *Proxies) UnmarshalJSON(b []byte) error {
|
func (proxies *Proxies) UnmarshalJSON(b []byte) error {
|
||||||
|
@@ -18,7 +18,7 @@ func (requestURL *RequestURL) UnmarshalJSON(data []byte) error {
|
|||||||
|
|
||||||
parsedURL, err := url.Parse(urlStr)
|
parsedURL, err := url.Parse(urlStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.New("Request URL is invalid")
|
return errors.New("request URL is invalid")
|
||||||
}
|
}
|
||||||
|
|
||||||
requestURL.URL = *parsedURL
|
requestURL.URL = *parsedURL
|
||||||
@@ -33,7 +33,7 @@ func (requestURL *RequestURL) UnmarshalYAML(unmarshal func(interface{}) error) e
|
|||||||
|
|
||||||
parsedURL, err := url.Parse(urlStr)
|
parsedURL, err := url.Parse(urlStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.New("Request URL is invalid")
|
return errors.New("request URL is invalid")
|
||||||
}
|
}
|
||||||
|
|
||||||
requestURL.URL = *parsedURL
|
requestURL.URL = *parsedURL
|
||||||
|
57
types/timeout.go
Normal file
57
types/timeout.go
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
package types
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Timeout struct {
|
||||||
|
time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func (timeout *Timeout) UnmarshalJSON(b []byte) error {
|
||||||
|
var v any
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
switch value := v.(type) {
|
||||||
|
case float64:
|
||||||
|
timeout.Duration = time.Duration(value)
|
||||||
|
return nil
|
||||||
|
case string:
|
||||||
|
var err error
|
||||||
|
timeout.Duration, err = time.ParseDuration(value)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
default:
|
||||||
|
return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (timeout Timeout) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(timeout.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (timeout *Timeout) UnmarshalYAML(unmarshal func(interface{}) error) error {
|
||||||
|
var v any
|
||||||
|
if err := unmarshal(&v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
switch value := v.(type) {
|
||||||
|
case float64:
|
||||||
|
timeout.Duration = time.Duration(value)
|
||||||
|
return nil
|
||||||
|
case string:
|
||||||
|
var err error
|
||||||
|
timeout.Duration, err = time.ParseDuration(value)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
default:
|
||||||
|
return errors.New("Timeout is invalid (e.g. 400ms, 1s, 5m, 1h)")
|
||||||
|
}
|
||||||
|
}
|
@@ -6,9 +6,5 @@ func IsNilOrZero[T comparable](value *T) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var zero T
|
var zero T
|
||||||
if *value == zero {
|
return *value == zero
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
@@ -20,9 +20,9 @@ func Flatten[T any](nested [][]*T) []*T {
|
|||||||
// The returned function isn't thread-safe and should be used in a single-threaded context.
|
// The returned function isn't thread-safe and should be used in a single-threaded context.
|
||||||
func RandomValueCycle[Value any](values []Value, localRand *rand.Rand) func() Value {
|
func RandomValueCycle[Value any](values []Value, localRand *rand.Rand) func() Value {
|
||||||
var (
|
var (
|
||||||
clientsCount int = len(values)
|
clientsCount = len(values)
|
||||||
currentIndex int = localRand.Intn(clientsCount)
|
currentIndex = localRand.Intn(clientsCount)
|
||||||
stopIndex int = currentIndex
|
stopIndex = currentIndex
|
||||||
)
|
)
|
||||||
|
|
||||||
return func() Value {
|
return func() Value {
|
||||||
|
Reference in New Issue
Block a user