Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated autogenerated mocks. #378

Merged
merged 1 commit into from
Aug 27, 2020
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion Source/CharacteristicNotificationManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class CharacteristicNotificationManager {

private func setNotifyValue(_ enabled: Bool, for characteristic: Characteristic) {
guard peripheral.state == .connected else {
RxBluetoothKitLog.w("\(peripheral.logDescription) is not connected." +
RxBluetoothKitLog.w("\(String(describing: peripheral.logDescription)) is not connected." +
" Changing notification state for not connected peripheral is not possible.")
return
}
Expand Down
72 changes: 64 additions & 8 deletions Templates/Mock.swifttemplate
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,42 @@ import RxSwift
let formattedName: String
let lastParamName: String?
}

struct Availability {
let iOS: String?
let macOS: String?
let watchOS: String?
let tvOS: String?

var description: String {
var constraints = [String]()
if let iOSVersion = iOS { constraints.append("iOS \(iOSVersion)") }
if let macOSVersion = macOS { constraints.append("macOS \(macOSVersion)") }
if let watchOSVersion = watchOS { constraints.append("watchOS \(watchOSVersion)") }
if let tvOSVersion = tvOS { constraints.append("tvOS \(tvOSVersion)") }
let value = "@available(\(constraints.joined(separator: ", ")), *)"
return value
}
}

struct MethodDefinition: Equatable {
let selectorName: String
let definedInTypeName: String
}

typealias MethodName = String

class Utils {
static let classNamesToMock = ["CBManager", "CBAttribute", "CBCentralManager", "CBPeripheralManager", "CBPeripheral", "CBDescriptor", "CBService", "CBCharacteristic", "CBL2CAPChannel", "CBPeer", "CBATTRequest", "CBCentral", "PeripheralProvider", "Connector", "CharacteristicNotificationManager"]
static let classNamesToTestable = ["Peripheral", "CentralManager", "PeripheralManager", "Characteristic"]
static let delegateWrapperNamesToMock = ["CBPeripheralDelegateWrapper", "CBCentralManagerDelegateWrapper", "CBPeripheralManagerDelegateWrapper"]
static let namesToMock = classNamesToMock + delegateWrapperNamesToMock
static let restrictedTypes: [String: Availability] = [
"CBManagerAuthorization": Availability(iOS: "13.0", macOS: "10.15", watchOS: "6.0", tvOS: "13.0")
]
static let unavailableOnMac: [MethodDefinition] = [
MethodDefinition(selectorName: "centralManager(_:didUpdateANCSAuthorizationFor:)", definedInTypeName: "CBCentralManagerDelegateWrapper")
]

static func capitalizeFirstLetter(_ text: String) -> String {
return text.prefix(1).uppercased() + text.dropFirst()
Expand Down Expand Up @@ -74,20 +103,22 @@ import RxSwift

static func printVariable(_ variable: Variable, useDefaultValue: Bool = false) -> String {
let forceUnwrap = variable.isOptional ? "" : "!"
let avaibilityString = restrictedTypes[variable.typeName.name]?.description.appending(" lazy ") ?? ""
let initialization = restrictedTypes[variable.typeName.name] != nil ? " = nil" : ""
if let defaultValue = variable.defaultValue, useDefaultValue {
let changedDefaultValue = changeTypeName(defaultValue)
return "var \(variable.name) = \(changedDefaultValue)"
return "\(avaibilityString)var \(variable.name) = \(changedDefaultValue)"
} else {
let changedTypeName = changeTypeName(variable.typeName.name)
return "var \(variable.name): \(changedTypeName)\(forceUnwrap)"
return "\(avaibilityString)var \(variable.name): \(changedTypeName)\(forceUnwrap)\(initialization)"
}
}

static func printMethodParamTypes(_ method: SourceryRuntime.Method) -> String {
return String(method.parameters.reduce("", { "\($0)\(changeTypeName($1.typeName.name)), " }).dropLast(2))
}

static func printMethodName(_ method: SourceryRuntime.Method, changeTypeNames: Bool = true) -> String {
static func printMethodName(_ method: SourceryRuntime.Method, changeTypeNames: Bool = true) -> String {
var methodParams = method.parameters.reduce("", { value, parameter in
var labelPart = ""
if (value.count == 0 && parameter.argumentLabel == nil) {
Expand All @@ -101,6 +132,15 @@ import RxSwift
}).dropLast(2)
return "\(method.callName)(\(methodParams))"
}

static func removeDuplicatesVariables(_ variables: [SourceryRuntime.Variable]) -> [SourceryRuntime.Variable] {
var filteredVariables = [SourceryRuntime.Variable]()
for variable in variables {
guard !filteredVariables.contains(where: { $0.name == variable.name }) else { continue }
filteredVariables.append(variable)
}
return filteredVariables
}
}
-%>

Expand All @@ -110,7 +150,10 @@ import RxSwift
let typeToMock = type[classNameToMock]!
let supertypeName = Utils.changeTypeName(typeToMock.supertype?.name ?? "NSObject") -%>
class <%= typeToMock.name %>Mock: <%= supertypeName %> {
<%_ for variable in typeToMock.variables { -%>
<%_ for containedType in typeToMock.containedTypes { -%>
class <%= containedType.localName %> {}
<% } -%>
<%_ for variable in Utils.removeDuplicatesVariables(typeToMock.variables) { -%>
<%= Utils.printVariable(variable) %>
<% } -%>

Expand Down Expand Up @@ -169,12 +212,25 @@ class <%= typeToMock.name %>Mock: NSObject <%= inheritedTypes %> {

override init() {
}

<%_ let filteredMethods = typeToMock.methods.filter { !$0.isInitializer }
for method in filteredMethods { -%>
<%_ let filteredMethods = typeToMock.methods
.filter { !$0.isInitializer }

for method in filteredMethods {
var isUnavailableOnMac = false
if let inTypeName = method.definedInTypeName?.name {
isUnavailableOnMac = !Utils.unavailableOnMac.contains(where: {
return !($0.selectorName == method.selectorName && $0.definedInTypeName == inTypeName)
})
} -%>

<%_ if isUnavailableOnMac { -%>
#if !os(macOS)
<%_ } -%>
func <%= Utils.printMethodName(method, changeTypeNames: false) %> {
}

<%_ if isUnavailableOnMac { -%>
#endif
<%_ } -%>
<%_ } -%>
}
<%_ } -%>
25 changes: 21 additions & 4 deletions Tests/Autogenerated/Mock.generated.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Generated using Sourcery 0.16.0 — https://github.com/krzysztofzablocki/Sourcery
// Generated using Sourcery 1.0.0 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT

import CoreBluetooth
Expand All @@ -10,6 +10,7 @@ import RxSwift

class CBManagerMock: NSObject {
var state: CBManagerState!
@available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, *) lazy var authorization: CBManagerAuthorization! = nil

override init() {
}
Expand All @@ -23,6 +24,7 @@ class CBAttributeMock: NSObject {

}
class CBCentralManagerMock: CBManagerMock {
class Feature {}
var delegate: CBCentralManagerDelegate?
var isScanning: Bool!
var logDescription: String!
Expand All @@ -34,6 +36,18 @@ class CBCentralManagerMock: CBManagerMock {
init(delegate: CBCentralManagerDelegate?, queue: DispatchQueue?) {
}

static var supportsParams: [(CBCentralManagerMock.Feature)] = []
static var supportsReturns: [Bool] = []
static var supportsReturn: Bool?
static func supports(_ features: CBCentralManagerMock.Feature) -> Bool {
supportsParams.append((features))
if supportsReturns.isEmpty {
return supportsReturn!
} else {
return supportsReturns.removeFirst()
}
}

var retrievePeripheralsParams: [([UUID])] = []
var retrievePeripheralsReturns: [[CBPeripheralMock]] = []
var retrievePeripheralsReturn: [CBPeripheralMock]?
Expand Down Expand Up @@ -78,6 +92,11 @@ class CBCentralManagerMock: CBManagerMock {
cancelPeripheralConnectionParams.append((peripheral))
}

var registerForConnectionEventsParams: [([CBConnectionEventMatchingOption : Any]?)] = []
func registerForConnectionEvents(options: [CBConnectionEventMatchingOption : Any]? = nil) {
registerForConnectionEventsParams.append((options))
}

}
class CBPeripheralManagerMock: CBManagerMock {
var delegate: CBPeripheralManagerDelegate?
Expand Down Expand Up @@ -168,6 +187,7 @@ class CBPeripheralMock: CBPeerMock {
var state: CBPeripheralState!
var services: [CBServiceMock]?
var canSendWriteWithoutResponse: Bool!
var ancsAuthorized: Bool!
var logDescription: String!
var uuidIdentifier: UUID!

Expand Down Expand Up @@ -546,7 +566,6 @@ class CBPeripheralDelegateWrapperMock: NSObject , CBPeripheralDelegate {

func peripheral(_ peripheral: CBPeripheral, didOpen channel: CBL2CAPChannel?, error: Error?) {
}

}
class CBCentralManagerDelegateWrapperMock: NSObject , CBCentralManagerDelegate {
var didUpdateState = PublishSubject<BluetoothState>()
Expand Down Expand Up @@ -576,7 +595,6 @@ class CBCentralManagerDelegateWrapperMock: NSObject , CBCentralManagerDelegate {

func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
}

}
class CBPeripheralManagerDelegateWrapperMock: NSObject , CBPeripheralManagerDelegate {
var didUpdateState = PublishSubject<BluetoothState>()
Expand Down Expand Up @@ -631,5 +649,4 @@ class CBPeripheralManagerDelegateWrapperMock: NSObject , CBPeripheralManagerDele

func peripheralManager(_ peripheral: CBPeripheralManager, didOpen channel: CBL2CAPChannel?, error: Error?) {
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ class _CharacteristicNotificationManager {

private func setNotifyValue(_ enabled: Bool, for characteristic: _Characteristic) {
guard peripheral.state == .connected else {
RxBluetoothKitLog.w("\(peripheral.logDescription) is not connected." +
RxBluetoothKitLog.w("\(String(describing: peripheral.logDescription)) is not connected." +
" Changing notification state for not connected peripheral is not possible.")
return
}
Expand Down