Skip to content

Добавил возможность матчить body реквеста по регулярке #9

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions Development/Source/Core/NetworkStubRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,20 +35,24 @@ public struct NetworkStubRequest: HttpRequestProtocol, Equatable {
/// Заголовки запроса.
/// Headers
public let headersDictionary: [String: String]

public var regexPatternBody: String?

public init(url: String,
query: [String: String] = [:],
excludedQuery: [String: String?] = [:],
httpMethod: NetworkStubMethod = .ANY,
bodyJson: JSON? = nil,
headersDictionary: [String: String] = [:]) {
headersDictionary: [String: String] = [:],
regexPatternBody: String? = nil) {

self.url = url
self.query = query
self.excludedQuery = excludedQuery
self.httpMethod = httpMethod
self.bodyJson = bodyJson
self.headersDictionary = headersDictionary
self.regexPatternBody = regexPatternBody
}
}

Expand Down Expand Up @@ -92,6 +96,16 @@ public extension NetworkStubRequest {
}
}
}()

let isBodyMatchedRegex: Bool = {
guard let regexPatternBody = regexPatternBody,
let requestBodyJson = request.bodyJson,
let requestBodyString = requestBodyJson.rawString() else {
return true
}

return doesMatchRegex(regexPattern: regexPatternBody, inputString: requestBodyString)
}()

var isExcludedQueryContained = false
excludedQuery.forEach { argKey, argValue in
Expand All @@ -107,7 +121,7 @@ public extension NetworkStubRequest {
}

return isQueryMatched && isHeadersDictionaryMatched &&
isBodyMatched && !isExcludedQueryContained
isBodyMatched && !isExcludedQueryContained && isBodyMatchedRegex
}
}

Expand All @@ -127,4 +141,15 @@ private extension NetworkStubRequest {
}
return nil
}

func doesMatchRegex(regexPattern: String, inputString: String) -> Bool {
do {
let regex = try NSRegularExpression(pattern: regexPattern)
let range = NSRange(inputString.startIndex..., in: inputString)
return regex.firstMatch(in: inputString, options: [], range: range) != nil
} catch {
print("Ошибка при создании регулярного выражения: \(error.localizedDescription)")
return false
}
}
}