| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567 |
- /*
- * Copyright 2024, gRPC Authors All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- #if os(macOS) || os(Linux) // swift-format doesn't like canImport(Foundation.Process)
- import GRPCCodeGen
- import GRPCProtobufCodeGen
- import SwiftProtobuf
- import SwiftProtobufPluginLibrary
- import XCTest
- final class ProtobufCodeGeneratorTests: XCTestCase {
- func testProtobufCodeGenerator() throws {
- try testCodeGeneration(
- proto: Google_Protobuf_FileDescriptorProto.helloWorldNestedPackage,
- indentation: 4,
- visibility: .internal,
- client: true,
- server: false,
- expectedCode: """
- // Copyright 2015 gRPC authors.
- //
- // Licensed under the Apache License, Version 2.0 (the "License");
- // you may not use this file except in compliance with the License.
- // You may obtain a copy of the License at
- //
- // http://www.apache.org/licenses/LICENSE-2.0
- //
- // Unless required by applicable law or agreed to in writing, software
- // distributed under the License is distributed on an "AS IS" BASIS,
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- // See the License for the specific language governing permissions and
- // limitations under the License.
- // DO NOT EDIT.
- // swift-format-ignore-file
- //
- // Generated by the gRPC Swift generator plugin for the protocol buffer compiler.
- // Source: helloworld.proto
- //
- // For information on using the generated types, please see the documentation:
- // https://github.com/grpc/grpc-swift
- internal import GRPCCore
- internal import GRPCProtobuf
- internal import DifferentModule
- internal import ExtraModule
- internal enum Hello_World_Greeter {
- internal static let descriptor = GRPCCore.ServiceDescriptor.hello_world_Greeter
- internal enum Method {
- internal enum SayHello {
- internal typealias Input = Hello_World_HelloRequest
- internal typealias Output = Hello_World_HelloReply
- internal static let descriptor = GRPCCore.MethodDescriptor(
- service: Hello_World_Greeter.descriptor.fullyQualifiedService,
- method: "SayHello"
- )
- }
- internal static let descriptors: [GRPCCore.MethodDescriptor] = [
- SayHello.descriptor
- ]
- }
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- internal typealias ClientProtocol = Hello_World_GreeterClientProtocol
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- internal typealias Client = Hello_World_GreeterClient
- }
- extension GRPCCore.ServiceDescriptor {
- internal static let hello_world_Greeter = Self(
- package: "hello.world",
- service: "Greeter"
- )
- }
- /// The greeting service definition.
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- internal protocol Hello_World_GreeterClientProtocol: Sendable {
- /// Sends a greeting.
- func sayHello<R>(
- request: GRPCCore.ClientRequest.Single<Hello_World_HelloRequest>,
- serializer: some GRPCCore.MessageSerializer<Hello_World_HelloRequest>,
- deserializer: some GRPCCore.MessageDeserializer<Hello_World_HelloReply>,
- options: GRPCCore.CallOptions,
- _ body: @Sendable @escaping (GRPCCore.ClientResponse.Single<Hello_World_HelloReply>) async throws -> R
- ) async throws -> R where R: Sendable
- }
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- extension Hello_World_Greeter.ClientProtocol {
- internal func sayHello<R>(
- request: GRPCCore.ClientRequest.Single<Hello_World_HelloRequest>,
- options: GRPCCore.CallOptions = .defaults,
- _ body: @Sendable @escaping (GRPCCore.ClientResponse.Single<Hello_World_HelloReply>) async throws -> R = {
- try $0.message
- }
- ) async throws -> R where R: Sendable {
- try await self.sayHello(
- request: request,
- serializer: GRPCProtobuf.ProtobufSerializer<Hello_World_HelloRequest>(),
- deserializer: GRPCProtobuf.ProtobufDeserializer<Hello_World_HelloReply>(),
- options: options,
- body
- )
- }
- }
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- extension Hello_World_Greeter.ClientProtocol {
- /// Sends a greeting.
- internal func sayHello<Result>(
- _ message: Hello_World_HelloRequest,
- metadata: GRPCCore.Metadata = [:],
- options: GRPCCore.CallOptions = .defaults,
- onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse.Single<Hello_World_HelloReply>) async throws -> Result = {
- try $0.message
- }
- ) async throws -> Result where Result: Sendable {
- let request = GRPCCore.ClientRequest.Single<Hello_World_HelloRequest>(
- message: message,
- metadata: metadata
- )
- return try await self.sayHello(
- request: request,
- options: options,
- handleResponse
- )
- }
- }
- /// The greeting service definition.
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- internal struct Hello_World_GreeterClient: Hello_World_Greeter.ClientProtocol {
- private let client: GRPCCore.GRPCClient
-
- internal init(wrapping client: GRPCCore.GRPCClient) {
- self.client = client
- }
-
- /// Sends a greeting.
- internal func sayHello<R>(
- request: GRPCCore.ClientRequest.Single<Hello_World_HelloRequest>,
- serializer: some GRPCCore.MessageSerializer<Hello_World_HelloRequest>,
- deserializer: some GRPCCore.MessageDeserializer<Hello_World_HelloReply>,
- options: GRPCCore.CallOptions = .defaults,
- _ body: @Sendable @escaping (GRPCCore.ClientResponse.Single<Hello_World_HelloReply>) async throws -> R = {
- try $0.message
- }
- ) async throws -> R where R: Sendable {
- try await self.client.unary(
- request: request,
- descriptor: Hello_World_Greeter.Method.SayHello.descriptor,
- serializer: serializer,
- deserializer: deserializer,
- options: options,
- handler: body
- )
- }
- }
- """
- )
- try testCodeGeneration(
- proto: Google_Protobuf_FileDescriptorProto.helloWorld,
- indentation: 2,
- visibility: .public,
- client: false,
- server: true,
- expectedCode: """
- // Copyright 2015 gRPC authors.
- //
- // Licensed under the Apache License, Version 2.0 (the "License");
- // you may not use this file except in compliance with the License.
- // You may obtain a copy of the License at
- //
- // http://www.apache.org/licenses/LICENSE-2.0
- //
- // Unless required by applicable law or agreed to in writing, software
- // distributed under the License is distributed on an "AS IS" BASIS,
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- // See the License for the specific language governing permissions and
- // limitations under the License.
- // DO NOT EDIT.
- // swift-format-ignore-file
- //
- // Generated by the gRPC Swift generator plugin for the protocol buffer compiler.
- // Source: helloworld.proto
- //
- // For information on using the generated types, please see the documentation:
- // https://github.com/grpc/grpc-swift
- public import GRPCCore
- internal import GRPCProtobuf
- public import DifferentModule
- public import ExtraModule
- public enum Helloworld_Greeter {
- public static let descriptor = GRPCCore.ServiceDescriptor.helloworld_Greeter
- public enum Method {
- public enum SayHello {
- public typealias Input = Helloworld_HelloRequest
- public typealias Output = Helloworld_HelloReply
- public static let descriptor = GRPCCore.MethodDescriptor(
- service: Helloworld_Greeter.descriptor.fullyQualifiedService,
- method: "SayHello"
- )
- }
- public static let descriptors: [GRPCCore.MethodDescriptor] = [
- SayHello.descriptor
- ]
- }
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- public typealias StreamingServiceProtocol = Helloworld_GreeterStreamingServiceProtocol
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- public typealias ServiceProtocol = Helloworld_GreeterServiceProtocol
- }
- extension GRPCCore.ServiceDescriptor {
- public static let helloworld_Greeter = Self(
- package: "helloworld",
- service: "Greeter"
- )
- }
- /// The greeting service definition.
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- public protocol Helloworld_GreeterStreamingServiceProtocol: GRPCCore.RegistrableRPCService {
- /// Sends a greeting.
- func sayHello(request: GRPCCore.ServerRequest.Stream<Helloworld_HelloRequest>) async throws -> GRPCCore.ServerResponse.Stream<Helloworld_HelloReply>
- }
- /// Conformance to `GRPCCore.RegistrableRPCService`.
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- extension Helloworld_Greeter.StreamingServiceProtocol {
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- public func registerMethods(with router: inout GRPCCore.RPCRouter) {
- router.registerHandler(
- forMethod: Helloworld_Greeter.Method.SayHello.descriptor,
- deserializer: GRPCProtobuf.ProtobufDeserializer<Helloworld_HelloRequest>(),
- serializer: GRPCProtobuf.ProtobufSerializer<Helloworld_HelloReply>(),
- handler: { request in
- try await self.sayHello(request: request)
- }
- )
- }
- }
- /// The greeting service definition.
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- public protocol Helloworld_GreeterServiceProtocol: Helloworld_Greeter.StreamingServiceProtocol {
- /// Sends a greeting.
- func sayHello(request: GRPCCore.ServerRequest.Single<Helloworld_HelloRequest>) async throws -> GRPCCore.ServerResponse.Single<Helloworld_HelloReply>
- }
- /// Partial conformance to `Helloworld_GreeterStreamingServiceProtocol`.
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- extension Helloworld_Greeter.ServiceProtocol {
- public func sayHello(request: GRPCCore.ServerRequest.Stream<Helloworld_HelloRequest>) async throws -> GRPCCore.ServerResponse.Stream<Helloworld_HelloReply> {
- let response = try await self.sayHello(request: GRPCCore.ServerRequest.Single(stream: request))
- return GRPCCore.ServerResponse.Stream(single: response)
- }
- }
- """
- )
- try testCodeGeneration(
- proto: Google_Protobuf_FileDescriptorProto.helloWorldEmptyPackage,
- indentation: 2,
- visibility: .package,
- client: true,
- server: true,
- expectedCode: """
- // Copyright 2015 gRPC authors.
- //
- // Licensed under the Apache License, Version 2.0 (the "License");
- // you may not use this file except in compliance with the License.
- // You may obtain a copy of the License at
- //
- // http://www.apache.org/licenses/LICENSE-2.0
- //
- // Unless required by applicable law or agreed to in writing, software
- // distributed under the License is distributed on an "AS IS" BASIS,
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- // See the License for the specific language governing permissions and
- // limitations under the License.
- // DO NOT EDIT.
- // swift-format-ignore-file
- //
- // Generated by the gRPC Swift generator plugin for the protocol buffer compiler.
- // Source: helloworld.proto
- //
- // For information on using the generated types, please see the documentation:
- // https://github.com/grpc/grpc-swift
- package import GRPCCore
- internal import GRPCProtobuf
- package import DifferentModule
- package import ExtraModule
- package enum Greeter {
- package static let descriptor = GRPCCore.ServiceDescriptor.Greeter
- package enum Method {
- package enum SayHello {
- package typealias Input = HelloRequest
- package typealias Output = HelloReply
- package static let descriptor = GRPCCore.MethodDescriptor(
- service: Greeter.descriptor.fullyQualifiedService,
- method: "SayHello"
- )
- }
- package static let descriptors: [GRPCCore.MethodDescriptor] = [
- SayHello.descriptor
- ]
- }
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- package typealias StreamingServiceProtocol = GreeterStreamingServiceProtocol
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- package typealias ServiceProtocol = GreeterServiceProtocol
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- package typealias ClientProtocol = GreeterClientProtocol
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- package typealias Client = GreeterClient
- }
- extension GRPCCore.ServiceDescriptor {
- package static let Greeter = Self(
- package: "",
- service: "Greeter"
- )
- }
- /// The greeting service definition.
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- package protocol GreeterStreamingServiceProtocol: GRPCCore.RegistrableRPCService {
- /// Sends a greeting.
- func sayHello(request: GRPCCore.ServerRequest.Stream<HelloRequest>) async throws -> GRPCCore.ServerResponse.Stream<HelloReply>
- }
- /// Conformance to `GRPCCore.RegistrableRPCService`.
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- extension Greeter.StreamingServiceProtocol {
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- package func registerMethods(with router: inout GRPCCore.RPCRouter) {
- router.registerHandler(
- forMethod: Greeter.Method.SayHello.descriptor,
- deserializer: GRPCProtobuf.ProtobufDeserializer<HelloRequest>(),
- serializer: GRPCProtobuf.ProtobufSerializer<HelloReply>(),
- handler: { request in
- try await self.sayHello(request: request)
- }
- )
- }
- }
- /// The greeting service definition.
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- package protocol GreeterServiceProtocol: Greeter.StreamingServiceProtocol {
- /// Sends a greeting.
- func sayHello(request: GRPCCore.ServerRequest.Single<HelloRequest>) async throws -> GRPCCore.ServerResponse.Single<HelloReply>
- }
- /// Partial conformance to `GreeterStreamingServiceProtocol`.
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- extension Greeter.ServiceProtocol {
- package func sayHello(request: GRPCCore.ServerRequest.Stream<HelloRequest>) async throws -> GRPCCore.ServerResponse.Stream<HelloReply> {
- let response = try await self.sayHello(request: GRPCCore.ServerRequest.Single(stream: request))
- return GRPCCore.ServerResponse.Stream(single: response)
- }
- }
- /// The greeting service definition.
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- package protocol GreeterClientProtocol: Sendable {
- /// Sends a greeting.
- func sayHello<R>(
- request: GRPCCore.ClientRequest.Single<HelloRequest>,
- serializer: some GRPCCore.MessageSerializer<HelloRequest>,
- deserializer: some GRPCCore.MessageDeserializer<HelloReply>,
- options: GRPCCore.CallOptions,
- _ body: @Sendable @escaping (GRPCCore.ClientResponse.Single<HelloReply>) async throws -> R
- ) async throws -> R where R: Sendable
- }
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- extension Greeter.ClientProtocol {
- package func sayHello<R>(
- request: GRPCCore.ClientRequest.Single<HelloRequest>,
- options: GRPCCore.CallOptions = .defaults,
- _ body: @Sendable @escaping (GRPCCore.ClientResponse.Single<HelloReply>) async throws -> R = {
- try $0.message
- }
- ) async throws -> R where R: Sendable {
- try await self.sayHello(
- request: request,
- serializer: GRPCProtobuf.ProtobufSerializer<HelloRequest>(),
- deserializer: GRPCProtobuf.ProtobufDeserializer<HelloReply>(),
- options: options,
- body
- )
- }
- }
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- extension Greeter.ClientProtocol {
- /// Sends a greeting.
- package func sayHello<Result>(
- _ message: HelloRequest,
- metadata: GRPCCore.Metadata = [:],
- options: GRPCCore.CallOptions = .defaults,
- onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse.Single<HelloReply>) async throws -> Result = {
- try $0.message
- }
- ) async throws -> Result where Result: Sendable {
- let request = GRPCCore.ClientRequest.Single<HelloRequest>(
- message: message,
- metadata: metadata
- )
- return try await self.sayHello(
- request: request,
- options: options,
- handleResponse
- )
- }
- }
- /// The greeting service definition.
- @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
- package struct GreeterClient: Greeter.ClientProtocol {
- private let client: GRPCCore.GRPCClient
-
- package init(wrapping client: GRPCCore.GRPCClient) {
- self.client = client
- }
-
- /// Sends a greeting.
- package func sayHello<R>(
- request: GRPCCore.ClientRequest.Single<HelloRequest>,
- serializer: some GRPCCore.MessageSerializer<HelloRequest>,
- deserializer: some GRPCCore.MessageDeserializer<HelloReply>,
- options: GRPCCore.CallOptions = .defaults,
- _ body: @Sendable @escaping (GRPCCore.ClientResponse.Single<HelloReply>) async throws -> R = {
- try $0.message
- }
- ) async throws -> R where R: Sendable {
- try await self.client.unary(
- request: request,
- descriptor: Greeter.Method.SayHello.descriptor,
- serializer: serializer,
- deserializer: deserializer,
- options: options,
- handler: body
- )
- }
- }
- """
- )
- }
- func testCodeGeneration(
- proto: Google_Protobuf_FileDescriptorProto,
- indentation: Int,
- visibility: SourceGenerator.Configuration.AccessLevel,
- client: Bool,
- server: Bool,
- expectedCode: String,
- file: StaticString = #filePath,
- line: UInt = #line
- ) throws {
- let configs = SourceGenerator.Configuration(
- accessLevel: visibility,
- client: client,
- server: server,
- indentation: indentation
- )
- let descriptorSet = DescriptorSet(
- protos: [
- Google_Protobuf_FileDescriptorProto(name: "same-module.proto", package: "same-package"),
- Google_Protobuf_FileDescriptorProto(
- name: "different-module.proto",
- package: "different-package"
- ),
- proto,
- ])
- guard let fileDescriptor = descriptorSet.fileDescriptor(named: "helloworld.proto") else {
- return XCTFail(
- """
- Could not find the file descriptor of "helloworld.proto".
- """
- )
- }
- let moduleMappings = SwiftProtobuf_GenSwift_ModuleMappings.with {
- $0.mapping = [
- SwiftProtobuf_GenSwift_ModuleMappings.Entry.with {
- $0.protoFilePath = ["different-module.proto"]
- $0.moduleName = "DifferentModule"
- }
- ]
- }
- let generator = ProtobufCodeGenerator(configuration: configs)
- try XCTAssertEqualWithDiff(
- try generator.generateCode(
- from: fileDescriptor,
- protoFileModuleMappings: ProtoFileToModuleMappings(moduleMappingsProto: moduleMappings),
- extraModuleImports: ["ExtraModule"]
- ),
- expectedCode,
- file: file,
- line: line
- )
- }
- }
- private func diff(expected: String, actual: String) throws -> String {
- let process = Process()
- process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
- process.arguments = [
- "bash", "-c",
- "diff -U5 --label=expected <(echo '\(expected)') --label=actual <(echo '\(actual)')",
- ]
- let pipe = Pipe()
- process.standardOutput = pipe
- try process.run()
- process.waitUntilExit()
- let pipeData = try XCTUnwrap(
- pipe.fileHandleForReading.readToEnd(),
- """
- No output from command:
- \(process.executableURL!.path) \(process.arguments!.joined(separator: " "))
- """
- )
- return String(decoding: pipeData, as: UTF8.self)
- }
- internal func XCTAssertEqualWithDiff(
- _ actual: String,
- _ expected: String,
- file: StaticString = #filePath,
- line: UInt = #line
- ) throws {
- if actual == expected { return }
- XCTFail(
- """
- XCTAssertEqualWithDiff failed (click for diff)
- \(try diff(expected: expected, actual: actual))
- """,
- file: file,
- line: line
- )
- }
- #endif // os(macOS) || os(Linux)
|