diff --git a/.swift-format b/.swift-format index 381b19fc..710e3be3 100644 --- a/.swift-format +++ b/.swift-format @@ -13,7 +13,8 @@ "lineBreakBeforeEachGenericRequirement" : true, "lineLength" : 120, "maximumBlankLines" : 1, - "multilineTrailingCommaBehavior" : "neverUsed", + "multilineTrailingCommaBehavior" : "keptAsWritten", + "multiElementCollectionTrailingCommas" : true, "prioritizeKeepingFunctionOutputTogether" : true, "respectsExistingLineBreaks" : true, "rules" : { diff --git a/Sources/NIOIMAPCore/Parser/Grammar/GrammarParser+Mailbox.swift b/Sources/NIOIMAPCore/Parser/Grammar/GrammarParser+Mailbox.swift index a65437c8..5303e4d7 100644 --- a/Sources/NIOIMAPCore/Parser/Grammar/GrammarParser+Mailbox.swift +++ b/Sources/NIOIMAPCore/Parser/Grammar/GrammarParser+Mailbox.swift @@ -265,24 +265,6 @@ extension GrammarParser { } } - // mbox-or-pat = list-mailbox / patterns - func parseMailboxOrPat(buffer: inout ParseBuffer, tracker: StackTracker) throws -> MailboxPatterns { - func parseMailboxOrPat_list(buffer: inout ParseBuffer, tracker: StackTracker) throws -> MailboxPatterns { - .mailbox(try self.parseListMailbox(buffer: &buffer, tracker: tracker)) - } - - func parseMailboxOrPat_patterns(buffer: inout ParseBuffer, tracker: StackTracker) throws -> MailboxPatterns { - .pattern(try self.parsePatterns(buffer: &buffer, tracker: tracker)) - } - - return try PL.parseOneOf( - parseMailboxOrPat_list, - parseMailboxOrPat_patterns, - buffer: &buffer, - tracker: tracker - ) - } - // mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag // *(SP mbx-list-oflag) / // mbx-list-oflag *(SP mbx-list-oflag) diff --git a/Tests/NIOIMAPCoreTests/Base64Tests.swift b/Tests/NIOIMAPCoreTests/Base64Tests.swift index c0991523..9ecd3ad4 100644 --- a/Tests/NIOIMAPCoreTests/Base64Tests.swift +++ b/Tests/NIOIMAPCoreTests/Base64Tests.swift @@ -155,6 +155,75 @@ struct Base64Tests { func parseBase64(_ fixture: ParseFixture) { fixture.checkParsing() } + + // MARK: - encodeString + + @Test( + "encodeString produces correct output", + arguments: [ + ([UInt8](), ""), + ([0x61, 0x62, 0x63], "YWJj"), // "abc" → 3-byte aligned, no remainder + ([0x61, 0x62], "YWI="), // "ab" → 2-byte remainder + ([0x61], "YQ=="), // "a" → 1-byte remainder + ] as [([UInt8], String)] + ) + func encodeStringProducesCorrectOutput(_ fixture: ([UInt8], String)) { + let result = Base64.encodeString(bytes: fixture.0) + #expect(result == fixture.1) + } + + @Test("encodeString with omitPaddingCharacter omits padding") + func encodeStringOmitsPadding() { + #expect(Base64.encodeString(bytes: [0x61], options: [.omitPaddingCharacter]) == "YQ") + #expect(Base64.encodeString(bytes: [0x61, 0x62], options: [.omitPaddingCharacter]) == "YWI") + } + + // MARK: - decode(string:) + + @Test( + "decode(string:) decodes valid base64", + arguments: [ + ("YWJj", [0x61, 0x62, 0x63]), // "abc" + ("YQ==", [0x61]), // "a" + ("YWI=", [0x61, 0x62]), // "ab" + ] as [(String, [UInt8])] + ) + func decodeStringDecodesValidBase64(_ fixture: (String, [UInt8])) throws { + let result = try Base64.decode(string: fixture.0) + #expect(result == fixture.1) + } + + @Test("decode(string:) with empty string returns empty") + func decodeStringEmptyReturnsEmpty() throws { + let result = try Base64.decode(string: "") + #expect(result == []) + } + + @Test("decode with omitPaddingCharacter and length mod 4 == 1 throws") + func decodeOmitPaddingInvalidLength() { + // Length 1 mod 4 = 1 is invalid even with omitPaddingCharacter + #expect(throws: (any Error).self) { + try Base64.decode(string: "Y", options: [.omitPaddingCharacter]) + } + } + + @Test("decode with invalid character in full 4-byte chunk throws") + func decodeInvalidCharacterInFullChunk() { + // 8-char aligned input: fullchunks = 8/4 - 1 = 1, so the loop processes + // the first 4 chars "YW!h" and hits the invalid '!' at the full-chunk check (line 525). + #expect(throws: (any Error).self) { + try Base64.decode(string: "YW!hYWFh") + } + } + + @Test("decode(string:) with omitPaddingCharacter round-trips non-aligned input") + func decodeStringOmitPaddingRoundTrip() throws { + // "a" encodes to "YQ" (length 2, 2 mod 4 = 2 → non-4-aligned) + let encoded = Base64.encodeString(bytes: [0x61], options: [.omitPaddingCharacter]) + #expect(encoded == "YQ") + let decoded = try Base64.decode(string: encoded, options: [.omitPaddingCharacter]) + #expect(decoded == [0x61]) + } } // MARK: - diff --git a/Tests/NIOIMAPCoreTests/EncodingOptions+Tests.swift b/Tests/NIOIMAPCoreTests/EncodingOptions+Tests.swift new file mode 100644 index 00000000..8d23d3d6 --- /dev/null +++ b/Tests/NIOIMAPCoreTests/EncodingOptions+Tests.swift @@ -0,0 +1,65 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +@_spi(NIOIMAPInternal) @testable import NIOIMAPCore +import Testing + +@Suite("EncodingOptions") +private struct EncodingOptionsTests { + @Test( + "command options from capabilities", + arguments: [ + OptionsFixture(capabilities: [], expected: CommandEncodingOptions()), + OptionsFixture( + capabilities: [.literalPlus], + expected: CommandEncodingOptions(useNonSynchronizingLiteralPlus: true) + ), + OptionsFixture( + capabilities: [.literalMinus], + expected: CommandEncodingOptions(useNonSynchronizingLiteralMinus: true) + ), + OptionsFixture(capabilities: [.binary], expected: CommandEncodingOptions(useBinaryLiteral: true)), + ] as [OptionsFixture] + ) + func commandOptionsFromCapabilities(_ fixture: OptionsFixture) { + #expect(CommandEncodingOptions(capabilities: fixture.capabilities) == fixture.expected) + } + + @Test( + "response options from capabilities", + arguments: [ + OptionsFixture(capabilities: [.imap4rev1], expected: ResponseEncodingOptions()) + ] as [OptionsFixture] + ) + func responseOptionsFromCapabilities(_ fixture: OptionsFixture) { + #expect(ResponseEncodingOptions(capabilities: fixture.capabilities) == fixture.expected) + } + + @Test("updateEnabledOptions removes useSearchCharset") + func updateEnabledOptionsRemovesSearchCharset() { + var options = CommandEncodingOptions() + #expect(options.useSearchCharset == true) + options.updateEnabledOptions(capabilities: [.utf8(.accept)]) + #expect(options.useSearchCharset == false) + } +} + +// MARK: - + +private struct OptionsFixture: CustomTestStringConvertible, Sendable { + var capabilities: [Capability] + var expected: O + + var testDescription: String { capabilities.map { String(reflecting: $0) }.joined(separator: " ") } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Append/AppendData+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Append/AppendData+Tests.swift index adf9bc17..7b9ef17c 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Append/AppendData+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Append/AppendData+Tests.swift @@ -44,6 +44,23 @@ struct AppendDataTests { fixture.checkEncoding() } + #if swift(>=6.2) + @Test("encode in server mode calls preconditionFailure") + func encodeInServerModeCallsPreconditionFailure() async { + await #expect( + processExitsWith: ExitTest.Condition.failure, + performing: { + var buffer = EncodeBuffer.serverEncodeBuffer( + buffer: ByteBufferAllocator().buffer(capacity: 128), + options: ResponseEncodingOptions(), + loggingMode: false + ) + buffer.writeAppendData(.init(byteCount: 123)) + } + ) + } + #endif + @Test(arguments: [ ParseFixture.appendData("{123}\r\n", "hello", expected: .success(.init(byteCount: 123))), ParseFixture.appendData( diff --git a/Tests/NIOIMAPCoreTests/Grammar/Append/AppendOptions+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Append/AppendOptions+Tests.swift index 8c106f69..15d93b80 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Append/AppendOptions+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Append/AppendOptions+Tests.swift @@ -45,6 +45,18 @@ struct AppendOptionsTests { ), " (\\Answered) \"25-Jun-1994 01:02:03 +0000\"" ), + EncodeFixture.appendOptions( + .init(flagList: [], internalDate: nil, extensions: ["name1": .sequence(.range(1...2))]), + " name1 1:2" + ), + EncodeFixture.appendOptions( + .init( + flagList: [], + internalDate: nil, + extensions: ["name1": .sequence(.range(1...2)), "name2": .sequence(.range(2...3))] + ), + " name1 1:2 name2 2:3" + ), ]) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() diff --git a/Tests/NIOIMAPCoreTests/Grammar/AttributeFlag+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/AttributeFlag+Tests.swift index 74eb6431..3c44009f 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/AttributeFlag+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/AttributeFlag+Tests.swift @@ -18,14 +18,17 @@ import Testing @Suite("AttributeFlag") struct AttributeFlagTests { - @Test(arguments: [ - EncodeFixture.attributeFlag(.answered, "\\\\answered"), - EncodeFixture.attributeFlag(.deleted, "\\\\deleted"), - EncodeFixture.attributeFlag(.draft, "\\\\draft"), - EncodeFixture.attributeFlag(.flagged, "\\\\flagged"), - EncodeFixture.attributeFlag(.seen, "\\\\seen"), - EncodeFixture.attributeFlag(.init("test"), "test"), - ]) + @Test( + "encode", + arguments: [ + EncodeFixture.attributeFlag(.answered, "\\\\answered"), + EncodeFixture.attributeFlag(.deleted, "\\\\deleted"), + EncodeFixture.attributeFlag(.draft, "\\\\draft"), + EncodeFixture.attributeFlag(.flagged, "\\\\flagged"), + EncodeFixture.attributeFlag(.seen, "\\\\seen"), + EncodeFixture.attributeFlag(.init("test"), "test"), + ] + ) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() } @@ -37,10 +40,24 @@ struct AttributeFlagTests { #expect(AttributeFlag("test").stringValue == "test") } - @Test(arguments: [ - ParseFixture.attributeFlag(#"\\Answered"#, expected: .success(.answered)), - ParseFixture.attributeFlag("some", expected: .success(.init("some"))), - ]) + @Test( + "string conversion", + arguments: [ + (AttributeFlag.answered, "\\\\answered"), + (AttributeFlag("custom"), "custom"), + ] as [(AttributeFlag, String)] + ) + func stringConversion(_ fixture: (AttributeFlag, String)) { + #expect(String(fixture.0) == fixture.1) + } + + @Test( + "parse", + arguments: [ + ParseFixture.attributeFlag(#"\\Answered"#, expected: .success(.answered)), + ParseFixture.attributeFlag("some", expected: .success(.init("some"))), + ] + ) func parse(_ fixture: ParseFixture) { fixture.checkParsing() } diff --git a/Tests/NIOIMAPCoreTests/Grammar/Body/BodyStructure+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Body/BodyStructure+Tests.swift index 827f0b8d..4d165162 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Body/BodyStructure+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Body/BodyStructure+Tests.swift @@ -1934,11 +1934,170 @@ private struct BodyStructureTests { " UID 1", expected: .failure ), + // Quoted string with backslash escapes inside an invalid body (covers the 0x5C case) + ParseFixture.invalidBodyStructure( + #"("\"hello\"")"#, + " UID 1", + expected: .success(.invalid) + ), + // Run-away body: >200,000 non-special bytes → throws "Run-away body structure" + ParseFixture.invalidBodyStructure( + "(" + String(repeating: "(", count: 200_000), + " UID 1", + expected: .failure + ), ] ) func parseInvalidBody(_ fixture: ParseFixture) { fixture.checkParsing() } + + @Test("underestimatedCount is 1 for singlepart, 3 for 2-part multipart") + func underestimatedCount() { + let basic = BodyStructure.singlepart( + .init( + kind: .basic(.init(topLevel: .application, sub: .mixed)), + fields: .init(parameters: [:], id: nil, contentDescription: nil, encoding: nil, octetCount: 0) + ) + ) + #expect(basic.underestimatedCount == 1) + + let multipart = BodyStructure.multipart( + .init( + parts: [basic, basic], + mediaSubtype: .mixed + ) + ) + #expect(multipart.underestimatedCount == 3) + } + + @Test("isEmpty always false") + func isEmpty() { + let basic = BodyStructure.singlepart( + .init( + kind: .basic(.init(topLevel: .application, sub: .mixed)), + fields: .init(parameters: [:], id: nil, contentDescription: nil, encoding: nil, octetCount: 0) + ) + ) + #expect(!basic.isEmpty) + } + + @Test("find returns nil for invalid positions") + func findReturnsNilForInvalidPositions() { + let basic = BodyStructure.singlepart( + .init( + kind: .basic(.init(topLevel: .application, sub: .mixed)), + fields: .init(parameters: [:], id: nil, contentDescription: nil, encoding: nil, octetCount: 0) + ) + ) + let multipart = BodyStructure.multipart( + .init( + parts: [basic, basic], + mediaSubtype: .mixed + ) + ) + // index 0 is out-of-range (1-based) + #expect(basic.find(SectionSpecifier.Part([0])) == nil) + // index exceeds multipart count + #expect(multipart.find(SectionSpecifier.Part([10])) == nil) + // sub-structure of basic part that has no children + #expect(multipart.find(SectionSpecifier.Part([1, 1])) == nil) + } + + @Test( + "encode body", + arguments: [ + EncodeFixture.body( + .valid( + .singlepart( + .init( + kind: .text(.init(mediaSubtype: .init("plain"), lineCount: 5)), + fields: .init( + parameters: [:], + id: nil, + contentDescription: nil, + encoding: nil, + octetCount: 100 + ) + ) + ) + ), + #"("TEXT" "PLAIN" NIL NIL NIL NIL 100 5)"# + ), + EncodeFixture.body( + .invalid, + "()" + ), + ] as [EncodeFixture] + ) + func encodeBodyMessageAttribute(_ fixture: EncodeFixture) { + fixture.checkEncoding() + } + + @Test("encode multipart body") + func encodeMultipartBody() { + let basic = BodyStructure.singlepart( + .init( + kind: .text(.init(mediaSubtype: .init("plain"), lineCount: 5)), + fields: .init(parameters: [:], id: nil, contentDescription: nil, encoding: nil, octetCount: 100) + ) + ) + let multipart = BodyStructure.multipart( + .init( + parts: [basic], + mediaSubtype: .mixed + ) + ) + let fixture = EncodeFixture.bodyStructure(multipart, #"(("TEXT" "PLAIN" NIL NIL NIL NIL 100 5) "MIXED")"#) + fixture.checkEncoding() + } + + #if swift(>=6.2) + @Test("subscript fatal error for invalid part") func subscriptFatalErrorForInvalidPart() async { + await #expect( + processExitsWith: ExitTest.Condition.failure, + performing: { + let basic = BodyStructure.singlepart( + .init( + kind: .basic(.init(topLevel: .application, sub: .mixed)), + fields: .init(parameters: [:], id: nil, contentDescription: nil, encoding: nil, octetCount: 0) + ) + ) + _ = basic[SectionSpecifier.Part([5])] + } + ) + } + + @Test("index(before:) fatal error at start index") func indexBeforeFatalErrorAtStartIndex() async { + await #expect( + processExitsWith: ExitTest.Condition.failure, + performing: { + let basic = BodyStructure.singlepart( + .init( + kind: .basic(.init(topLevel: .application, sub: .mixed)), + fields: .init(parameters: [:], id: nil, contentDescription: nil, encoding: nil, octetCount: 0) + ) + ) + _ = basic.index(before: basic.startIndex) + } + ) + } + + @Test("index(after:) fatal error for invalid part") func indexAfterFatalErrorForInvalidPart() async { + await #expect( + processExitsWith: ExitTest.Condition.failure, + performing: { + let basic = BodyStructure.singlepart( + .init( + kind: .basic(.init(topLevel: .application, sub: .mixed)), + fields: .init(parameters: [:], id: nil, contentDescription: nil, encoding: nil, octetCount: 0) + ) + ) + _ = basic.index(after: SectionSpecifier.Part([1])) + } + ) + } + #endif } // MARK: - @@ -2010,3 +2169,31 @@ extension ParseFixture { ) } } + +extension EncodeFixture { + fileprivate static func body( + _ input: MessageAttribute.BodyStructure, + _ expectedString: String + ) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeBody($1) } + ) + } +} + +extension EncodeFixture { + fileprivate static func bodyStructure( + _ input: BodyStructure, + _ expectedString: String + ) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeBody($1) } + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Body/Field/BodyFieldDSPTests.swift b/Tests/NIOIMAPCoreTests/Grammar/Body/Field/BodyFieldDSPTests.swift index 71777c5c..5077c7aa 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Body/Field/BodyFieldDSPTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Body/Field/BodyFieldDSPTests.swift @@ -40,24 +40,27 @@ struct BodyFieldDSPTests { var testDescription: String { name } } - @Test(arguments: [ - SizeFixture(name: "no size parameter", disposition: .init(kind: "test", parameters: [:]), expected: nil), - SizeFixture( - name: "lowercase size parameter", - disposition: .init(kind: "test", parameters: ["size": "123"]), - expected: 123 - ), - SizeFixture( - name: "uppercase SIZE parameter", - disposition: .init(kind: "test", parameters: ["SIZE": "456"]), - expected: 456 - ), - SizeFixture( - name: "invalid size value", - disposition: .init(kind: "test", parameters: ["SIZE": "abc"]), - expected: nil - ), - ]) + @Test( + "size property", + arguments: [ + SizeFixture(name: "no size parameter", disposition: .init(kind: "test", parameters: [:]), expected: nil), + SizeFixture( + name: "lowercase size parameter", + disposition: .init(kind: "test", parameters: ["size": "123"]), + expected: 123 + ), + SizeFixture( + name: "uppercase SIZE parameter", + disposition: .init(kind: "test", parameters: ["SIZE": "456"]), + expected: 456 + ), + SizeFixture( + name: "invalid size value", + disposition: .init(kind: "test", parameters: ["SIZE": "abc"]), + expected: nil + ), + ] + ) func sizeProperty(_ fixture: SizeFixture) { #expect(fixture.disposition.size == fixture.expected) } @@ -70,23 +73,26 @@ struct BodyFieldDSPTests { var testDescription: String { name } } - @Test(arguments: [ - FilenameFixture( - name: "no filename parameter", - disposition: .init(kind: "test", parameters: [:]), - expected: nil - ), - FilenameFixture( - name: "lowercase filename parameter", - disposition: .init(kind: "test", parameters: ["filename": "hello"]), - expected: "hello" - ), - FilenameFixture( - name: "uppercase FILENAME parameter", - disposition: .init(kind: "test", parameters: ["FILENAME": "world"]), - expected: "world" - ), - ]) + @Test( + "filename property", + arguments: [ + FilenameFixture( + name: "no filename parameter", + disposition: .init(kind: "test", parameters: [:]), + expected: nil + ), + FilenameFixture( + name: "lowercase filename parameter", + disposition: .init(kind: "test", parameters: ["filename": "hello"]), + expected: "hello" + ), + FilenameFixture( + name: "uppercase FILENAME parameter", + disposition: .init(kind: "test", parameters: ["FILENAME": "world"]), + expected: "world" + ), + ] + ) func filenameProperty(_ fixture: FilenameFixture) { #expect(fixture.disposition.filename == fixture.expected) } diff --git a/Tests/NIOIMAPCoreTests/Grammar/Body/Field/BodyFieldEncodingTests.swift b/Tests/NIOIMAPCoreTests/Grammar/Body/Field/BodyFieldEncodingTests.swift index 56471a6d..5a4af14b 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Body/Field/BodyFieldEncodingTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Body/Field/BodyFieldEncodingTests.swift @@ -18,29 +18,61 @@ import Testing @Suite("BodyStructure.Encoding") struct BodyFieldEncodingTests { - @Test(arguments: [ - EncodeFixture.bodyEncoding(.sevenBit, #""7BIT""#), - EncodeFixture.bodyEncoding(.eightBit, #""8BIT""#), - EncodeFixture.bodyEncoding(.binary, #""BINARY""#), - EncodeFixture.bodyEncoding(.base64, #""BASE64""#), - EncodeFixture.bodyEncoding(.quotedPrintable, #""QUOTED-PRINTABLE""#), - EncodeFixture.bodyEncoding(.init("some"), "\"SOME\""), - ]) + @Test( + "encoding", + arguments: [ + EncodeFixture.bodyEncoding(.sevenBit, #""7BIT""#), + EncodeFixture.bodyEncoding(.eightBit, #""8BIT""#), + EncodeFixture.bodyEncoding(.binary, #""BINARY""#), + EncodeFixture.bodyEncoding(.base64, #""BASE64""#), + EncodeFixture.bodyEncoding(.quotedPrintable, #""QUOTED-PRINTABLE""#), + EncodeFixture.bodyEncoding(.init("some"), "\"SOME\""), + ] + ) func encoding(_ fixture: EncodeFixture) { fixture.checkEncoding() } - @Test(arguments: [ - ParseFixture.bodyEncoding(#""BASE64""#, expected: .success(.base64)), - ParseFixture.bodyEncoding(#""BINARY""#, expected: .success(.binary)), - ParseFixture.bodyEncoding(#""7BIT""#, expected: .success(.sevenBit)), - ParseFixture.bodyEncoding(#""8BIT""#, expected: .success(.eightBit)), - ParseFixture.bodyEncoding(#""QUOTED-PRINTABLE""#, expected: .success(.quotedPrintable)), - ParseFixture.bodyEncoding(#""other""#, expected: .success(.init("other"))), - ]) + @Test( + "parse", + arguments: [ + ParseFixture.bodyEncoding(#""BASE64""#, expected: .success(.base64)), + ParseFixture.bodyEncoding(#""BINARY""#, expected: .success(.binary)), + ParseFixture.bodyEncoding(#""7BIT""#, expected: .success(.sevenBit)), + ParseFixture.bodyEncoding(#""8BIT""#, expected: .success(.eightBit)), + ParseFixture.bodyEncoding(#""QUOTED-PRINTABLE""#, expected: .success(.quotedPrintable)), + ParseFixture.bodyEncoding(#""other""#, expected: .success(.init("other"))), + ] + ) func parse(_ fixture: ParseFixture) { fixture.checkParsing() } + + @Test("nil encoding encodes as NIL") + func nilEncodingEncodesAsNIL() { + let expected = "NIL" + var buffer = EncodeBuffer.serverEncodeBuffer( + buffer: ByteBufferAllocator().buffer(capacity: 32), + options: ResponseEncodingOptions(), + loggingMode: false + ) + _ = buffer.writeBodyEncoding(nil) + var remaining = buffer + let chunk = remaining.nextChunk() + #expect(String(buffer: chunk.bytes) == expected) + } + + @Test("debug description") + func debugDescription() { + #expect(BodyStructure.Encoding.sevenBit.debugDescription == "7BIT") + #expect(BodyStructure.Encoding.base64.debugDescription == "BASE64") + } + + @Test("string conversion") + func stringConversion() { + #expect(String(BodyStructure.Encoding.sevenBit) == "7BIT") + #expect(String(BodyStructure.Encoding.quotedPrintable) == "QUOTED-PRINTABLE") + } } // MARK: - diff --git a/Tests/NIOIMAPCoreTests/Grammar/Body/Type/BodySinglepartTests.swift b/Tests/NIOIMAPCoreTests/Grammar/Body/Type/BodySinglepartTests.swift index dd349bd2..08bf6f5b 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Body/Type/BodySinglepartTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Body/Type/BodySinglepartTests.swift @@ -215,6 +215,51 @@ extension BodySinglepartTests { ) ) ), + // Extension with non-nil md5 + ParseFixture.bodySinglepart( + #""TEXT" "plain" NIL NIL NIL "7BIT" 100 10 "md5hash""#, + "\r\n", + expected: .success( + .init( + kind: .text(.init(mediaSubtype: "plain", lineCount: 10)), + fields: .init( + parameters: [:], + id: nil, + contentDescription: nil, + encoding: .sevenBit, + octetCount: 100 + ), + extension: .init(digest: "md5hash", dispositionAndLanguage: nil) + ) + ) + ), + // Full extension chain: md5 + disposition + language + location + body-extension + ParseFixture.bodySinglepart( + #""TEXT" "plain" NIL NIL NIL "7BIT" 100 10 "md5hash" NIL NIL "http://example.com" 42"#, + "\r\n", + expected: .success( + .init( + kind: .text(.init(mediaSubtype: "plain", lineCount: 10)), + fields: .init( + parameters: [:], + id: nil, + contentDescription: nil, + encoding: .sevenBit, + octetCount: 100 + ), + extension: .init( + digest: "md5hash", + dispositionAndLanguage: .init( + disposition: nil, + language: .init( + languages: [], + location: .init(location: "http://example.com", extensions: [.number(42)]) + ) + ) + ) + ) + ) + ), ]) func parse(_ fixture: ParseFixture) { fixture.checkParsing() diff --git a/Tests/NIOIMAPCoreTests/Grammar/ByteBufferWriteLiteralTests.swift b/Tests/NIOIMAPCoreTests/Grammar/ByteBufferWriteLiteralTests.swift index 0a12c3f0..3d959abb 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/ByteBufferWriteLiteralTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/ByteBufferWriteLiteralTests.swift @@ -117,6 +117,63 @@ struct ByteBufferWriteLiteralTests { func writeLiteral8WithClientBuffers(_ fixture: EncodeFixture) { fixture.checkEncoding() } + + @Test("writeIMAPString in logging mode redacts content") + func writeIMAPStringLoggingMode() { + // quoted string in logging mode → "∅" (with enclosing quotes) + var quotedBuffer = EncodeBuffer.serverEncodeBuffer( + buffer: ByteBufferAllocator().buffer(capacity: 128), + options: ResponseEncodingOptions(), + loggingMode: true + ) + _ = quotedBuffer.writeIMAPString(ByteBuffer(string: "hello")) + var chunk = quotedBuffer.nextChunk() + let quotedOutput = String(buffer: chunk.bytes) + while chunk.waitForContinuation { chunk = quotedBuffer.nextChunk() } + #expect(quotedOutput == #""∅""#) + + // server literal in logging mode + var serverOptions = ResponseEncodingOptions() + serverOptions.useQuotedString = false + var serverLiteralBuffer = EncodeBuffer.serverEncodeBuffer( + buffer: ByteBufferAllocator().buffer(capacity: 128), + options: serverOptions, + loggingMode: true + ) + _ = serverLiteralBuffer.writeIMAPString(ByteBuffer(string: "hello")) + chunk = serverLiteralBuffer.nextChunk() + let serverLiteralOutput = String(buffer: chunk.bytes) + while chunk.waitForContinuation { chunk = serverLiteralBuffer.nextChunk() } + #expect(serverLiteralOutput == "{5}\r\n∅") + + // client synchronizing literal in logging mode + var clientSyncBuffer = EncodeBuffer.clientEncodeBuffer( + buffer: ByteBufferAllocator().buffer(capacity: 128), + options: CommandEncodingOptions(useQuotedString: false, useSynchronizingLiteral: true), + loggingMode: true + ) + _ = clientSyncBuffer.writeIMAPString(ByteBuffer(string: "hello")) + chunk = clientSyncBuffer.nextChunk() + let clientSyncFirstChunk = String(buffer: chunk.bytes) + #expect(clientSyncFirstChunk == "{5}\r\n") + #expect(chunk.waitForContinuation) + + // client non-synchronizing literal in logging mode + var clientNonSyncBuffer = EncodeBuffer.clientEncodeBuffer( + buffer: ByteBufferAllocator().buffer(capacity: 128), + options: CommandEncodingOptions( + useQuotedString: false, + useSynchronizingLiteral: false, + useNonSynchronizingLiteralPlus: true + ), + loggingMode: true + ) + _ = clientNonSyncBuffer.writeIMAPString(ByteBuffer(string: "hello")) + chunk = clientNonSyncBuffer.nextChunk() + let clientNonSyncOutput = String(buffer: chunk.bytes) + while chunk.waitForContinuation { chunk = clientNonSyncBuffer.nextChunk() } + #expect(clientNonSyncOutput == "{5+}\r\n∅") + } } // MARK: - diff --git a/Tests/NIOIMAPCoreTests/Grammar/Capability+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Capability+Tests.swift index 88af1a89..8d0d0c35 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Capability+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Capability+Tests.swift @@ -181,22 +181,79 @@ struct CapabilityTests { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.capabilityData("CAPABILITY IMAP4rev1", expected: .success([.imap4rev1])), - ParseFixture.capabilityData("CAPABILITY IMAP4 IMAP4rev1", expected: .success([.imap4, .imap4rev1])), - ParseFixture.capabilityData("CAPABILITY FILTERS IMAP4", expected: .success([.filters, .imap4])), - ParseFixture.capabilityData( - "CAPABILITY FILTERS IMAP4rev1 ENABLE", - expected: .success([.filters, .imap4rev1, .enable]) - ), - ParseFixture.capabilityData( - "CAPABILITY FILTERS IMAP4rev1 ENABLE IMAP4", - expected: .success([.filters, .imap4rev1, .enable, .imap4]) - ), - ]) + @Test( + "parse CAPABILITY suffix", + arguments: [ + ParseFixture.capabilitySuffix(" IMAP4rev1", expected: .success([.imap4rev1])), + ParseFixture.capabilitySuffix( + " CONDSTORE ENABLE FILTERS", + expected: .success([.condStore, .enable, .filters]) + ), + ParseFixture.capabilitySuffix( + " AUTH=PLAIN IMAP4rev1", + expected: .success([.authenticate(.plain), .imap4rev1]) + ), + ParseFixture.capabilitySuffix("", "", expected: .incompleteMessage), + ] + ) + func parseCapabilitySuffix(_ fixture: ParseFixture<[Capability]>) { + fixture.checkParsing() + } + + @Test( + "parse capability data", + arguments: [ + ParseFixture.capabilityData("CAPABILITY IMAP4rev1", expected: .success([.imap4rev1])), + ParseFixture.capabilityData("CAPABILITY IMAP4 IMAP4rev1", expected: .success([.imap4, .imap4rev1])), + ParseFixture.capabilityData("CAPABILITY FILTERS IMAP4", expected: .success([.filters, .imap4])), + ParseFixture.capabilityData( + "CAPABILITY FILTERS IMAP4rev1 ENABLE", + expected: .success([.filters, .imap4rev1, .enable]) + ), + ParseFixture.capabilityData( + "CAPABILITY FILTERS IMAP4rev1 ENABLE IMAP4", + expected: .success([.filters, .imap4rev1, .enable, .imap4]) + ), + ] + ) func parseCapabilityData(_ fixture: ParseFixture<[Capability]>) { fixture.checkParsing() } + + @Test( + "string conversion", + arguments: [ + (Capability.acl, "ACL"), + (Capability.idle, "IDLE"), + (Capability.authenticate(.plain), "AUTH=PLAIN"), + ] as [(Capability, String)] + ) + func stringConversion(_ fixture: (Capability, String)) { + #expect(String(fixture.0) == fixture.1) + } + + @Test( + "case-insensitive kind initializers", + arguments: [ + (Capability.context(Capability.ContextKind("search")), Capability.context(.search)), + (Capability.context(Capability.ContextKind("SEARCH")), Capability.context(.search)), + (Capability.sort(Capability.SortKind("display")), Capability.sort(.display)), + (Capability.sort(Capability.SortKind("DISPLAY")), Capability.sort(.display)), + (Capability.thread(Capability.ThreadKind("orderedsubject")), Capability.thread(.orderedSubject)), + (Capability.thread(Capability.ThreadKind("ORDEREDSUBJECT")), Capability.thread(.orderedSubject)), + (Capability.status(Capability.StatusKind("size")), Capability.status(.size)), + (Capability.status(Capability.StatusKind("SIZE")), Capability.status(.size)), + (Capability.utf8(Capability.UTF8Kind("accept")), Capability.utf8(.accept)), + (Capability.utf8(Capability.UTF8Kind("ACCEPT")), Capability.utf8(.accept)), + (Capability.rights(Capability.RightsKind("tekx")), Capability.rights(.tekx)), + (Capability.rights(Capability.RightsKind("TEKX")), Capability.rights(.tekx)), + (Capability.compression(Capability.CompressionKind("deflate")), Capability.compression(.deflate)), + (Capability.compression(Capability.CompressionKind("DEFLATE")), Capability.compression(.deflate)), + ] as [(Capability, Capability)] + ) + func caseInsensitiveKindInitializers(_ fixture: (Capability, Capability)) { + #expect(fixture.0 == fixture.1) + } } // MARK: - @@ -260,4 +317,17 @@ extension ParseFixture<[Capability]> { parser: GrammarParser().parseCapabilityData ) } + + fileprivate static func capabilitySuffix( + _ input: String, + _ terminator: String = "\r", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseCapabilitySuffix + ) + } } diff --git a/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandStream+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandStream+Tests.swift index f538b13e..0f134932 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandStream+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandStream+Tests.swift @@ -284,6 +284,64 @@ private struct CommandStreamTests { func descriptionWithoutPII(_ fixture: PIIFixture) { #expect(CommandStreamPart.descriptionWithoutPII([fixture.input]) == fixture.expected) } + + @Test( + "AppendCommand tag", + arguments: [ + (AppendCommand.start(tag: "A1", appendingTo: .inbox), "A1"), + (AppendCommand.beginMessage(message: .init(options: .none, data: .init(byteCount: 5))), nil), + (AppendCommand.messageBytes("data"), nil), + (AppendCommand.endMessage, nil), + (AppendCommand.beginCatenate(options: .none), nil), + (AppendCommand.catenateURL("/mailbox"), nil), + (AppendCommand.catenateData(.begin(size: 3)), nil), + (AppendCommand.catenateData(.bytes("abc")), nil), + (AppendCommand.catenateData(.end), nil), + (AppendCommand.endCatenate, nil), + (AppendCommand.finish, nil), + ] as [(AppendCommand, String?)] + ) + func appendCommandTag(_ fixture: (AppendCommand, String?)) { + #expect(fixture.0.tag == fixture.1) + } + + @Test( + "CommandStreamPart tag", + arguments: [ + (CommandStreamPart.idleDone, nil), + (CommandStreamPart.tagged(.init(tag: "B2", command: .noop)), "B2"), + (CommandStreamPart.append(.start(tag: "C3", appendingTo: .inbox)), "C3"), + (CommandStreamPart.append(.finish), nil), + (CommandStreamPart.continuationResponse("data"), nil), + ] as [(CommandStreamPart, String?)] + ) + func commandStreamPartTag(_ fixture: (CommandStreamPart, String?)) { + #expect(fixture.0.tag == fixture.1) + } + + @Test("CommandStreamPart debugDescription") + func commandStreamPartDebugDescription() { + let part = CommandStreamPart.tagged(.init(tag: "1", command: .noop)) + let desc = part.debugDescription + #expect(desc == "1 NOOP\r\n") + } + + @Test("writeAppendCommand in loggingMode for messageBytes") + func writeAppendCommandLoggingModeMessageBytes() { + var buffer = CommandEncodeBuffer(buffer: "", capabilities: [], loggingMode: true) + let count = buffer.writeCommandStream(.append(.messageBytes("hello"))) + #expect(count == 0) + #expect(String(buffer: buffer.buffer.nextChunk().bytes) == "") + } + + @Test("writeAppendCommand in loggingMode for endMessage") + func writeAppendCommandLoggingModeEndMessage() { + var buffer = CommandEncodeBuffer(buffer: "", capabilities: [], loggingMode: true) + let count = buffer.writeCommandStream(.append(.endMessage)) + #expect(count > 0) + let chunk = buffer.buffer.nextChunk() + #expect(String(buffer: chunk.bytes) == "∅") + } } // MARK: - diff --git a/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandType+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandType+Tests.swift index 10d5c880..b6c84159 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandType+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/CommandType/CommandType+Tests.swift @@ -174,11 +174,126 @@ struct CommandTypeTests { .custom(name: "FOOBAR", payloads: [.literal(.init(string: "¶"))]), expectedStrings: ["FOOBAR {2}\r\n", "¶"] ), + CommandEncodeFixture.command( + .rename(from: .inbox, to: .init("other"), parameters: [:]), + #"RENAME "INBOX" "other""# + ), + CommandEncodeFixture.command( + .rename(from: .inbox, to: .init("other"), parameters: ["test": nil]), + #"RENAME "INBOX" "other" (test)"# + ), + + // listIndependent: select options and return options combinations + CommandEncodeFixture.command( + .listIndependent([.remote], reference: .inbox, .mailbox("*"), [.children]), + #"LIST(REMOTE) "INBOX" "*" RETURN (CHILDREN)"# + ), + CommandEncodeFixture.command( + .listIndependent([.specialUse], reference: .inbox, .mailbox("*"), []), + #"LIST(SPECIAL-USE) "INBOX" "*""# + ), + CommandEncodeFixture.command( + .listIndependent([.remote, .specialUse], reference: .inbox, .mailbox("*"), [.children]), + #"LIST(REMOTE SPECIAL-USE) "INBOX" "*" RETURN (CHILDREN)"# + ), + CommandEncodeFixture.command( + .listIndependent([], reference: .inbox, .mailbox("*"), [.children]), + #"LIST "INBOX" "*" RETURN (CHILDREN)"# + ), + CommandEncodeFixture.command( + .listIndependent([], reference: .inbox, .mailbox("*"), []), + #"LIST "INBOX" "*""# + ), + + // authenticate with initial response + CommandEncodeFixture.command( + .authenticate(mechanism: .gssAPI, initialResponse: .init(ByteBuffer(string: "hey"))), + "AUTHENTICATE GSSAPI aGV5" + ), + CommandEncodeFixture.command( + .authenticate(mechanism: .gssAPI, initialResponse: .empty), + "AUTHENTICATE GSSAPI =" + ), + + // enable + CommandEncodeFixture.command(.enable([.binary]), "ENABLE BINARY"), + CommandEncodeFixture.command(.enable([.binary, .acl]), "ENABLE BINARY ACL"), + + // setQuota + CommandEncodeFixture.command( + .setQuota(.init("ROOT"), [.init(resourceName: "STORAGE", limit: 512)]), + #"SETQUOTA "ROOT" (STORAGE 512)"# + ), + CommandEncodeFixture.command( + .setQuota( + .init(""), + [.init(resourceName: "STORAGE", limit: 0), .init(resourceName: "BANDWIDTH", limit: 99)] + ), + #"SETQUOTA "" (STORAGE 0 BANDWIDTH 99)"# + ), + + // store with modifiers (covers write(if: modifiers.count >= 1) branch) + CommandEncodeFixture.command( + .store( + .set([1]), + [.unchangedSince(.init(modificationSequence: 5))], + .flags(.add(silent: false, list: [.seen])) + ), + "STORE 1 (UNCHANGEDSINCE 5) +FLAGS (\\Seen)" + ), + CommandEncodeFixture.command( + .uidStore( + .set(.init(range: 1...5)), + [.unchangedSince(.init(modificationSequence: 10))], + .flags(.remove(silent: true, list: [.answered])) + ), + "UID STORE 1:5 (UNCHANGEDSINCE 10) -FLAGS.SILENT (\\Answered)" + ), ]) func encode(_ fixture: CommandEncodeFixture) { fixture.checkEncoding() } + @Test("Command debugDescription") + func commandDebugDescription() { + #expect(Command.noop.debugDescription == "NOOP") + #expect(Command.capability.debugDescription == "CAPABILITY") + #expect(Command.select(.inbox, []).debugDescription == "SELECT \"INBOX\"") + } + + @Test("authenticate with initialResponse in loggingMode") + func authenticateWithInitialResponseLoggingMode() { + var buffer = CommandEncodeBuffer( + buffer: ByteBufferAllocator().buffer(capacity: 64), + capabilities: [], + loggingMode: true + ) + _ = buffer.writeCommand(.authenticate(mechanism: .gssAPI, initialResponse: .init(ByteBuffer(string: "secret")))) + #expect(String(buffer: buffer.buffer.nextChunk().bytes) == "AUTHENTICATE GSSAPI ∅") + } + + @Test("UID convenience functions return nil for empty UIDSet") + func uidConvenienceFunctionsReturnNilForEmpty() { + #expect(Command.uidMove(messages: UIDSet(), mailbox: .inbox) == nil) + #expect(Command.uidCopy(messages: UIDSet(), mailbox: .inbox) == nil) + #expect(Command.uidFetch(messages: UIDSet(), attributes: [.flags], modifiers: []) == nil) + #expect( + Command.uidStore(messages: UIDSet(), modifiers: [], data: .flags(.add(silent: false, list: [.seen]))) == nil + ) + #expect(Command.uidExpunge(messages: UIDSet(), mailbox: .inbox) == nil) + } + + @Test("UID convenience functions return command for non-empty UIDSet") + func uidConvenienceFunctionsReturnCommandForNonEmpty() { + #expect(Command.uidMove(messages: [1...10], mailbox: .inbox) != nil) + #expect(Command.uidCopy(messages: [1...10], mailbox: .inbox) != nil) + #expect(Command.uidFetch(messages: [1...10], attributes: [.flags], modifiers: []) != nil) + #expect( + Command.uidStore(messages: [1...10], modifiers: [], data: .flags(.add(silent: false, list: [.seen]))) != nil + ) + #expect(Command.uidExpunge(messages: [1...10], mailbox: .inbox) != nil) + } + @Test(arguments: [ ParseFixture.command("CAPABILITY", expected: .success(.capability)), ParseFixture.command("LOGOUT", expected: .success(.logout)), @@ -244,6 +359,12 @@ struct CommandTypeTests { "RENAME box5 box6 (test)", expected: .success(.rename(from: .init("box5"), to: .init("box6"), parameters: ["test": nil])) ), + ParseFixture.command( + "RENAME box5 box6 (test1 test2)", + expected: .success( + .rename(from: .init("box5"), to: .init("box6"), parameters: ["test1": nil, "test2": nil]) + ) + ), ParseFixture.command("SELECT INBOX", expected: .success(.select(.inbox, []))), ParseFixture.command("STATUS INBOX (SIZE)", expected: .success(.status(.inbox, [.size]))), ParseFixture.command("SUBSCRIBE INBOX", expected: .success(.subscribe(.inbox))), @@ -314,543 +435,694 @@ struct CommandTypeTests { } } - @Test(arguments: [ - ParseFixture.idSuffix(" ()", expected: .success(.id([:]))), - ParseFixture.idSuffix(" nil", expected: .success(.id([:]))), - ParseFixture.idSuffix(#" ("name" "some")"#, expected: .success(.id(["name": "some"]))), - ParseFixture.idSuffix(#" ("k1" "v1" "k2" "v2")"#, expected: .success(.id(["k1": "v1", "k2": "v2"]))), - ParseFixture.idSuffix(" ~", "", expected: .failure), - ParseFixture.idSuffix(" []", "", expected: .failure), - ParseFixture.idSuffix(" (\"name\"", "", expected: .incompleteMessage), - ParseFixture.idSuffix(" (\"name\" \"some\"", "", expected: .incompleteMessage), - ]) + @Test( + "parse ID suffix", + arguments: [ + ParseFixture.idSuffix(" ()", expected: .success(.id([:]))), + ParseFixture.idSuffix(" nil", expected: .success(.id([:]))), + ParseFixture.idSuffix(#" ("name" "some")"#, expected: .success(.id(["name": "some"]))), + ParseFixture.idSuffix(#" ("k1" "v1" "k2" "v2")"#, expected: .success(.id(["k1": "v1", "k2": "v2"]))), + ParseFixture.idSuffix(" ~", "", expected: .failure), + ParseFixture.idSuffix(" []", "", expected: .failure), + ParseFixture.idSuffix(" (\"name\"", "", expected: .incompleteMessage), + ParseFixture.idSuffix(" (\"name\" \"some\"", "", expected: .incompleteMessage), + ] + ) func parseIdSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.enableSuffix(" ACL", expected: .success(.enable([.acl]))), - ParseFixture.enableSuffix(" ACL BINARY CHILDREN", expected: .success(.enable([.acl, .binary, .children]))), - ParseFixture.enableSuffix(" (ACL)", expected: .failure), - ParseFixture.enableSuffix(" ACL", "", expected: .incompleteMessage), - ]) + @Test( + "parse ENABLE suffix", + arguments: [ + ParseFixture.enableSuffix(" ACL", expected: .success(.enable([.acl]))), + ParseFixture.enableSuffix(" ACL BINARY CHILDREN", expected: .success(.enable([.acl, .binary, .children]))), + ParseFixture.enableSuffix(" (ACL)", expected: .failure), + ParseFixture.enableSuffix(" ACL", "", expected: .incompleteMessage), + ] + ) func parseEnableSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.getMetadataSuffix( - " INBOX a", - " ", - expected: .success(.getMetadata(options: [], mailbox: .inbox, entries: ["a"])) - ), - ParseFixture.getMetadataSuffix( - " (MAXSIZE 123) INBOX (a b)", - " ", - expected: .success(.getMetadata(options: [.maxSize(123)], mailbox: .inbox, entries: ["a", "b"])) - ), - ParseFixture.getMetadataSuffix(" (MAXSIZE 123 rogue) INBOX", expected: .failure), - ParseFixture.getMetadataSuffix(" (key", "", expected: .incompleteMessage), - ParseFixture.getMetadataSuffix(" (key value", "", expected: .incompleteMessage), - ParseFixture.getMetadataSuffix(" (MAXSIZE 123) INBOX", "", expected: .incompleteMessage), - ]) + @Test( + "parse GETMETADATA suffix", + arguments: [ + ParseFixture.getMetadataSuffix( + " INBOX a", + " ", + expected: .success(.getMetadata(options: [], mailbox: .inbox, entries: ["a"])) + ), + ParseFixture.getMetadataSuffix( + " (MAXSIZE 123) INBOX (a b)", + " ", + expected: .success(.getMetadata(options: [.maxSize(123)], mailbox: .inbox, entries: ["a", "b"])) + ), + ParseFixture.getMetadataSuffix(" (MAXSIZE 123 rogue) INBOX", expected: .failure), + ParseFixture.getMetadataSuffix(" (key", "", expected: .incompleteMessage), + ParseFixture.getMetadataSuffix(" (key value", "", expected: .incompleteMessage), + ParseFixture.getMetadataSuffix(" (MAXSIZE 123) INBOX", "", expected: .incompleteMessage), + ] + ) func parseGetMetadataSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.setMetadataSuffix( - " INBOX (a NIL)", - " ", - expected: .success(.setMetadata(mailbox: .inbox, entries: ["a": .init(nil)])) - ), - ParseFixture.setMetadataSuffix(" (a NIL)", "", expected: .failure), - ParseFixture.setMetadataSuffix(" INBOX", "", expected: .incompleteMessage), - ParseFixture.setMetadataSuffix(" INBOX (", "", expected: .incompleteMessage), - ParseFixture.setMetadataSuffix(" INBOX (a", "", expected: .incompleteMessage), - ]) + @Test( + "parse SETMETADATA suffix", + arguments: [ + ParseFixture.setMetadataSuffix( + " INBOX (a NIL)", + " ", + expected: .success(.setMetadata(mailbox: .inbox, entries: ["a": .init(nil)])) + ), + ParseFixture.setMetadataSuffix(" (a NIL)", "", expected: .failure), + ParseFixture.setMetadataSuffix(" INBOX", "", expected: .incompleteMessage), + ParseFixture.setMetadataSuffix(" INBOX (", "", expected: .incompleteMessage), + ParseFixture.setMetadataSuffix(" INBOX (a", "", expected: .incompleteMessage), + ] + ) func parseSetMetadataSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.resetKeySuffix("", expected: .success(.resetKey(mailbox: nil, mechanisms: []))), - ParseFixture.resetKeySuffix(" INBOX", expected: .success(.resetKey(mailbox: .inbox, mechanisms: []))), - ParseFixture.resetKeySuffix( - " INBOX INTERNAL", - expected: .success(.resetKey(mailbox: .inbox, mechanisms: [.internal])) - ), - ParseFixture.resetKeySuffix( - " INBOX INTERNAL test", - expected: .success(.resetKey(mailbox: .inbox, mechanisms: [.internal, .init("test")])) - ), - ParseFixture.resetKeySuffix(" INBOX", "", expected: .incompleteMessage), - ParseFixture.resetKeySuffix(" INBOX INTERNAL", "", expected: .incompleteMessage), - ParseFixture.resetKeySuffix(" INBOX INTERNAL test", "", expected: .incompleteMessage), - ]) + @Test( + "parse RESETKEY suffix", + arguments: [ + ParseFixture.resetKeySuffix("", expected: .success(.resetKey(mailbox: nil, mechanisms: []))), + ParseFixture.resetKeySuffix(" INBOX", expected: .success(.resetKey(mailbox: .inbox, mechanisms: []))), + ParseFixture.resetKeySuffix( + " INBOX INTERNAL", + expected: .success(.resetKey(mailbox: .inbox, mechanisms: [.internal])) + ), + ParseFixture.resetKeySuffix( + " INBOX INTERNAL test", + expected: .success(.resetKey(mailbox: .inbox, mechanisms: [.internal, .init("test")])) + ), + ParseFixture.resetKeySuffix(" INBOX", "", expected: .incompleteMessage), + ParseFixture.resetKeySuffix(" INBOX INTERNAL", "", expected: .incompleteMessage), + ParseFixture.resetKeySuffix(" INBOX INTERNAL test", "", expected: .incompleteMessage), + ] + ) func parseResetKeySuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.genURLAuthSuffix( - " test INTERNAL", - expected: .success(.generateAuthorizedURL([.init(urlRump: "test", mechanism: .internal)])) - ), - ParseFixture.genURLAuthSuffix( - " test INTERNAL test2 INTERNAL", - expected: .success( - .generateAuthorizedURL([ - .init(urlRump: "test", mechanism: .internal), .init(urlRump: "test2", mechanism: .internal), - ]) - ) - ), - ParseFixture.genURLAuthSuffix(" \\", "", expected: .failure), - ParseFixture.genURLAuthSuffix(" ", "", expected: .incompleteMessage), - ParseFixture.genURLAuthSuffix(" test", "", expected: .incompleteMessage), - ParseFixture.genURLAuthSuffix(" test internal", "", expected: .incompleteMessage), - ]) + @Test( + "parse GENURLAUTH suffix", + arguments: [ + ParseFixture.genURLAuthSuffix( + " test INTERNAL", + expected: .success(.generateAuthorizedURL([.init(urlRump: "test", mechanism: .internal)])) + ), + ParseFixture.genURLAuthSuffix( + " test INTERNAL test2 INTERNAL", + expected: .success( + .generateAuthorizedURL([ + .init(urlRump: "test", mechanism: .internal), .init(urlRump: "test2", mechanism: .internal), + ]) + ) + ), + ParseFixture.genURLAuthSuffix(" \\", "", expected: .failure), + ParseFixture.genURLAuthSuffix(" ", "", expected: .incompleteMessage), + ParseFixture.genURLAuthSuffix(" test", "", expected: .incompleteMessage), + ParseFixture.genURLAuthSuffix(" test internal", "", expected: .incompleteMessage), + ] + ) func parseGenURLAuthSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.urlFetchSuffix(" test", expected: .success(.urlFetch(["test"]))), - ParseFixture.urlFetchSuffix(" test1 test2", expected: .success(.urlFetch(["test1", "test2"]))), - ParseFixture.urlFetchSuffix(" \\ ", "", expected: .failure), - ParseFixture.urlFetchSuffix(" test", "", expected: .incompleteMessage), - ParseFixture.urlFetchSuffix(" test1 test2 test3", "", expected: .incompleteMessage), - ]) + @Test( + "parse URLFETCH suffix", + arguments: [ + ParseFixture.urlFetchSuffix(" test", expected: .success(.urlFetch(["test"]))), + ParseFixture.urlFetchSuffix(" test1 test2", expected: .success(.urlFetch(["test1", "test2"]))), + ParseFixture.urlFetchSuffix(" \\ ", "", expected: .failure), + ParseFixture.urlFetchSuffix(" test", "", expected: .incompleteMessage), + ParseFixture.urlFetchSuffix(" test1 test2 test3", "", expected: .incompleteMessage), + ] + ) func parseUrlFetchSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.copySuffix(" $ inbox", expected: .success(.copy(.lastCommand, .inbox))), - ParseFixture.copySuffix(" 1 inbox", expected: .success(.copy(.set([1]), .inbox))), - ParseFixture.copySuffix(" 1,5,7 inbox", expected: .success(.copy(.set([1, 5, 7]), .inbox))), - ParseFixture.copySuffix(" 1:100 inbox", expected: .success(.copy(.set([1...100]), .inbox))), - ParseFixture.copySuffix(" a inbox", expected: .failure), - ParseFixture.copySuffix(" 1: inbox", expected: .failure), - ParseFixture.copySuffix(" 1", "", expected: .incompleteMessage), - ParseFixture.copySuffix(" 1 inbox", "", expected: .incompleteMessage), - ]) + @Test( + "parse COPY suffix", + arguments: [ + ParseFixture.copySuffix(" $ inbox", expected: .success(.copy(.lastCommand, .inbox))), + ParseFixture.copySuffix(" 1 inbox", expected: .success(.copy(.set([1]), .inbox))), + ParseFixture.copySuffix(" 1,5,7 inbox", expected: .success(.copy(.set([1, 5, 7]), .inbox))), + ParseFixture.copySuffix(" 1:100 inbox", expected: .success(.copy(.set([1...100]), .inbox))), + ParseFixture.copySuffix(" a inbox", expected: .failure), + ParseFixture.copySuffix(" 1: inbox", expected: .failure), + ParseFixture.copySuffix(" 1", "", expected: .incompleteMessage), + ParseFixture.copySuffix(" 1 inbox", "", expected: .incompleteMessage), + ] + ) func parseCopySuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.deleteSuffix(" INBOX", "\r\n", expected: .success(.delete(.inbox))), - ParseFixture.deleteSuffix(" {5}12345", " ", expected: .failure), - ParseFixture.deleteSuffix(" INBOX", "", expected: .incompleteMessage), - ]) + @Test( + "parse DELETE suffix", + arguments: [ + ParseFixture.deleteSuffix(" INBOX", "\r\n", expected: .success(.delete(.inbox))), + ParseFixture.deleteSuffix(" {5}12345", " ", expected: .failure), + ParseFixture.deleteSuffix(" INBOX", "", expected: .incompleteMessage), + ] + ) func parseDeleteSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.moveSuffix(" $ inbox", expected: .success(.move(.lastCommand, .inbox))), - ParseFixture.moveSuffix(" 1 inbox", expected: .success(.move(.set([1]), .inbox))), - ParseFixture.moveSuffix(" 1,5,7 inbox", expected: .success(.move(.set([1, 5, 7]), .inbox))), - ParseFixture.moveSuffix(" 1:100 inbox", expected: .success(.move(.set([1...100]), .inbox))), - ParseFixture.moveSuffix(" a inbox", expected: .failure), - ParseFixture.moveSuffix(" 1: inbox", expected: .failure), - ParseFixture.moveSuffix(" 1", "", expected: .incompleteMessage), - ParseFixture.moveSuffix(" 1 inbox", "", expected: .incompleteMessage), - ]) + @Test( + "parse MOVE suffix", + arguments: [ + ParseFixture.moveSuffix(" $ inbox", expected: .success(.move(.lastCommand, .inbox))), + ParseFixture.moveSuffix(" 1 inbox", expected: .success(.move(.set([1]), .inbox))), + ParseFixture.moveSuffix(" 1,5,7 inbox", expected: .success(.move(.set([1, 5, 7]), .inbox))), + ParseFixture.moveSuffix(" 1:100 inbox", expected: .success(.move(.set([1...100]), .inbox))), + ParseFixture.moveSuffix(" a inbox", expected: .failure), + ParseFixture.moveSuffix(" 1: inbox", expected: .failure), + ParseFixture.moveSuffix(" 1", "", expected: .incompleteMessage), + ParseFixture.moveSuffix(" 1 inbox", "", expected: .incompleteMessage), + ] + ) func parseMoveSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.searchSuffix(" ALL", expected: .success(.search(key: .all))), - ParseFixture.searchSuffix( - " ALL DELETED FLAGGED", - expected: .success(.search(key: .and([.all, .deleted, .flagged]))) - ), - ParseFixture.searchSuffix(" CHARSET UTF-8 ALL", expected: .success(.search(key: .all, charset: "UTF-8"))), - ParseFixture.searchSuffix(" DELETED", expected: .success(.search(key: .deleted, returnOptions: []))), - ParseFixture.searchSuffix( - " RETURN () DELETED", - expected: .success(.search(key: .deleted, returnOptions: [.all])) - ), - ParseFixture.searchSuffix( - " RETURN (ALL) DELETED", - expected: .success(.search(key: .deleted, returnOptions: [.all])) - ), - ParseFixture.searchSuffix( - " RETURN (ALL COUNT) ANSWERED", - expected: .success(.search(key: .answered, returnOptions: [.all, .count])) - ), - ParseFixture.searchSuffix(" RETURN (MIN) ALL", expected: .success(.search(key: .all, returnOptions: [.min]))), - ParseFixture.searchSuffix( - #" CHARSET UTF-8 (OR FROM "me" FROM "you") (OR NEW UNSEEN)"#, - expected: .success( - .search(key: .and([.or(.from("me"), .from("you")), .or(.new, .unseen)]), charset: "UTF-8") - ) - ), - ParseFixture.searchSuffix( - #" RETURN (MIN MAX) CHARSET UTF-8 OR (FROM "me" FROM "you") (NEW UNSEEN)"#, - expected: .success( - .search( - key: .or(.and([.from("me"), .from("you")]), .and([.new, .unseen])), - charset: "UTF-8", - returnOptions: [.min, .max] + @Test( + "parse SEARCH suffix", + arguments: [ + ParseFixture.searchSuffix(" ALL", expected: .success(.search(key: .all))), + ParseFixture.searchSuffix( + " ALL DELETED FLAGGED", + expected: .success(.search(key: .and([.all, .deleted, .flagged]))) + ), + ParseFixture.searchSuffix(" CHARSET UTF-8 ALL", expected: .success(.search(key: .all, charset: "UTF-8"))), + ParseFixture.searchSuffix(" DELETED", expected: .success(.search(key: .deleted, returnOptions: []))), + ParseFixture.searchSuffix( + " RETURN () DELETED", + expected: .success(.search(key: .deleted, returnOptions: [.all])) + ), + ParseFixture.searchSuffix( + " RETURN (ALL) DELETED", + expected: .success(.search(key: .deleted, returnOptions: [.all])) + ), + ParseFixture.searchSuffix( + " RETURN (ALL COUNT) ANSWERED", + expected: .success(.search(key: .answered, returnOptions: [.all, .count])) + ), + ParseFixture.searchSuffix( + " RETURN (MIN) ALL", + expected: .success(.search(key: .all, returnOptions: [.min])) + ), + ParseFixture.searchSuffix( + #" CHARSET UTF-8 (OR FROM "me" FROM "you") (OR NEW UNSEEN)"#, + expected: .success( + .search(key: .and([.or(.from("me"), .from("you")), .or(.new, .unseen)]), charset: "UTF-8") ) - ) - ), - ]) + ), + ParseFixture.searchSuffix( + #" RETURN (MIN MAX) CHARSET UTF-8 OR (FROM "me" FROM "you") (NEW UNSEEN)"#, + expected: .success( + .search( + key: .or(.and([.from("me"), .from("you")]), .and([.new, .unseen])), + charset: "UTF-8", + returnOptions: [.min, .max] + ) + ) + ), + ParseFixture.searchSuffix( + " (ALL SEEN)", + expected: .success(.search(key: .and([.all, .seen]))) + ), + ] + ) func parseSearchSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.esearchSuffix(" ALL", expected: .success(.extendedSearch(.init(key: .all)))), - ParseFixture.esearchSuffix( - " IN (mailboxes \"folder1\" subtree \"folder2\") unseen", - expected: .success( - .extendedSearch( - ExtendedSearchOptions( - key: .unseen, - charset: nil, - returnOptions: [], - sourceOptions: ExtendedSearchSourceOptions(sourceMailbox: [ - .mailboxes(Mailboxes([MailboxName("folder1")])!), - .subtree(Mailboxes([MailboxName("folder2")])!), - ]) + @Test( + "parse ESEARCH suffix", + arguments: [ + ParseFixture.esearchSuffix(" ALL", expected: .success(.extendedSearch(.init(key: .all)))), + ParseFixture.esearchSuffix( + " IN (mailboxes \"folder1\" subtree \"folder2\") unseen", + expected: .success( + .extendedSearch( + ExtendedSearchOptions( + key: .unseen, + charset: nil, + returnOptions: [], + sourceOptions: ExtendedSearchSourceOptions(sourceMailbox: [ + .mailboxes(Mailboxes([MailboxName("folder1")])!), + .subtree(Mailboxes([MailboxName("folder2")])!), + ]) + ) ) ) - ) - ), - ParseFixture.esearchSuffix(" IN (mailboxes ", "", expected: .incompleteMessage), - ]) + ), + ParseFixture.esearchSuffix(" IN (mailboxes ", "", expected: .incompleteMessage), + ] + ) func parseEsearchSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.storeSuffix( - " 1 +FLAGS \\answered", - expected: .success(.store(.set([1]), [], .flags(.add(silent: false, list: [.answered])))) - ), - ParseFixture.storeSuffix( - " 1 (label) -FLAGS \\seen", - expected: .success( - .store( - .set([1]), - [.other(.init(key: "label", value: nil))], - .flags(.remove(silent: false, list: [.seen])) + @Test( + "parse STORE suffix", + arguments: [ + ParseFixture.storeSuffix( + " 1 +FLAGS \\answered", + expected: .success(.store(.set([1]), [], .flags(.add(silent: false, list: [.answered])))) + ), + ParseFixture.storeSuffix( + " 1 (label) -FLAGS \\seen", + expected: .success( + .store( + .set([1]), + [.other(.init(key: "label", value: nil))], + .flags(.remove(silent: false, list: [.seen])) + ) ) - ) - ), - ParseFixture.storeSuffix( - " 1 (label UNCHANGEDSINCE 5) -FLAGS \\seen", - expected: .success( - .store( - .set([1]), - [.other(.init(key: "label", value: nil)), .unchangedSince(.init(modificationSequence: 5))], - .flags(.remove(silent: false, list: [.seen])) + ), + ParseFixture.storeSuffix( + " 1 (label UNCHANGEDSINCE 5) -FLAGS \\seen", + expected: .success( + .store( + .set([1]), + [.other(.init(key: "label", value: nil)), .unchangedSince(.init(modificationSequence: 5))], + .flags(.remove(silent: false, list: [.seen])) + ) ) - ) - ), - ParseFixture.storeSuffix(" +FLAGS \\answered", expected: .failure), - ParseFixture.storeSuffix(" ", "", expected: .incompleteMessage), - ParseFixture.storeSuffix(" 1 ", "", expected: .incompleteMessage), - ]) + ), + ParseFixture.storeSuffix(" +FLAGS \\answered", expected: .failure), + ParseFixture.storeSuffix(" ", "", expected: .incompleteMessage), + ParseFixture.storeSuffix(" 1 ", "", expected: .incompleteMessage), + ] + ) func parseStoreSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.examineSuffix("EXAMINE inbox", expected: .success(.examine(.inbox, []))), - ParseFixture.examineSuffix("examine inbox", expected: .success(.examine(.inbox, []))), - ParseFixture.examineSuffix( - "EXAMINE inbox (number)", - expected: .success(.examine(.inbox, [.basic(.init(key: "number", value: nil))])) - ), - ]) + @Test( + "parse EXAMINE suffix", + arguments: [ + ParseFixture.examineSuffix("EXAMINE inbox", expected: .success(.examine(.inbox, []))), + ParseFixture.examineSuffix("examine inbox", expected: .success(.examine(.inbox, []))), + ParseFixture.examineSuffix( + "EXAMINE inbox (number)", + expected: .success(.examine(.inbox, [.basic(.init(key: "number", value: nil))])) + ), + ] + ) func parseExamineSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.listSuffix( - #" "" """#, - expected: .success(.list(nil, reference: MailboxName(""), .mailbox(""), [])) - ) - ]) + @Test( + "parse LIST suffix", + arguments: [ + ParseFixture.listSuffix( + #" "" """#, + expected: .success(.list(nil, reference: MailboxName(""), .mailbox(""), [])) + ), + // with return options only + ParseFixture.listSuffix( + #" "" "" RETURN (CHILDREN)"#, + expected: .success(.list(nil, reference: MailboxName(""), .mailbox(""), [.children])) + ), + ParseFixture.listSuffix( + #" "" "" RETURN (CHILDREN SUBSCRIBED)"#, + expected: .success(.list(nil, reference: MailboxName(""), .mailbox(""), [.children, .subscribed])) + ), + // with select options (triggers parseListSelectOptions) + ParseFixture.listSuffix( + " (SUBSCRIBED) \"\" \"\"", + expected: .success( + .list(.init(baseOption: .subscribed, options: []), reference: MailboxName(""), .mailbox(""), []) + ) + ), + ParseFixture.listSuffix( + " (REMOTE SUBSCRIBED) \"\" \"\"", + expected: .success( + .list( + .init(baseOption: .subscribed, options: [.remote]), + reference: MailboxName(""), + .mailbox(""), + [] + ) + ) + ), + ParseFixture.listSuffix( + " (SPECIAL-USE SUBSCRIBED) INBOX * RETURN (CHILDREN)", + expected: .success( + .list( + .init(baseOption: .subscribed, options: [.specialUse]), + reference: .inbox, + .mailbox("*"), + [.children] + ) + ) + ), + ParseFixture.listSuffix( + " (RECURSIVEMATCH SUBSCRIBED) \"\" \"\"", + expected: .success( + .list( + .init(baseOption: .subscribed, options: [.recursiveMatch]), + reference: MailboxName(""), + .mailbox(""), + [] + ) + ) + ), + ] + ) func parseListSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.LSUBSuffix( - " inbox someList", - " ", - expected: .success(.lsub(reference: .inbox, pattern: "someList")) - ), - ParseFixture.LSUBSuffix( - " \"inbox\" \"someList\"", - " ", - expected: .success(.lsub(reference: .inbox, pattern: "someList")) - ), - ParseFixture.LSUBSuffix(" {5}inbox", "", expected: .failure), - ParseFixture.LSUBSuffix(" inbox", "", expected: .incompleteMessage), - ParseFixture.LSUBSuffix(" inbox list", "", expected: .incompleteMessage), - ]) + @Test( + "parse LSUB suffix", + arguments: [ + ParseFixture.LSUBSuffix( + " inbox someList", + " ", + expected: .success(.lsub(reference: .inbox, pattern: "someList")) + ), + ParseFixture.LSUBSuffix( + " \"inbox\" \"someList\"", + " ", + expected: .success(.lsub(reference: .inbox, pattern: "someList")) + ), + ParseFixture.LSUBSuffix(" {5}inbox", "", expected: .failure), + ParseFixture.LSUBSuffix(" inbox", "", expected: .incompleteMessage), + ParseFixture.LSUBSuffix(" inbox list", "", expected: .incompleteMessage), + ] + ) func parseLSUBSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.renameSuffix( - " box1 box2", - expected: .success( - .rename(from: .init(.init(string: "box1")), to: .init(.init(string: "box2")), parameters: [:]) - ) - ), - ParseFixture.renameSuffix(" {2}b1 {2}b2", "", expected: .failure), - ParseFixture.renameSuffix(" {2}\r\nb1 {2}b2", "", expected: .failure), - ParseFixture.renameSuffix(" box1", "", expected: .incompleteMessage), - ParseFixture.renameSuffix(" box1 box2", "", expected: .incompleteMessage), - ]) + @Test( + "parse RENAME suffix", + arguments: [ + ParseFixture.renameSuffix( + " box1 box2", + expected: .success( + .rename(from: .init(.init(string: "box1")), to: .init(.init(string: "box2")), parameters: [:]) + ) + ), + ParseFixture.renameSuffix(" {2}b1 {2}b2", "", expected: .failure), + ParseFixture.renameSuffix(" {2}\r\nb1 {2}b2", "", expected: .failure), + ParseFixture.renameSuffix(" box1", "", expected: .incompleteMessage), + ParseFixture.renameSuffix(" box1 box2", "", expected: .incompleteMessage), + ] + ) func parseRenameSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.selectSuffix(" inbox", expected: .success(.select(.inbox, []))), - ParseFixture.selectSuffix( - " inbox (some1)", - expected: .success(.select(.inbox, [.basic(.init(key: "some1", value: nil))])) - ), - ParseFixture.selectSuffix(" ", expected: .failure), - ParseFixture.selectSuffix(" ", "", expected: .incompleteMessage), - ]) + @Test( + "parse SELECT suffix", + arguments: [ + ParseFixture.selectSuffix(" inbox", expected: .success(.select(.inbox, []))), + ParseFixture.selectSuffix( + " inbox (some1)", + expected: .success(.select(.inbox, [.basic(.init(key: "some1", value: nil))])) + ), + ParseFixture.selectSuffix(" ", expected: .failure), + ParseFixture.selectSuffix(" ", "", expected: .incompleteMessage), + ] + ) func parseSelectSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.statusSuffix( - " inbox (messages unseen)", - "\r\n", - expected: .success(.status(.inbox, [.messageCount, .unseenCount])) - ), - ParseFixture.statusSuffix( - " Deleted (messages unseen HIGHESTMODSEQ)", - "\r\n", - expected: .success( - .status(MailboxName("Deleted"), [.messageCount, .unseenCount, .highestModificationSequence]) - ) - ), - ParseFixture.statusSuffix(" inbox (messages unseen", "\r\n", expected: .failure), - ParseFixture.statusSuffix("", "", expected: .incompleteMessage), - ParseFixture.statusSuffix(" Deleted (messages ", "", expected: .incompleteMessage), - ]) + @Test( + "parse STATUS suffix", + arguments: [ + ParseFixture.statusSuffix( + " inbox (messages unseen)", + "\r\n", + expected: .success(.status(.inbox, [.messageCount, .unseenCount])) + ), + ParseFixture.statusSuffix( + " Deleted (messages unseen HIGHESTMODSEQ)", + "\r\n", + expected: .success( + .status(MailboxName("Deleted"), [.messageCount, .unseenCount, .highestModificationSequence]) + ) + ), + ParseFixture.statusSuffix(" inbox (messages unseen", "\r\n", expected: .failure), + ParseFixture.statusSuffix("", "", expected: .incompleteMessage), + ParseFixture.statusSuffix(" Deleted (messages ", "", expected: .incompleteMessage), + ] + ) func parseStatusSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.subscribeSuffix(" INBOX", expected: .success(.subscribe(.inbox))), - ParseFixture.subscribeSuffix("inbox", "", expected: .failure), - ParseFixture.subscribeSuffix(" inbox", "", expected: .incompleteMessage), - ]) + @Test( + "parse SUBSCRIBE suffix", + arguments: [ + ParseFixture.subscribeSuffix(" INBOX", expected: .success(.subscribe(.inbox))), + ParseFixture.subscribeSuffix("inbox", "", expected: .failure), + ParseFixture.subscribeSuffix(" inbox", "", expected: .incompleteMessage), + ] + ) func parseSubscribeSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.unsubscribeSuffix(" inbox", expected: .success(.unsubscribe(.inbox))), - ParseFixture.unsubscribeSuffix("inbox", "", expected: .failure), - ParseFixture.unsubscribeSuffix(" inbox", "", expected: .incompleteMessage), - ]) + @Test( + "parse UNSUBSCRIBE suffix", + arguments: [ + ParseFixture.unsubscribeSuffix(" inbox", expected: .success(.unsubscribe(.inbox))), + ParseFixture.unsubscribeSuffix("inbox", "", expected: .failure), + ParseFixture.unsubscribeSuffix(" inbox", "", expected: .incompleteMessage), + ] + ) func parseUnsubscribeSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.uidSuffix(" EXPUNGE 1", "\r\n", expected: .success(.uidExpunge(.set([1])))), - ParseFixture.uidSuffix(" COPY 1 Inbox", "\r\n", expected: .success(.uidCopy(.set([1]), .inbox))), - ParseFixture.uidSuffix(" FETCH 1 FLAGS", "\r\n", expected: .success(.uidFetch(.set([1]), [.flags], []))), - ParseFixture.uidSuffix( - " SEARCH CHARSET UTF8 ALL", - "\r\n", - expected: .success(.uidSearch(key: .all, charset: "UTF8")) - ), - ParseFixture.uidSuffix( - " STORE 1 +FLAGS (Test)", - "\r\n", - expected: .success(.uidStore(.set([1]), [], .flags(.add(silent: false, list: ["Test"])))) - ), - ParseFixture.uidSuffix( - " STORE 1 (UNCHANGEDSINCE 5 test) +FLAGS (Test)", - "\r\n", - expected: .success( - .uidStore( - .set([1]), - [.unchangedSince(.init(modificationSequence: 5)), .other(.init(key: "test", value: nil))], - .flags(.add(silent: false, list: ["Test"])) + @Test( + "parse UID suffix", + arguments: [ + ParseFixture.uidSuffix(" EXPUNGE 1", "\r\n", expected: .success(.uidExpunge(.set([1])))), + ParseFixture.uidSuffix(" COPY 1 Inbox", "\r\n", expected: .success(.uidCopy(.set([1]), .inbox))), + ParseFixture.uidSuffix(" FETCH 1 FLAGS", "\r\n", expected: .success(.uidFetch(.set([1]), [.flags], []))), + ParseFixture.uidSuffix( + " SEARCH CHARSET UTF8 ALL", + "\r\n", + expected: .success(.uidSearch(key: .all, charset: "UTF8")) + ), + ParseFixture.uidSuffix( + " STORE 1 +FLAGS (Test)", + "\r\n", + expected: .success(.uidStore(.set([1]), [], .flags(.add(silent: false, list: ["Test"])))) + ), + ParseFixture.uidSuffix( + " STORE 1 (UNCHANGEDSINCE 5 test) +FLAGS (Test)", + "\r\n", + expected: .success( + .uidStore( + .set([1]), + [.unchangedSince(.init(modificationSequence: 5)), .other(.init(key: "test", value: nil))], + .flags(.add(silent: false, list: ["Test"])) + ) ) - ) - ), - ParseFixture.uidSuffix( - " COPY * Inbox", - "\r\n", - expected: .success(.uidCopy(.set([MessageIdentifierRange(.max)]), .inbox)) - ), - ParseFixture.uidSuffix("UID RENAME inbox other", " ", expected: .failure), - ]) + ), + ParseFixture.uidSuffix( + " COPY * Inbox", + "\r\n", + expected: .success(.uidCopy(.set([MessageIdentifierRange(.max)]), .inbox)) + ), + ParseFixture.uidSuffix("UID RENAME inbox other", " ", expected: .failure), + ] + ) func parseUidSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.fetchSuffix(" 1:3 ALL", expected: .success(.fetch(.set([1...3]), .all, []))), - ParseFixture.fetchSuffix(" 2:4 FULL", expected: .success(.fetch(.set([2...4]), .full, []))), - ParseFixture.fetchSuffix(" 3:5 FAST", expected: .success(.fetch(.set([3...5]), .fast, []))), - ParseFixture.fetchSuffix(" 4:6 ENVELOPE", expected: .success(.fetch(.set([4...6]), [.envelope], []))), - ParseFixture.fetchSuffix( - " 5:7 (ENVELOPE FLAGS)", - expected: .success(.fetch(.set([5...7]), [.envelope, .flags], [])) - ), - ParseFixture.fetchSuffix( - " 3:5 FAST (name)", - expected: .success(.fetch(.set([3...5]), .fast, [.other(.init(key: "name", value: nil))])) - ), - ParseFixture.fetchSuffix( - " 1 BODY[TEXT]", - expected: .success(.fetch(.set([1]), [.bodySection(peek: false, .init(kind: .text), nil)], [])) - ), - ]) + @Test( + "parse FETCH suffix", + arguments: [ + ParseFixture.fetchSuffix(" 1:3 ALL", expected: .success(.fetch(.set([1...3]), .all, []))), + ParseFixture.fetchSuffix(" 2:4 FULL", expected: .success(.fetch(.set([2...4]), .full, []))), + ParseFixture.fetchSuffix(" 3:5 FAST", expected: .success(.fetch(.set([3...5]), .fast, []))), + ParseFixture.fetchSuffix(" 4:6 ENVELOPE", expected: .success(.fetch(.set([4...6]), [.envelope], []))), + ParseFixture.fetchSuffix( + " 5:7 (ENVELOPE FLAGS)", + expected: .success(.fetch(.set([5...7]), [.envelope, .flags], [])) + ), + ParseFixture.fetchSuffix( + " 3:5 FAST (name)", + expected: .success(.fetch(.set([3...5]), .fast, [.other(.init(key: "name", value: nil))])) + ), + ParseFixture.fetchSuffix( + " 1 BODY[TEXT]", + expected: .success(.fetch(.set([1]), [.bodySection(peek: false, .init(kind: .text), nil)], [])) + ), + ] + ) func parseFetchSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.loginSuffix( - " email password", - expected: .success(.login(username: "email", password: "password")) - ), - ParseFixture.loginSuffix( - " \"email\" \"password\"", - expected: .success(.login(username: "email", password: "password")) - ), - ParseFixture.loginSuffix( - " {5}\r\nemail {8}\r\npassword", - expected: .success(.login(username: "email", password: "password")) - ), - ParseFixture.loginSuffix("email password", "", expected: .failure), - ParseFixture.loginSuffix(" email", "", expected: .incompleteMessage), - ParseFixture.loginSuffix(" email password", "", expected: .incompleteMessage), - ParseFixture.loginSuffix(" {5}\r\nemail {8}", "", expected: .incompleteMessage), - ]) + @Test( + "parse LOGIN suffix", + arguments: [ + ParseFixture.loginSuffix( + " email password", + expected: .success(.login(username: "email", password: "password")) + ), + ParseFixture.loginSuffix( + " \"email\" \"password\"", + expected: .success(.login(username: "email", password: "password")) + ), + ParseFixture.loginSuffix( + " {5}\r\nemail {8}\r\npassword", + expected: .success(.login(username: "email", password: "password")) + ), + ParseFixture.loginSuffix("email password", "", expected: .failure), + ParseFixture.loginSuffix(" email", "", expected: .incompleteMessage), + ParseFixture.loginSuffix(" email password", "", expected: .incompleteMessage), + ParseFixture.loginSuffix(" {5}\r\nemail {8}", "", expected: .incompleteMessage), + ] + ) func parseLoginSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.userId("test", " ", expected: .success("test")), - ParseFixture.userId("{4}\r\ntest", " ", expected: .success("test")), - ParseFixture.userId("{4+}\r\ntest", " ", expected: .success("test")), - ParseFixture.userId("\"test\"", " ", expected: .success("test")), - ParseFixture.userId("\\\\", "", expected: .failure), - ParseFixture.userId("aaa", "", expected: .incompleteMessage), - ParseFixture.userId("{1}\r\n", "", expected: .incompleteMessage), - ]) + @Test( + "parse user ID", + arguments: [ + ParseFixture.userId("test", " ", expected: .success("test")), + ParseFixture.userId("{4}\r\ntest", " ", expected: .success("test")), + ParseFixture.userId("{4+}\r\ntest", " ", expected: .success("test")), + ParseFixture.userId("\"test\"", " ", expected: .success("test")), + ParseFixture.userId("\\\\", "", expected: .failure), + ParseFixture.userId("aaa", "", expected: .incompleteMessage), + ParseFixture.userId("{1}\r\n", "", expected: .incompleteMessage), + ] + ) func parseUserId(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.authenticateSuffix( - " GSSAPI", - expected: .success(.authenticate(mechanism: .gssAPI, initialResponse: nil)) - ), - ParseFixture.authenticateSuffix( - " GSSAPI aGV5", - expected: .success(.authenticate(mechanism: .gssAPI, initialResponse: .init(.init(.init(string: "hey"))))) - ), - ParseFixture.authenticateSuffix(" \"GSSAPI\"", "", expected: .failure), - ParseFixture.authenticateSuffix(" gssapi", "", expected: .incompleteMessage), - ]) + @Test( + "parse AUTHENTICATE suffix", + arguments: [ + ParseFixture.authenticateSuffix( + " GSSAPI", + expected: .success(.authenticate(mechanism: .gssAPI, initialResponse: nil)) + ), + ParseFixture.authenticateSuffix( + " GSSAPI aGV5", + expected: .success( + .authenticate(mechanism: .gssAPI, initialResponse: .init(.init(.init(string: "hey")))) + ) + ), + ParseFixture.authenticateSuffix(" \"GSSAPI\"", "", expected: .failure), + ParseFixture.authenticateSuffix(" gssapi", "", expected: .incompleteMessage), + ] + ) func parseAuthenticateSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.createSuffix(" inbox", expected: .success(.create(.inbox, []))), - ParseFixture.createSuffix( - " inbox (some)", - expected: .success(.create(.inbox, [.labelled(.init(key: "some", value: nil))])) - ), - ParseFixture.createSuffix(" inbox (USE (\\All))", expected: .success(.create(.inbox, [.attributes([.all])]))), - ParseFixture.createSuffix( - " inbox (USE (\\All \\Flagged))", - expected: .success(.create(.inbox, [.attributes([.all, .flagged])])) - ), - ParseFixture.createSuffix( - " inbox (USE (\\All \\Flagged) some1 2 USE (\\Sent))", - expected: .success( - .create( - .inbox, - [ - .attributes([.all, .flagged]), .labelled(.init(key: "some1", value: .sequence(.set([2])))), - .attributes([.sent]), - ] + @Test( + "parse CREATE suffix", + arguments: [ + ParseFixture.createSuffix(" inbox", expected: .success(.create(.inbox, []))), + ParseFixture.createSuffix( + " inbox (some)", + expected: .success(.create(.inbox, [.labelled(.init(key: "some", value: nil))])) + ), + ParseFixture.createSuffix( + " inbox (USE (\\All))", + expected: .success(.create(.inbox, [.attributes([.all])])) + ), + ParseFixture.createSuffix( + " inbox (USE (\\All \\Flagged))", + expected: .success(.create(.inbox, [.attributes([.all, .flagged])])) + ), + ParseFixture.createSuffix( + " inbox (USE (\\All \\Flagged) some1 2 USE (\\Sent))", + expected: .success( + .create( + .inbox, + [ + .attributes([.all, .flagged]), .labelled(.init(key: "some1", value: .sequence(.set([2])))), + .attributes([.sent]), + ] + ) ) - ) - ), - ParseFixture.createSuffix(" inbox", "", expected: .incompleteMessage), - ParseFixture.createSuffix(" inbox (USE", "", expected: .incompleteMessage), - ]) + ), + ParseFixture.createSuffix(" inbox", "", expected: .incompleteMessage), + ParseFixture.createSuffix(" inbox (USE", "", expected: .incompleteMessage), + ] + ) func parseCreateSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.getQuotaSuffix(" \"\"", expected: .success(.getQuota(.init("")))), - ParseFixture.getQuotaSuffix(" \"quota\"", expected: .success(.getQuota(.init("quota")))), - ParseFixture.getQuotaSuffix(" {5}quota", expected: .failure), - ParseFixture.getQuotaSuffix(" \"root", "", expected: .incompleteMessage), - ]) + @Test( + "parse GETQUOTA suffix", + arguments: [ + ParseFixture.getQuotaSuffix(" \"\"", expected: .success(.getQuota(.init("")))), + ParseFixture.getQuotaSuffix(" \"quota\"", expected: .success(.getQuota(.init("quota")))), + ParseFixture.getQuotaSuffix(" {5}quota", expected: .failure), + ParseFixture.getQuotaSuffix(" \"root", "", expected: .incompleteMessage), + ] + ) func parseGetQuotaSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.setQuotaSuffix( - #" "" (STORAGE 512)"#, - expected: .success(.setQuota(.init(""), [.init(resourceName: "STORAGE", limit: 512)])) - ), - ParseFixture.setQuotaSuffix( - #" "" (STORAGE 512 BANDWIDTH 123)"#, - expected: .success( - .setQuota( - .init(""), - [.init(resourceName: "STORAGE", limit: 512), .init(resourceName: "BANDWIDTH", limit: 123)] + @Test( + "parse SETQUOTA suffix", + arguments: [ + ParseFixture.setQuotaSuffix( + #" "" (STORAGE 512)"#, + expected: .success(.setQuota(.init(""), [.init(resourceName: "STORAGE", limit: 512)])) + ), + ParseFixture.setQuotaSuffix( + #" "" (STORAGE 512 BANDWIDTH 123)"#, + expected: .success( + .setQuota( + .init(""), + [.init(resourceName: "STORAGE", limit: 512), .init(resourceName: "BANDWIDTH", limit: 123)] + ) ) - ) - ), - ParseFixture.setQuotaSuffix(#" "" STORAGE 512"#, "", expected: .failure), - ParseFixture.setQuotaSuffix(#" ""#, "", expected: .incompleteMessage), - ParseFixture.setQuotaSuffix(#" "root"#, "", expected: .incompleteMessage), - ParseFixture.setQuotaSuffix(#" "root" ("#, "", expected: .incompleteMessage), - ParseFixture.setQuotaSuffix(#" "root" (STORAGE"#, "", expected: .incompleteMessage), - ParseFixture.setQuotaSuffix(#" "root" (STORAGE 123"#, "", expected: .incompleteMessage), - ]) + ), + ParseFixture.setQuotaSuffix(#" "" STORAGE 512"#, "", expected: .failure), + ParseFixture.setQuotaSuffix(#" ""#, "", expected: .incompleteMessage), + ParseFixture.setQuotaSuffix(#" "root"#, "", expected: .incompleteMessage), + ParseFixture.setQuotaSuffix(#" "root" ("#, "", expected: .incompleteMessage), + ParseFixture.setQuotaSuffix(#" "root" (STORAGE"#, "", expected: .incompleteMessage), + ParseFixture.setQuotaSuffix(#" "root" (STORAGE 123"#, "", expected: .incompleteMessage), + ] + ) func parseSetQuotaSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.getQuotaRootSuffix(" INBOX", expected: .success(.getQuotaRoot(.inbox))), - ParseFixture.getQuotaRootSuffix(" \"INBOX\"", expected: .success(.getQuotaRoot(.inbox))), - ParseFixture.getQuotaRootSuffix(" {5}\r\nINBOX", expected: .success(.getQuotaRoot(.inbox))), - ParseFixture.getQuotaRootSuffix(" {5}INBOX", "", expected: .failure), - ParseFixture.getQuotaRootSuffix(" INBOX", "", expected: .incompleteMessage), - ]) + @Test( + "parse GETQUOTAROOT suffix", + arguments: [ + ParseFixture.getQuotaRootSuffix(" INBOX", expected: .success(.getQuotaRoot(.inbox))), + ParseFixture.getQuotaRootSuffix(" \"INBOX\"", expected: .success(.getQuotaRoot(.inbox))), + ParseFixture.getQuotaRootSuffix(" {5}\r\nINBOX", expected: .success(.getQuotaRoot(.inbox))), + ParseFixture.getQuotaRootSuffix(" {5}INBOX", "", expected: .failure), + ParseFixture.getQuotaRootSuffix(" INBOX", "", expected: .incompleteMessage), + ] + ) func parseGetQuotaRootSuffix(_ fixture: ParseFixture) { fixture.checkParsing() } @@ -1292,3 +1564,32 @@ extension CommandEncodeFixture { ) } } + +@Suite("AuthenticationMechanism") +struct AuthenticationMechanismTests { + @Test( + "encode", + arguments: [ + EncodeFixture.authenticationMechanism(.gssAPI, "GSSAPI"), + EncodeFixture.authenticationMechanism(.plain, "PLAIN"), + EncodeFixture.authenticationMechanism(.init("myAuth"), "MYAUTH"), + ] + ) + func encode(_ fixture: EncodeFixture) { + fixture.checkEncoding() + } +} + +extension EncodeFixture { + fileprivate static func authenticationMechanism( + _ input: AuthenticationMechanism, + _ expectedString: String + ) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeAuthenticationMechanism($1) } + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/CommandType/SetQuota+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/CommandType/SetQuota+Tests.swift index 795f719f..f3e58936 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/CommandType/SetQuota+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/CommandType/SetQuota+Tests.swift @@ -18,55 +18,69 @@ import Testing @Suite("Quota Commands") struct QuotaCommandTests { - @Test(arguments: [ - ParseFixture.setQuota( - "SETQUOTA \"\" (STORAGE 512)", - expected: .success(.setQuota(QuotaRoot(""), [QuotaLimit(resourceName: "STORAGE", limit: 512)])) - ), - ParseFixture.setQuota( - "SETQUOTA \"MASSIVE_POOL\" (STORAGE 512)", - expected: .success(.setQuota(QuotaRoot("MASSIVE_POOL"), [QuotaLimit(resourceName: "STORAGE", limit: 512)])) - ), - ParseFixture.setQuota( - "SETQUOTA \"MASSIVE_POOL\" (STORAGE 512 BEANS 50000)", - expected: .success( - .setQuota( - QuotaRoot("MASSIVE_POOL"), - [ - QuotaLimit(resourceName: "STORAGE", limit: 512), - QuotaLimit(resourceName: "BEANS", limit: 50000), - ] + @Test( + "parse SETQUOTA", + arguments: [ + ParseFixture.setQuota( + "SETQUOTA \"\" (STORAGE 512)", + expected: .success(.setQuota(QuotaRoot(""), [QuotaLimit(resourceName: "STORAGE", limit: 512)])) + ), + ParseFixture.setQuota( + "SETQUOTA \"MASSIVE_POOL\" (STORAGE 512)", + expected: .success( + .setQuota(QuotaRoot("MASSIVE_POOL"), [QuotaLimit(resourceName: "STORAGE", limit: 512)]) ) - ) - ), - ParseFixture.setQuota( - "SETQUOTA \"MASSIVE_POOL\" ()", - expected: .success(.setQuota(QuotaRoot("MASSIVE_POOL"), [])) - ), - ParseFixture.setQuota("SETQUOTA \"MASSIVE_POOL\" (STORAGE BEANS)", expected: .failure), - ParseFixture.setQuota("SETQUOTA \"MASSIVE_POOL\" (STORAGE 40M)", expected: .failure), - ParseFixture.setQuota("SETQUOTA \"MASSIVE_POOL\" (STORAGE)", expected: .failure), - ParseFixture.setQuota("SETQUOTA \"MASSIVE_POOL\" (", expected: .failure), - ParseFixture.setQuota("SETQUOTA \"MASSIVE_POOL\"", expected: .failure), - ]) + ), + ParseFixture.setQuota( + "SETQUOTA \"MASSIVE_POOL\" (STORAGE 512 BEANS 50000)", + expected: .success( + .setQuota( + QuotaRoot("MASSIVE_POOL"), + [ + QuotaLimit(resourceName: "STORAGE", limit: 512), + QuotaLimit(resourceName: "BEANS", limit: 50000), + ] + ) + ) + ), + ParseFixture.setQuota( + "SETQUOTA \"MASSIVE_POOL\" ()", + expected: .success(.setQuota(QuotaRoot("MASSIVE_POOL"), [])) + ), + ParseFixture.setQuota("SETQUOTA \"MASSIVE_POOL\" (STORAGE BEANS)", expected: .failure), + ParseFixture.setQuota("SETQUOTA \"MASSIVE_POOL\" (STORAGE 40M)", expected: .failure), + ParseFixture.setQuota("SETQUOTA \"MASSIVE_POOL\" (STORAGE)", expected: .failure), + ParseFixture.setQuota("SETQUOTA \"MASSIVE_POOL\" (", expected: .failure), + ParseFixture.setQuota("SETQUOTA \"MASSIVE_POOL\"", expected: .failure), + ] + ) func parseSetQuota(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.getQuota("GETQUOTA \"\"", expected: .success(.getQuota(QuotaRoot("")))), - ParseFixture.getQuota("GETQUOTA \"MASSIVE_POOL\"", expected: .success(.getQuota(QuotaRoot("MASSIVE_POOL")))), - ParseFixture.getQuota("GETQUOTA", expected: .failure), - ]) + @Test( + "parse GETQUOTA", + arguments: [ + ParseFixture.getQuota("GETQUOTA \"\"", expected: .success(.getQuota(QuotaRoot("")))), + ParseFixture.getQuota( + "GETQUOTA \"MASSIVE_POOL\"", + expected: .success(.getQuota(QuotaRoot("MASSIVE_POOL"))) + ), + ParseFixture.getQuota("GETQUOTA", expected: .failure), + ] + ) func parseGetQuota(_ fixture: ParseFixture) { fixture.checkParsing() } - @Test(arguments: [ - ParseFixture.getQuotaRoot("GETQUOTAROOT INBOX", expected: .success(.getQuotaRoot(MailboxName("INBOX")))), - ParseFixture.getQuotaRoot("GETQUOTAROOT Other", expected: .success(.getQuotaRoot(MailboxName("Other")))), - ParseFixture.getQuotaRoot("GETQUOTAROOT", expected: .failure), - ]) + @Test( + "parse GETQUOTAROOT", + arguments: [ + ParseFixture.getQuotaRoot("GETQUOTAROOT INBOX", expected: .success(.getQuotaRoot(MailboxName("INBOX")))), + ParseFixture.getQuotaRoot("GETQUOTAROOT Other", expected: .success(.getQuotaRoot(MailboxName("Other")))), + ParseFixture.getQuotaRoot("GETQUOTAROOT", expected: .failure), + ] + ) func parseGetQuotaRoot(_ fixture: ParseFixture) { fixture.checkParsing() } diff --git a/Tests/NIOIMAPCoreTests/Grammar/CommandType/TaggedCommand+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/CommandType/TaggedCommand+Tests.swift index 147298f8..7e5bfc6d 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/CommandType/TaggedCommand+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/CommandType/TaggedCommand+Tests.swift @@ -18,17 +18,41 @@ import Testing @Suite("TaggedCommand") struct TaggedCommandTests { - @Test(arguments: [ - ParseFixture.taggedCommand("a CAPABILITY", expected: .success(.init(tag: "a", command: .capability))), - ParseFixture.taggedCommand("1 CAPABILITY", expected: .success(.init(tag: "1", command: .capability))), - ParseFixture.taggedCommand("a1 CAPABILITY", expected: .success(.init(tag: "a1", command: .capability))), - ParseFixture.taggedCommand("(", "CAPABILITY", expected: .failure), - ParseFixture.taggedCommand("a CAPABILITY", "", expected: .incompleteMessage), - ]) + @Test( + "parse", + arguments: [ + ParseFixture.taggedCommand("a CAPABILITY", expected: .success(.init(tag: "a", command: .capability))), + ParseFixture.taggedCommand("1 CAPABILITY", expected: .success(.init(tag: "1", command: .capability))), + ParseFixture.taggedCommand("a1 CAPABILITY", expected: .success(.init(tag: "a1", command: .capability))), + ParseFixture.taggedCommand("(", "CAPABILITY", expected: .failure), + ParseFixture.taggedCommand("a CAPABILITY", "", expected: .incompleteMessage), + ] + ) func parse(_ fixture: ParseFixture) { fixture.checkParsing() } + @Test( + "debug description", + arguments: [ + DebugStringFixture( + sut: .init(tag: "A1", command: .capability), + expected: "A1 CAPABILITY\r\n" + ), + DebugStringFixture( + sut: .init(tag: "A1", command: .select(.inbox)), + expected: "A1 SELECT \"INBOX\"\r\n" + ), + DebugStringFixture( + sut: .init(tag: "A1", command: .login(username: "alice", password: "secret")), + expected: "A1 LOGIN \"alice\" \"secret\"\r\n" + ), + ] + ) + func debugDescription(_ fixture: DebugStringFixture) { + fixture.check() + } + @Test("parse tagged command throws bad command") func parseTaggedCommandThrowsBadCommand() { // Test that the parser error occurs when parsing the command name var buffer1 = TestUtilities.makeParseBuffer(for: "A1 ()\r\n") diff --git a/Tests/NIOIMAPCoreTests/Grammar/ConditionalStore/ConditionalStore+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/ConditionalStore/ConditionalStore+Tests.swift index 2b69b753..2dd20ed0 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/ConditionalStore/ConditionalStore+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/ConditionalStore/ConditionalStore+Tests.swift @@ -42,6 +42,123 @@ struct ConditionalStoreTests { } } +@Suite("LastCommandSet (RFC 5182)") +struct LastCommandSetRFC5182Tests { + @Test( + "encode LastCommandSet", + arguments: [ + EncodeFixture.lastCommandSet(.lastCommand, "$"), + EncodeFixture.lastCommandSet(.range(UID(1)...UID(3)), "1:3"), + EncodeFixture.lastCommandSet(.set(.init(range: .init(UID(5)))), "5"), + ] + ) + func encode(_ fixture: EncodeFixture>) { + fixture.checkEncoding() + } + + @Test( + "parse LastCommandSet", + arguments: [ + ParseFixture.lastCommandSet("$", expected: .success(.lastCommand)), + ParseFixture.lastCommandSet("1:3", expected: .success(.range(UID(1)...UID(3)))), + ParseFixture.lastCommandSet("5", expected: .success(.set(.init(range: .init(UID(5)))))), + ParseFixture.lastCommandSet("", "", expected: .incompleteMessage), + ] + ) + func parse(_ fixture: ParseFixture>) { + fixture.checkParsing() + } +} + +@Suite("LastCommandMessageID (RFC 5182)") +struct LastCommandMessageIDRFC5182Tests { + @Test( + "encode LastCommandMessageID", + arguments: [ + EncodeFixture.lastCommandMessageID(.lastCommand, "$"), + EncodeFixture.lastCommandMessageID(.id(UID(42)), "42"), + ] + ) + func encode(_ fixture: EncodeFixture>) { + fixture.checkEncoding() + } + + @Test( + "parse LastCommandMessageID", + arguments: [ + ParseFixture.lastCommandMessageID("$", expected: .success(.lastCommand)), + ParseFixture.lastCommandMessageID("42", expected: .success(.id(UID(42)))), + ParseFixture.lastCommandMessageID("", "", expected: .incompleteMessage), + ] + ) + func parse(_ fixture: ParseFixture>) { + fixture.checkParsing() + } +} + +@Suite("StoreModifier") +struct StoreModifierTests { + @Test(arguments: [ + EncodeFixture.storeModifier( + .unchangedSince(.init(modificationSequence: 12345)), + "UNCHANGEDSINCE 12345" + ), + EncodeFixture.storeModifier( + .other(.init(key: "MYEXT", value: nil)), + "MYEXT" + ), + ]) + func encode(_ fixture: EncodeFixture) { + fixture.checkEncoding() + } + + @Test( + "parse StoreModifier", + arguments: [ + ParseFixture.storeModifier( + "UNCHANGEDSINCE 12345", + expected: .success(.unchangedSince(.init(modificationSequence: 12345))) + ), + ParseFixture.storeModifier("MYEXT", ")", expected: .success(.other(.init(key: "MYEXT", value: nil)))), + ParseFixture.storeModifier("", "", expected: .incompleteMessage), + ] + ) + func parse(_ fixture: ParseFixture) { + fixture.checkParsing() + } +} + +@Suite("StoreModifiers (array)") +struct StoreModifiersTests { + @Test( + "encode StoreModifiers", + arguments: [ + EncodeFixture.storeModifiers( + [.unchangedSince(.init(modificationSequence: 99))], + " (UNCHANGEDSINCE 99)" + ), + EncodeFixture.storeModifiers([], ""), + ] + ) + func encode(_ fixture: EncodeFixture<[StoreModifier]>) { + fixture.checkEncoding() + } + + @Test( + "parse StoreModifiers", + arguments: [ + ParseFixture.storeModifiers( + " (UNCHANGEDSINCE 42)", + expected: .success([.unchangedSince(.init(modificationSequence: 42))]) + ), + ParseFixture.storeModifiers("", "", expected: .incompleteMessage), + ] + ) + func parse(_ fixture: ParseFixture<[StoreModifier]>) { + fixture.checkParsing() + } +} + // MARK: - /// `Void` / `nil` replacement that is `Equatable`. @@ -64,3 +181,122 @@ extension ParseFixture { ) } } + +extension EncodeFixture> { + fileprivate static func lastCommandSet(_ input: LastCommandSet, _ expectedString: String) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeLastCommandSet($1) } + ) + } +} + +extension ParseFixture> { + fileprivate static func lastCommandSet( + _ input: String, + _ terminator: String = " ", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: { buffer, tracker in + try GrammarParser().parseLastCommandSet( + buffer: &buffer, + tracker: tracker, + setParser: GrammarParser().parseUIDSetNonEmpty + ) + } + ) + } +} + +extension EncodeFixture> { + fileprivate static func lastCommandMessageID( + _ input: LastCommandMessageID, + _ expectedString: String + ) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeLastCommandMessageID($1) } + ) + } +} + +extension ParseFixture> { + fileprivate static func lastCommandMessageID( + _ input: String, + _ terminator: String = " ", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: { buffer, tracker in + try GrammarParser().parseLastCommandMessageID( + buffer: &buffer, + tracker: tracker, + setParser: GrammarParser().parseMessageIdentifier + ) + } + ) + } +} + +extension EncodeFixture { + fileprivate static func storeModifier(_ input: StoreModifier, _ expectedString: String) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeStoreModifier($1) } + ) + } +} + +extension ParseFixture { + fileprivate static func storeModifier( + _ input: String, + _ terminator: String = " ", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseStoreModifier + ) + } +} + +extension EncodeFixture<[StoreModifier]> { + fileprivate static func storeModifiers(_ input: [StoreModifier], _ expectedString: String) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeStoreModifiers($1) } + ) + } +} + +extension ParseFixture<[StoreModifier]> { + fileprivate static func storeModifiers( + _ input: String, + _ terminator: String = " ", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseStoreModifiers + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/DateTests/DateTests.swift b/Tests/NIOIMAPCoreTests/Grammar/DateTests/DateTests.swift index 4f7eb8eb..3ea5cf6e 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/DateTests/DateTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/DateTests/DateTests.swift @@ -90,12 +90,19 @@ extension DateTests { fixture.checkEncoding() } - @Test(arguments: [ - ParseFixture.date("25-Jun-1994", " ", expected: .success(IMAPCalendarDay(year: 1994, month: 6, day: 25)!)), - ParseFixture.date("\"25-Jun-1994\"", "\r", expected: .success(IMAPCalendarDay(year: 1994, month: 6, day: 25)!)), - ParseFixture.date("\"25-Jun-1994 ", "\r", expected: .failure), - ParseFixture.date("\"\"", "\r", expected: .failure), - ]) + @Test( + "parse date", + arguments: [ + ParseFixture.date("25-Jun-1994", " ", expected: .success(IMAPCalendarDay(year: 1994, month: 6, day: 25)!)), + ParseFixture.date( + "\"25-Jun-1994\"", + "\r", + expected: .success(IMAPCalendarDay(year: 1994, month: 6, day: 25)!) + ), + ParseFixture.date("\"25-Jun-1994 ", "\r", expected: .failure), + ParseFixture.date("\"\"", "\r", expected: .failure), + ] + ) func parse(_ fixture: ParseFixture) { fixture.checkParsing() } @@ -136,6 +143,7 @@ extension DateTests { expected: .success(IMAPCalendarDay(year: 1994, month: 6, day: 25)!) ), ParseFixture.dateText("25-Jun-", "", expected: .incompleteMessageIgnoringBufferModifications), + ParseFixture.dateText("99-Jun-1994", " ", expected: .failureIgnoringBufferModifications), ] ) func parseDateText(_ fixture: ParseFixture) { diff --git a/Tests/NIOIMAPCoreTests/Grammar/DateTests/InternalDateTests.swift b/Tests/NIOIMAPCoreTests/Grammar/DateTests/InternalDateTests.swift index 8f58d2c1..ec811633 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/DateTests/InternalDateTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/DateTests/InternalDateTests.swift @@ -17,6 +17,22 @@ import Testing @Suite("ServerMessageDate") struct InternalDateTests { + @Test("UInt64 conversion") + func uint64Conversion() { + let components = ServerMessageDate.Components( + year: 2024, + month: 3, + day: 15, + hour: 10, + minute: 30, + second: 45, + timeZoneMinutes: 0 + )! + let date = ServerMessageDate(components) + let raw = UInt64(date) + #expect(raw == date.rawValue) + } + @Test("component initialization and roundtrip with typical values") func componentInitializationAndRoundtripWithTypicalValues() { let components = ServerMessageDate.Components( @@ -147,10 +163,217 @@ struct InternalDateTests { ), ParseFixture.internalDate(#""25-Jun-1994 01:02:03 +12""#, "", expected: .failureIgnoringBufferModifications), ParseFixture.internalDate(#""25-Jun-1994 01:02:03 abc""#, "", expected: .failureIgnoringBufferModifications), + ParseFixture.internalDate( + #"" 5-Jun-1994 01:02:03 +0000""#, + "\r", + expected: .success( + ServerMessageDate( + ServerMessageDate.Components( + year: 1994, + month: 6, + day: 5, + hour: 1, + minute: 2, + second: 3, + timeZoneMinutes: 0 + )! + ) + ) + ), + ParseFixture.internalDate( + #""99-Jun-1994 01:02:03 +0000""#, + "\r", + expected: .failureIgnoringBufferModifications + ), + ParseFixture.internalDate( + #""25-Jun-1994 01:02:03 +9999""#, + "\r", + expected: .failureIgnoringBufferModifications + ), + ParseFixture.internalDate( + #""25-Jun-1994 01:02:03 -9999""#, + "\r", + expected: .failureIgnoringBufferModifications + ), + ParseFixture.internalDate( + #""15-Feb-2000 00:00:00 +0000""#, + "\r", + expected: .success( + ServerMessageDate( + ServerMessageDate.Components( + year: 2000, + month: 2, + day: 15, + hour: 0, + minute: 0, + second: 0, + timeZoneMinutes: 0 + )! + ) + ) + ), + ParseFixture.internalDate( + #""15-Mar-2000 00:00:00 +0000""#, + "\r", + expected: .success( + ServerMessageDate( + ServerMessageDate.Components( + year: 2000, + month: 3, + day: 15, + hour: 0, + minute: 0, + second: 0, + timeZoneMinutes: 0 + )! + ) + ) + ), + ParseFixture.internalDate( + #""15-Apr-2000 00:00:00 +0000""#, + "\r", + expected: .success( + ServerMessageDate( + ServerMessageDate.Components( + year: 2000, + month: 4, + day: 15, + hour: 0, + minute: 0, + second: 0, + timeZoneMinutes: 0 + )! + ) + ) + ), + ParseFixture.internalDate( + #""15-May-2000 00:00:00 +0000""#, + "\r", + expected: .success( + ServerMessageDate( + ServerMessageDate.Components( + year: 2000, + month: 5, + day: 15, + hour: 0, + minute: 0, + second: 0, + timeZoneMinutes: 0 + )! + ) + ) + ), + ParseFixture.internalDate( + #""15-Jul-2000 00:00:00 +0000""#, + "\r", + expected: .success( + ServerMessageDate( + ServerMessageDate.Components( + year: 2000, + month: 7, + day: 15, + hour: 0, + minute: 0, + second: 0, + timeZoneMinutes: 0 + )! + ) + ) + ), + ParseFixture.internalDate( + #""15-Aug-2000 00:00:00 +0000""#, + "\r", + expected: .success( + ServerMessageDate( + ServerMessageDate.Components( + year: 2000, + month: 8, + day: 15, + hour: 0, + minute: 0, + second: 0, + timeZoneMinutes: 0 + )! + ) + ) + ), + ParseFixture.internalDate( + #""15-Sep-2000 00:00:00 +0000""#, + "\r", + expected: .success( + ServerMessageDate( + ServerMessageDate.Components( + year: 2000, + month: 9, + day: 15, + hour: 0, + minute: 0, + second: 0, + timeZoneMinutes: 0 + )! + ) + ) + ), + ParseFixture.internalDate( + #""15-Oct-2000 00:00:00 +0000""#, + "\r", + expected: .success( + ServerMessageDate( + ServerMessageDate.Components( + year: 2000, + month: 10, + day: 15, + hour: 0, + minute: 0, + second: 0, + timeZoneMinutes: 0 + )! + ) + ) + ), + ParseFixture.internalDate( + #""15-Nov-2000 00:00:00 +0000""#, + "\r", + expected: .success( + ServerMessageDate( + ServerMessageDate.Components( + year: 2000, + month: 11, + day: 15, + hour: 0, + minute: 0, + second: 0, + timeZoneMinutes: 0 + )! + ) + ) + ), ]) func parse(_ fixture: ParseFixture) { fixture.checkParsing() } + + @Test( + "encodes all month names", + arguments: [ + (1, "Jan"), (2, "Feb"), (3, "Mar"), (4, "Apr"), (5, "May"), + (7, "Jul"), (8, "Aug"), (9, "Sep"), (10, "Oct"), (11, "Nov"), (12, "Dec"), + ] as [(Int, String)] + ) + func encodesMonthName(_ fixture: (Int, String)) { + let (month, monthName) = fixture + let components = ServerMessageDate.Components( + year: 2000, + month: month, + day: 15, + hour: 12, + minute: 0, + second: 0, + timeZoneMinutes: 0 + )! + let date = ServerMessageDate(components) + #expect(String(reflecting: date) == "\"15-\(monthName)-2000 12:00:00 +0000\"") + } } // MARK: - diff --git a/Tests/NIOIMAPCoreTests/Grammar/ESearch/ESearchOptions+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/ESearch/ESearchOptions+Tests.swift index 525e008e..eb279ec5 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/ESearch/ESearchOptions+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/ESearch/ESearchOptions+Tests.swift @@ -81,70 +81,73 @@ struct ExtendedSearchOptionsTests { fixture.checkEncoding() } - @Test(arguments: [ - ParseFixture.extendedSearchOptions( - " ALL", - expected: .success(ExtendedSearchOptions(key: .all)) - ), - ParseFixture.extendedSearchOptions( - " RETURN (MIN) ALL", - expected: .success(ExtendedSearchOptions(key: .all, returnOptions: [.min])) - ), - ParseFixture.extendedSearchOptions( - " CHARSET Alien ALL", - expected: .success(ExtendedSearchOptions(key: .all, charset: "Alien")) - ), - ParseFixture.extendedSearchOptions( - " IN (inboxes) ALL", - expected: .success( - ExtendedSearchOptions( - key: .all, - sourceOptions: ExtendedSearchSourceOptions(sourceMailbox: [.inboxes]) + @Test( + "parse extended search options", + arguments: [ + ParseFixture.extendedSearchOptions( + " ALL", + expected: .success(ExtendedSearchOptions(key: .all)) + ), + ParseFixture.extendedSearchOptions( + " RETURN (MIN) ALL", + expected: .success(ExtendedSearchOptions(key: .all, returnOptions: [.min])) + ), + ParseFixture.extendedSearchOptions( + " CHARSET Alien ALL", + expected: .success(ExtendedSearchOptions(key: .all, charset: "Alien")) + ), + ParseFixture.extendedSearchOptions( + " IN (inboxes) ALL", + expected: .success( + ExtendedSearchOptions( + key: .all, + sourceOptions: ExtendedSearchSourceOptions(sourceMailbox: [.inboxes]) + ) ) - ) - ), - ParseFixture.extendedSearchOptions( - " IN (inboxes) CHARSET Alien ALL", - expected: .success( - ExtendedSearchOptions( - key: .all, - charset: "Alien", - sourceOptions: ExtendedSearchSourceOptions(sourceMailbox: [.inboxes]) + ), + ParseFixture.extendedSearchOptions( + " IN (inboxes) CHARSET Alien ALL", + expected: .success( + ExtendedSearchOptions( + key: .all, + charset: "Alien", + sourceOptions: ExtendedSearchSourceOptions(sourceMailbox: [.inboxes]) + ) ) - ) - ), - ParseFixture.extendedSearchOptions( - " IN (inboxes) RETURN (MIN) ALL", - expected: .success( - ExtendedSearchOptions( - key: .all, - returnOptions: [.min], - sourceOptions: ExtendedSearchSourceOptions(sourceMailbox: [.inboxes]) + ), + ParseFixture.extendedSearchOptions( + " IN (inboxes) RETURN (MIN) ALL", + expected: .success( + ExtendedSearchOptions( + key: .all, + returnOptions: [.min], + sourceOptions: ExtendedSearchSourceOptions(sourceMailbox: [.inboxes]) + ) ) - ) - ), - ParseFixture.extendedSearchOptions( - " RETURN (MIN) CHARSET Alien ALL", - expected: .success( - ExtendedSearchOptions( - key: .all, - charset: "Alien", - returnOptions: [.min] + ), + ParseFixture.extendedSearchOptions( + " RETURN (MIN) CHARSET Alien ALL", + expected: .success( + ExtendedSearchOptions( + key: .all, + charset: "Alien", + returnOptions: [.min] + ) ) - ) - ), - ParseFixture.extendedSearchOptions( - " IN (inboxes) RETURN (MIN) CHARSET Alien ALL", - expected: .success( - ExtendedSearchOptions( - key: .all, - charset: "Alien", - returnOptions: [.min], - sourceOptions: ExtendedSearchSourceOptions(sourceMailbox: [.inboxes]) + ), + ParseFixture.extendedSearchOptions( + " IN (inboxes) RETURN (MIN) CHARSET Alien ALL", + expected: .success( + ExtendedSearchOptions( + key: .all, + charset: "Alien", + returnOptions: [.min], + sourceOptions: ExtendedSearchSourceOptions(sourceMailbox: [.inboxes]) + ) ) - ) - ), - ]) + ), + ] + ) func parseExtendedSearchOptions(_ fixture: ParseFixture) { fixture.checkParsing() } diff --git a/Tests/NIOIMAPCoreTests/Grammar/ESearch/ESearchScopeOptions+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/ESearch/ESearchScopeOptions+Tests.swift index c65f6fbf..d0ebf008 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/ESearch/ESearchScopeOptions+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/ESearch/ESearchScopeOptions+Tests.swift @@ -32,17 +32,28 @@ struct ExtendedSearchScopeOptionsTests { fixture.checkEncoding() } - @Test(arguments: [ - ParseFixture.extendedSearchScopeOptions("name", expected: .success(ExtendedSearchScopeOptions(["name": nil])!)), - ParseFixture.extendedSearchScopeOptions( - "name $", - expected: .success(ExtendedSearchScopeOptions(["name": .sequence(.lastCommand)])!) - ), - ParseFixture.extendedSearchScopeOptions( - "name name2", - expected: .success(ExtendedSearchScopeOptions(["name": nil, "name2": nil])!) - ), - ]) + @Test("nil when empty") + func nilWhenEmpty() { + #expect(ExtendedSearchScopeOptions([:]) == nil) + } + + @Test( + "parse extended search scope options", + arguments: [ + ParseFixture.extendedSearchScopeOptions( + "name", + expected: .success(ExtendedSearchScopeOptions(["name": nil])!) + ), + ParseFixture.extendedSearchScopeOptions( + "name $", + expected: .success(ExtendedSearchScopeOptions(["name": .sequence(.lastCommand)])!) + ), + ParseFixture.extendedSearchScopeOptions( + "name name2", + expected: .success(ExtendedSearchScopeOptions(["name": nil, "name2": nil])!) + ), + ] + ) func parseExtendedSearchScopeOptions(_ fixture: ParseFixture) { fixture.checkParsing() } diff --git a/Tests/NIOIMAPCoreTests/Grammar/ESearch/ESearchSourceOptions+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/ESearch/ESearchSourceOptions+Tests.swift index e5a8cb32..5927c6a6 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/ESearch/ESearchSourceOptions+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/ESearch/ESearchSourceOptions+Tests.swift @@ -18,6 +18,19 @@ import Testing @Suite("ExtendedSearchSourceOptions") struct ExtendedSearchSourceOptionsTests { + @Test( + "failable init", + arguments: [ + ([] as [MailboxFilter], false), + ([.inboxes] as [MailboxFilter], true), + ] as [([MailboxFilter], Bool)] + ) + func failableInit(_ fixture: ([MailboxFilter], Bool)) { + let (sourceMailbox, shouldSucceed) = fixture + let result = ExtendedSearchSourceOptions(sourceMailbox: sourceMailbox) + #expect((result != nil) == shouldSucceed) + } + @Test(arguments: [ EncodeFixture.extendedSearchSourceOptions( ExtendedSearchSourceOptions(sourceMailbox: [.inboxes])!, @@ -42,33 +55,36 @@ struct ExtendedSearchSourceOptionsTests { fixture.checkEncoding() } - @Test(arguments: [ - ParseFixture.extendedSearchSourceOptions( - "IN (inboxes)", - expected: .success(ExtendedSearchSourceOptions(sourceMailbox: [.inboxes])!) - ), - ParseFixture.extendedSearchSourceOptions( - "IN (inboxes personal)", - expected: .success(ExtendedSearchSourceOptions(sourceMailbox: [.inboxes, .personal])!) - ), - ParseFixture.extendedSearchSourceOptions( - "IN (inboxes (name))", - expected: .success( - ExtendedSearchSourceOptions( - sourceMailbox: [.inboxes], - scopeOptions: ExtendedSearchScopeOptions(["name": nil])! - )! - ) - ), - ParseFixture.extendedSearchSourceOptions("IN (inboxes ())", expected: .failure), - ParseFixture.extendedSearchSourceOptions("IN ((name))", expected: .failure), - ParseFixture.extendedSearchSourceOptions("IN (inboxes (name)", expected: .failure), - ParseFixture.extendedSearchSourceOptions("IN (inboxes (name", expected: .failure), - ParseFixture.extendedSearchSourceOptions("IN (inboxes (", expected: .failure), - ParseFixture.extendedSearchSourceOptions("IN (inboxes )", expected: .failure), - ParseFixture.extendedSearchSourceOptions("IN (", expected: .failure), - ParseFixture.extendedSearchSourceOptions("IN", expected: .failure), - ]) + @Test( + "parse extended search source options", + arguments: [ + ParseFixture.extendedSearchSourceOptions( + "IN (inboxes)", + expected: .success(ExtendedSearchSourceOptions(sourceMailbox: [.inboxes])!) + ), + ParseFixture.extendedSearchSourceOptions( + "IN (inboxes personal)", + expected: .success(ExtendedSearchSourceOptions(sourceMailbox: [.inboxes, .personal])!) + ), + ParseFixture.extendedSearchSourceOptions( + "IN (inboxes (name))", + expected: .success( + ExtendedSearchSourceOptions( + sourceMailbox: [.inboxes], + scopeOptions: ExtendedSearchScopeOptions(["name": nil])! + )! + ) + ), + ParseFixture.extendedSearchSourceOptions("IN (inboxes ())", expected: .failure), + ParseFixture.extendedSearchSourceOptions("IN ((name))", expected: .failure), + ParseFixture.extendedSearchSourceOptions("IN (inboxes (name)", expected: .failure), + ParseFixture.extendedSearchSourceOptions("IN (inboxes (name", expected: .failure), + ParseFixture.extendedSearchSourceOptions("IN (inboxes (", expected: .failure), + ParseFixture.extendedSearchSourceOptions("IN (inboxes )", expected: .failure), + ParseFixture.extendedSearchSourceOptions("IN (", expected: .failure), + ParseFixture.extendedSearchSourceOptions("IN", expected: .failure), + ] + ) func parseExtendedSearchSourceOptions(_ fixture: ParseFixture) { fixture.checkParsing() } diff --git a/Tests/NIOIMAPCoreTests/Grammar/EmailAddressTests.swift b/Tests/NIOIMAPCoreTests/Grammar/EmailAddressTests.swift index cf386960..7409579f 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/EmailAddressTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/EmailAddressTests.swift @@ -32,28 +32,36 @@ struct EmailAddressTestsSuite { #expect(address.host == host) } - @Test(arguments: [ - EmailAddressFixture( - name: "all nil", - address: .init(personName: nil, sourceRoot: nil, mailbox: nil, host: nil), - expectedString: "(NIL NIL NIL NIL)" - ), - EmailAddressFixture( - name: "none nil", - address: .init(personName: "somename", sourceRoot: "someadl", mailbox: "somemailbox", host: "someaddress"), - expectedString: "(\"somename\" \"someadl\" \"somemailbox\" \"someaddress\")" - ), - EmailAddressFixture( - name: "mixed nil", - address: .init(personName: nil, sourceRoot: "some", mailbox: "thing", host: nil), - expectedString: "(NIL \"some\" \"thing\" NIL)" - ), - EmailAddressFixture( - name: "unicode", - address: .init(personName: nil, sourceRoot: nil, mailbox: "阿Q", host: "例子.中国"), - expectedString: "(NIL NIL {4}\r\n阿Q {13}\r\n例子.中国)" - ), - ]) + @Test( + "encode email address", + arguments: [ + EmailAddressFixture( + name: "all nil", + address: .init(personName: nil, sourceRoot: nil, mailbox: nil, host: nil), + expectedString: "(NIL NIL NIL NIL)" + ), + EmailAddressFixture( + name: "none nil", + address: .init( + personName: "somename", + sourceRoot: "someadl", + mailbox: "somemailbox", + host: "someaddress" + ), + expectedString: "(\"somename\" \"someadl\" \"somemailbox\" \"someaddress\")" + ), + EmailAddressFixture( + name: "mixed nil", + address: .init(personName: nil, sourceRoot: "some", mailbox: "thing", host: nil), + expectedString: "(NIL \"some\" \"thing\" NIL)" + ), + EmailAddressFixture( + name: "unicode", + address: .init(personName: nil, sourceRoot: nil, mailbox: "阿Q", host: "例子.中国"), + expectedString: "(NIL NIL {4}\r\n阿Q {13}\r\n例子.中国)" + ), + ] + ) func encodeEmailAddress(_ fixture: EmailAddressFixture) { fixture.checkEncoding() } @@ -82,123 +90,126 @@ struct EmailAddressTestsSuite { fixture.checkParsing() } - @Test(arguments: [ - EnvelopeGroupingFixture( - addresses: [], - expected: [] - ), - EnvelopeGroupingFixture( - addresses: [.init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a")], - expected: [.singleAddress(.init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a"))] - ), - EnvelopeGroupingFixture( - addresses: [ - .init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a"), - .init(personName: "b", sourceRoot: "b", mailbox: "b", host: "b"), - ], - expected: [ - .singleAddress(.init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a")), - .singleAddress(.init(personName: "b", sourceRoot: "b", mailbox: "b", host: "b")), - ] - ), - EnvelopeGroupingFixture( - addresses: [ - .init(personName: nil, sourceRoot: nil, mailbox: "group", host: nil), - .init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a"), - .init(personName: nil, sourceRoot: nil, mailbox: nil, host: nil), - ], - expected: [ - .group( - .init( - groupName: "group", - sourceRoot: nil, - children: [.singleAddress(.init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a"))] + @Test( + "parse envelope email address groups", + arguments: [ + EnvelopeGroupingFixture( + addresses: [], + expected: [] + ), + EnvelopeGroupingFixture( + addresses: [.init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a")], + expected: [.singleAddress(.init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a"))] + ), + EnvelopeGroupingFixture( + addresses: [ + .init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a"), + .init(personName: "b", sourceRoot: "b", mailbox: "b", host: "b"), + ], + expected: [ + .singleAddress(.init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a")), + .singleAddress(.init(personName: "b", sourceRoot: "b", mailbox: "b", host: "b")), + ] + ), + EnvelopeGroupingFixture( + addresses: [ + .init(personName: nil, sourceRoot: nil, mailbox: "group", host: nil), + .init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a"), + .init(personName: nil, sourceRoot: nil, mailbox: nil, host: nil), + ], + expected: [ + .group( + .init( + groupName: "group", + sourceRoot: nil, + children: [.singleAddress(.init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a"))] + ) ) - ) - ] - ), - EnvelopeGroupingFixture( - addresses: [ - .init(personName: nil, sourceRoot: nil, mailbox: nil, host: nil) - ], - expected: [ - .singleAddress(.init(personName: nil, sourceRoot: nil, mailbox: nil, host: nil)) - ] - ), - EnvelopeGroupingFixture( - addresses: [ - .init(personName: nil, sourceRoot: nil, mailbox: "group", host: nil), - .init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a"), - .init(personName: "b", sourceRoot: "b", mailbox: "b", host: "b"), - .init(personName: "c", sourceRoot: "c", mailbox: "c", host: "c"), - .init(personName: nil, sourceRoot: nil, mailbox: nil, host: nil), - ], - expected: [ - .group( - .init( - groupName: "group", - sourceRoot: nil, - children: [ - .singleAddress(.init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a")), - .singleAddress(.init(personName: "b", sourceRoot: "b", mailbox: "b", host: "b")), - .singleAddress(.init(personName: "c", sourceRoot: "c", mailbox: "c", host: "c")), - ] + ] + ), + EnvelopeGroupingFixture( + addresses: [ + .init(personName: nil, sourceRoot: nil, mailbox: nil, host: nil) + ], + expected: [ + .singleAddress(.init(personName: nil, sourceRoot: nil, mailbox: nil, host: nil)) + ] + ), + EnvelopeGroupingFixture( + addresses: [ + .init(personName: nil, sourceRoot: nil, mailbox: "group", host: nil), + .init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a"), + .init(personName: "b", sourceRoot: "b", mailbox: "b", host: "b"), + .init(personName: "c", sourceRoot: "c", mailbox: "c", host: "c"), + .init(personName: nil, sourceRoot: nil, mailbox: nil, host: nil), + ], + expected: [ + .group( + .init( + groupName: "group", + sourceRoot: nil, + children: [ + .singleAddress(.init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a")), + .singleAddress(.init(personName: "b", sourceRoot: "b", mailbox: "b", host: "b")), + .singleAddress(.init(personName: "c", sourceRoot: "c", mailbox: "c", host: "c")), + ] + ) ) - ) - ] - ), - EnvelopeGroupingFixture( - addresses: [ - .init(personName: nil, sourceRoot: nil, mailbox: "group1", host: nil), - .init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a"), - .init(personName: nil, sourceRoot: nil, mailbox: "group2", host: nil), - .init(personName: "b", sourceRoot: "b", mailbox: "b", host: "b"), - .init(personName: nil, sourceRoot: nil, mailbox: "group3", host: nil), - .init(personName: "c", sourceRoot: "c", mailbox: "c", host: "c"), - .init(personName: nil, sourceRoot: nil, mailbox: nil, host: nil), - .init(personName: nil, sourceRoot: nil, mailbox: nil, host: nil), - .init(personName: nil, sourceRoot: nil, mailbox: nil, host: nil), - ], - expected: [ - .group( - .init( - groupName: "group1", - sourceRoot: nil, - children: [ - .singleAddress(.init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a")), - .group( - .init( - groupName: "group2", - sourceRoot: nil, - children: [ - .singleAddress( - .init(personName: "b", sourceRoot: "b", mailbox: "b", host: "b") - ), - .group( - .init( - groupName: "group3", - sourceRoot: nil, - children: [ - .singleAddress( - .init( - personName: "c", - sourceRoot: "c", - mailbox: "c", - host: "c" + ] + ), + EnvelopeGroupingFixture( + addresses: [ + .init(personName: nil, sourceRoot: nil, mailbox: "group1", host: nil), + .init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a"), + .init(personName: nil, sourceRoot: nil, mailbox: "group2", host: nil), + .init(personName: "b", sourceRoot: "b", mailbox: "b", host: "b"), + .init(personName: nil, sourceRoot: nil, mailbox: "group3", host: nil), + .init(personName: "c", sourceRoot: "c", mailbox: "c", host: "c"), + .init(personName: nil, sourceRoot: nil, mailbox: nil, host: nil), + .init(personName: nil, sourceRoot: nil, mailbox: nil, host: nil), + .init(personName: nil, sourceRoot: nil, mailbox: nil, host: nil), + ], + expected: [ + .group( + .init( + groupName: "group1", + sourceRoot: nil, + children: [ + .singleAddress(.init(personName: "a", sourceRoot: "a", mailbox: "a", host: "a")), + .group( + .init( + groupName: "group2", + sourceRoot: nil, + children: [ + .singleAddress( + .init(personName: "b", sourceRoot: "b", mailbox: "b", host: "b") + ), + .group( + .init( + groupName: "group3", + sourceRoot: nil, + children: [ + .singleAddress( + .init( + personName: "c", + sourceRoot: "c", + mailbox: "c", + host: "c" + ) ) - ) - ] - ) - ), - ] - ) - ), - ] + ] + ) + ), + ] + ) + ), + ] + ) ) - ) - ] - ), - ]) + ] + ), + ] + ) func parseEnvelopeEmailAddressGroups(_ fixture: EnvelopeGroupingFixture) { let actual = GrammarParser().parseEnvelopeEmailAddressGroups(fixture.addresses) #expect(actual == fixture.expected) diff --git a/Tests/NIOIMAPCoreTests/Grammar/FetchAttribute+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/FetchAttribute+Tests.swift index fd67bbd2..beeb0580 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/FetchAttribute+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/FetchAttribute+Tests.swift @@ -34,6 +34,8 @@ struct FetchAttributeTests { EncodeFixture.fetchAttribute(.binarySize(section: [1]), "BINARY.SIZE[1]"), EncodeFixture.fetchAttribute(.binary(peek: true, section: [1, 2, 3], partial: nil), "BINARY.PEEK[1.2.3]"), EncodeFixture.fetchAttribute(.binary(peek: false, section: [3, 4, 5], partial: nil), "BINARY[3.4.5]"), + EncodeFixture.fetchAttribute(.binary(peek: false, section: [1], partial: 3...6), "BINARY[1]<3.4>"), + EncodeFixture.fetchAttribute(.binary(peek: true, section: [2], partial: 4...8), "BINARY.PEEK[2]<4.5>"), EncodeFixture.fetchAttribute(.modificationSequenceValue(.zero), "0"), EncodeFixture.fetchAttribute(.modificationSequenceValue(3), "3"), EncodeFixture.fetchAttribute(.modificationSequence, "MODSEQ"), @@ -200,6 +202,9 @@ struct FetchAttributeTests { ParseFixture.fetchAttribute("PREVIEW (LAZY)", " ", expected: .success(.preview(lazy: true))), ParseFixture.fetchAttribute("EMAILID", " ", expected: .success(.emailID)), ParseFixture.fetchAttribute("THREADID", " ", expected: .success(.threadID)), + // Numeric inputs fall back to parseFetchAttribute_modificationSequence + ParseFixture.fetchAttribute("0", " ", expected: .success(.modificationSequenceValue(.zero))), + ParseFixture.fetchAttribute("42", " ", expected: .success(.modificationSequenceValue(42))), ]) func parse(_ fixture: ParseFixture) { fixture.checkParsing() @@ -225,6 +230,7 @@ struct FetchAttributeTests { ParseFixture.partial("<2.4294967294>", expected: .failure), ParseFixture.partial("<4294967000.4294967000>", expected: .failure), ParseFixture.partial("<2200000000.2200000000>", expected: .failure), + ParseFixture.partial("<0.4294967296>", expected: .failure), ParseFixture.partial("<", "", expected: .incompleteMessage), ParseFixture.partial("<111111111", "", expected: .incompleteMessage), ParseFixture.partial("<1.", "", expected: .incompleteMessage), diff --git a/Tests/NIOIMAPCoreTests/Grammar/FetchResponse+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/FetchResponse+Tests.swift index 8021d018..7365ba53 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/FetchResponse+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/FetchResponse+Tests.swift @@ -50,10 +50,50 @@ struct FetchResponseTests { func parseStart(_ fixture: ParseFixture) { fixture.checkParsing() } + + @Test( + "parse streaming response", + arguments: [ + // BODY without section brackets triggers the nil-section path (offset present) + ParseFixture.fetchStreamingResponse("BODY<0>", " ", expected: .success(.body(section: .init(), offset: 0))), + // BODY with section and offset + ParseFixture.fetchStreamingResponse( + "BODY[TEXT]<5>", + " ", + expected: .success(.body(section: .init(kind: .text), offset: 5)) + ), + // BODY with section, no offset + ParseFixture.fetchStreamingResponse( + "BODY[HEADER]", + " ", + expected: .success(.body(section: .init(kind: .header), offset: nil)) + ), + ParseFixture.fetchStreamingResponse("RFC822.TEXT", " ", expected: .success(.rfc822Text)), + ParseFixture.fetchStreamingResponse("RFC822.HEADER", " ", expected: .success(.rfc822Header)), + ] + ) + func parseStreamingResponse(_ fixture: ParseFixture) { + fixture.checkParsing() + } } // MARK: - +extension ParseFixture { + fileprivate static func fetchStreamingResponse( + _ input: String, + _ terminator: String = " ", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseFetchStreamingResponse + ) + } +} + extension ParseFixture { fileprivate static func fetchResponse( _ input: String, diff --git a/Tests/NIOIMAPCoreTests/Grammar/Flag/Flag+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Flag/Flag+Tests.swift index 718bfdab..9d9dc75c 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Flag/Flag+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Flag/Flag+Tests.swift @@ -49,6 +49,29 @@ struct FlagTests { #expect(input == expected) } + @Test( + "string conversion", + arguments: [ + (Flag.answered, "\\Answered"), + (Flag.flagged, "\\Flagged"), + (Flag("Custom"), "Custom"), + ] as [(Flag, String)] + ) + func stringConversion(_ fixture: (Flag, String)) { + #expect(String(fixture.0) == fixture.1) + } + + #if swift(>=6.2) + @Test("extension(_:) precondition failure without backslash") func extensionPreconditionFailure() async { + await #expect( + processExitsWith: ExitTest.Condition.failure, + performing: { + _ = Flag.extension("NoBackslash") + } + ) + } + #endif + @Test("equality checks") func equalityChecks() { expectEqualAndEqualHash(Flag.answered, .answered) diff --git a/Tests/NIOIMAPCoreTests/Grammar/Flag/FlagKeyword+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Flag/FlagKeyword+Tests.swift index f8199009..51b30240 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Flag/FlagKeyword+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Flag/FlagKeyword+Tests.swift @@ -27,6 +27,12 @@ struct FlagKeywordTests { #expect(Flag.Keyword("a") != Flag.Keyword("b")) } + @Test("debug description") + func debugDescription() { + #expect(Flag.Keyword.forwarded.debugDescription == "$Forwarded") + #expect(Flag.Keyword.junk.debugDescription == "$Junk") + } + @Test(arguments: [ EncodeFixture.flagKeyword( .forwarded, @@ -77,9 +83,12 @@ struct FlagKeywordTests { fixture.checkEncoding() } - @Test(arguments: [ - ParseFixture.flagKeyword("keyword", expected: .success(Flag.Keyword("keyword")!)) - ]) + @Test( + "parse", + arguments: [ + ParseFixture.flagKeyword("keyword", expected: .success(Flag.Keyword("keyword")!)) + ] + ) func parse(_ fixture: ParseFixture) { fixture.checkParsing() } diff --git a/Tests/NIOIMAPCoreTests/Grammar/Flag/StoreOperation+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Flag/StoreOperation+Tests.swift new file mode 100644 index 00000000..83c466d4 --- /dev/null +++ b/Tests/NIOIMAPCoreTests/Grammar/Flag/StoreOperation+Tests.swift @@ -0,0 +1,73 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import NIO +@_spi(NIOIMAPInternal) @testable import NIOIMAPCore +import Testing + +@Suite("StoreOperation") +struct StoreOperationTests { + @Test( + "encode", + arguments: [ + EncodeFixture.storeOperation(.add, "+"), + EncodeFixture.storeOperation(.remove, "-"), + EncodeFixture.storeOperation(.replace, ""), + ] + ) + func encode(_ fixture: EncodeFixture) { + fixture.checkEncoding() + } + + @Test( + "parse", + arguments: [ + ParseFixture.storeOperation("+", expected: .success(.add)), + ParseFixture.storeOperation("-", expected: .success(.remove)), + // .replace matches the empty prefix — succeeds on any input without consuming bytes + ParseFixture.storeOperation("", " ", expected: .success(.replace)), + ] + ) + func parse(_ fixture: ParseFixture) { + fixture.checkParsing() + } +} + +// MARK: - + +extension EncodeFixture { + fileprivate static func storeOperation(_ input: StoreOperation, _ expectedString: String) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { buffer, op in buffer.writeString(op.rawValue) } + ) + } +} + +extension ParseFixture { + fileprivate static func storeOperation( + _ input: String, + _ terminator: String = " ", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseStoreOperation + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/FullDateTime+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/FullDateTime+Tests.swift index 7453f9f6..a1ce0871 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/FullDateTime+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/FullDateTime+Tests.swift @@ -126,6 +126,26 @@ struct FullDateTimeTests { func parseFullTime(_ fixture: ParseFixture) { fixture.checkParsing() } + + #if swift(>=6.2) + @Test("invalid month triggers precondition failure") func invalidMonthPrecondition() async { + await #expect( + processExitsWith: ExitTest.Condition.failure, + performing: { + _ = FullDate(year: 2024, month: 0, day: 1) + } + ) + } + + @Test("invalid day triggers precondition failure") func invalidDayPrecondition() async { + await #expect( + processExitsWith: ExitTest.Condition.failure, + performing: { + _ = FullDate(year: 2024, month: 1, day: 0) + } + ) + } + #endif } // MARK: - diff --git a/Tests/NIOIMAPCoreTests/Grammar/IMAPServer+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/IMAPServer+Tests.swift index 24d28a72..3b34ebbb 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/IMAPServer+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/IMAPServer+Tests.swift @@ -74,6 +74,11 @@ struct IMAPServerTests { ) ) ), + ParseFixture.imapServer( + "[someHost]", + " ", + expected: .success(.init(userAuthenticationMechanism: nil, host: "someHost", port: nil)) + ), ]) func parse(_ fixture: ParseFixture) { fixture.checkParsing() diff --git a/Tests/NIOIMAPCoreTests/Grammar/IUserInfo+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/IUserInfo+Tests.swift index 44500723..f503ef08 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/IUserInfo+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/IUserInfo+Tests.swift @@ -52,10 +52,26 @@ struct UserAuthenticationMechanismTests { " ", expected: .success(.init(encodedUser: .init(data: "test"), authenticationMechanism: .any)) ), + ParseFixture.userAuthenticationMechanism( + "@localhost", + " ", + expected: .failureIgnoringBufferModifications + ), ]) func parse(_ fixture: ParseFixture) { fixture.checkParsing() } + + #if swift(>=6.2) + @Test("both nil arguments triggers precondition failure") func bothNilPreconditionFailure() async { + await #expect( + processExitsWith: ExitTest.Condition.failure, + performing: { + _ = UserAuthenticationMechanism(encodedUser: nil, authenticationMechanism: nil) + } + ) + } + #endif } // MARK: - diff --git a/Tests/NIOIMAPCoreTests/Grammar/ImapUrl+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/ImapUrl+Tests.swift index 04414f48..15be42c3 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/ImapUrl+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/ImapUrl+Tests.swift @@ -27,6 +27,19 @@ struct IMAPURLTests { .init(server: .init(host: "mail.example.com"), query: nil), "imap://mail.example.com/" ), + EncodeFixture.imapURL( + .init( + server: .init(host: "localhost"), + query: .fetch( + path: .init( + mailboxReference: .init(encodeMailbox: .init(mailbox: "test")), + iUID: .init(uid: 123) + ), + authenticatedURL: nil + ) + ), + "imap://localhost/test/;UID=123" + ), ]) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() diff --git a/Tests/NIOIMAPCoreTests/Grammar/InternetMessageDate+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/InternetMessageDate+Tests.swift index 2eab8d13..d32f258a 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/InternetMessageDate+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/InternetMessageDate+Tests.swift @@ -18,12 +18,20 @@ import Testing @Suite("InternetMessageDate") struct InternetMessageDateTests { - @Test(arguments: [ - EncodeFixture.internetMessageDate(.init("test"), "test") - ]) + @Test( + "encode", + arguments: [ + EncodeFixture.internetMessageDate(.init("test"), "test") + ] + ) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() } + + @Test("string conversion") + func stringConversion() { + #expect(String(InternetMessageDate("Mon, 01 Jan 2024 00:00:00 +0000")) == "Mon, 01 Jan 2024 00:00:00 +0000") + } } // MARK: - diff --git a/Tests/NIOIMAPCoreTests/Grammar/List/ListReturnOptions+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/List/ListReturnOptions+Tests.swift index d2a8f02f..2c9b577b 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/List/ListReturnOptions+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/List/ListReturnOptions+Tests.swift @@ -18,14 +18,33 @@ import Testing @Suite("ListReturnOptions") struct ListReturnOptionsTests { - @Test(arguments: [ - EncodeFixture.listReturnOptions([], "RETURN ()"), - EncodeFixture.listReturnOptions([.subscribed], "RETURN (SUBSCRIBED)"), - EncodeFixture.listReturnOptions([.subscribed, .children], "RETURN (SUBSCRIBED CHILDREN)"), - ]) + @Test( + "encode", + arguments: [ + EncodeFixture.listReturnOptions([], "RETURN ()"), + EncodeFixture.listReturnOptions([.subscribed], "RETURN (SUBSCRIBED)"), + EncodeFixture.listReturnOptions([.subscribed, .children], "RETURN (SUBSCRIBED CHILDREN)"), + ] + ) func encode(_ fixture: EncodeFixture<[ReturnOption]>) { fixture.checkEncoding() } + + @Test(arguments: [ + ParseFixture.returnOption("SUBSCRIBED", ")", expected: .success(.subscribed)), + ParseFixture.returnOption("CHILDREN", ")", expected: .success(.children)), + ParseFixture.returnOption("STATUS (MESSAGES)", " ", expected: .success(.statusOption([.messageCount]))), + ParseFixture.returnOption( + "MYEXT", + ")", + expected: .success(.optionExtension(.init(key: .standard("MYEXT"), value: nil))) + ), + ParseFixture.returnOption("", "", expected: .incompleteMessage), + ParseFixture.returnOption("123invalid", expected: .failure), + ]) + func parse(_ fixture: ParseFixture) { + fixture.checkParsing() + } } // MARK: - @@ -43,3 +62,18 @@ extension EncodeFixture<[ReturnOption]> { ) } } + +extension ParseFixture { + fileprivate static func returnOption( + _ input: String, + _ terminator: String = " ", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseReturnOption + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/List/ListSelectBaseOption+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/List/ListSelectBaseOption+Tests.swift index bde77493..88d649f2 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/List/ListSelectBaseOption+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/List/ListSelectBaseOption+Tests.swift @@ -18,10 +18,13 @@ import Testing @Suite("ListSelectBaseOption") struct ListSelectBaseOptionTests { - @Test(arguments: [ - EncodeFixture.listSelectBaseOption(.subscribed, "SUBSCRIBED"), - EncodeFixture.listSelectBaseOption(.option(.init(key: .standard("test"), value: nil)), "test"), - ]) + @Test( + "encode", + arguments: [ + EncodeFixture.listSelectBaseOption(.subscribed, "SUBSCRIBED"), + EncodeFixture.listSelectBaseOption(.option(.init(key: .standard("test"), value: nil)), "test"), + ] + ) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() } @@ -35,6 +38,40 @@ struct ListSelectBaseOptionTests { func encodeQuoted(_ fixture: EncodeFixture) { fixture.checkEncoding() } + + @Test( + "parse", + arguments: [ + ParseFixture.listSelectBaseOption("SUBSCRIBED", ")", expected: .success(.subscribed)), + ParseFixture.listSelectBaseOption( + "REMOTE", + ")", + expected: .success(.option(.init(key: .standard("REMOTE"), value: nil))) + ), + ParseFixture.listSelectBaseOption("", "", expected: .incompleteMessage), + ] + ) + func parse(_ fixture: ParseFixture) { + fixture.checkParsing() + } + + @Test( + "parse CHILDINFO extended item", + arguments: [ + ParseFixture.childinfoExtendedItem( + #"CHILDINFO ("SUBSCRIBED")"#, + expected: .success([.subscribed]) + ), + ParseFixture.childinfoExtendedItem( + #"CHILDINFO ("SUBSCRIBED" "REMOTE")"#, + expected: .success([.subscribed, .option(.init(key: .standard("REMOTE"), value: nil))]) + ), + ParseFixture.childinfoExtendedItem("", "", expected: .incompleteMessage), + ] + ) + func parseChildinfoExtendedItem(_ fixture: ParseFixture<[ListSelectBaseOption]>) { + fixture.checkParsing() + } } // MARK: - @@ -64,3 +101,33 @@ extension EncodeFixture { ) } } + +extension ParseFixture { + fileprivate static func listSelectBaseOption( + _ input: String, + _ terminator: String = " ", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseListSelectBaseOption + ) + } +} + +extension ParseFixture<[ListSelectBaseOption]> { + fileprivate static func childinfoExtendedItem( + _ input: String, + _ terminator: String = "\r", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseChildinfoExtendedItem + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/List/ListSelectIndependentOption+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/List/ListSelectIndependentOption+Tests.swift index 94173a9a..de684331 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/List/ListSelectIndependentOption+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/List/ListSelectIndependentOption+Tests.swift @@ -18,14 +18,29 @@ import Testing @Suite("ListSelectIndependentOption") struct ListSelectIndependentOptionTests { - @Test(arguments: [ - EncodeFixture.listSelectIndependentOption(.remote, "REMOTE"), - EncodeFixture.listSelectIndependentOption(.option(.init(key: .standard("test"), value: nil)), "test"), - EncodeFixture.listSelectIndependentOption(.specialUse, "SPECIAL-USE"), - ]) + @Test( + "encode", + arguments: [ + EncodeFixture.listSelectIndependentOption(.remote, "REMOTE"), + EncodeFixture.listSelectIndependentOption(.option(.init(key: .standard("test"), value: nil)), "test"), + EncodeFixture.listSelectIndependentOption(.specialUse, "SPECIAL-USE"), + ] + ) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() } + + @Test( + "parse", + arguments: [ + ParseFixture.listSelectIndependentOption("REMOTE", " ", expected: .success(.remote)), + ParseFixture.listSelectIndependentOption("SPECIAL-USE", " ", expected: .failure), + ParseFixture.listSelectIndependentOption("", "", expected: .incompleteMessage), + ] + ) + func parse(_ fixture: ParseFixture) { + fixture.checkParsing() + } } // MARK: - @@ -43,3 +58,18 @@ extension EncodeFixture { ) } } + +extension ParseFixture { + fileprivate static func listSelectIndependentOption( + _ input: String, + _ terminator: String = "\r", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseListSelectIndependentOption + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/List/ListSelectOption+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/List/ListSelectOption+Tests.swift index 7a50492b..795d3f68 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/List/ListSelectOption+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/List/ListSelectOption+Tests.swift @@ -25,6 +25,10 @@ struct ListSelectOptionTests { EncodeFixture.listSelectOption(.remote, "REMOTE"), EncodeFixture.listSelectOption(.recursiveMatch, "RECURSIVEMATCH"), EncodeFixture.listSelectOption(.specialUse, "SPECIAL-USE"), + EncodeFixture.listSelectOption( + .option(.init(key: .standard("MYEXT"), value: nil)), + "MYEXT" + ), ] ) func encodeSingleOption(_ fixture: EncodeFixture) { @@ -48,6 +52,25 @@ struct ListSelectOptionTests { func encodeMultipleOptions(_ fixture: EncodeFixture) { fixture.checkEncoding() } + + @Test( + "parse single option", + arguments: [ + ParseFixture.listSelectOption("SUBSCRIBED", " ", expected: .success(.subscribed)), + ParseFixture.listSelectOption("REMOTE", " ", expected: .success(.remote)), + ParseFixture.listSelectOption("RECURSIVEMATCH", " ", expected: .success(.recursiveMatch)), + ParseFixture.listSelectOption("SPECIAL-USE", " ", expected: .success(.specialUse)), + ParseFixture.listSelectOption( + "MYEXT", + expected: .success(.option(.init(key: .standard("MYEXT"), value: nil))) + ), + ParseFixture.listSelectOption("(invalid)", "", expected: .failure), + ParseFixture.listSelectOption("", "", expected: .incompleteMessage), + ] + ) + func parseSingleOption(_ fixture: ParseFixture) { + fixture.checkParsing() + } } // MARK: - @@ -73,3 +96,18 @@ extension EncodeFixture { ) } } + +extension ParseFixture { + fileprivate static func listSelectOption( + _ input: String, + _ terminator: String = "\r", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseListSelectOption + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxAttribute+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxAttribute+Tests.swift index 477bf2c5..221e371e 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxAttribute+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxAttribute+Tests.swift @@ -137,6 +137,21 @@ struct MailboxAttributeTests { func parseMailboxStatus(_ fixture: ParseFixture) { fixture.checkParsing() } + @Test( + "parse status option", + arguments: [ + ParseFixture.statusOption("STATUS (MESSAGES)", expected: .success([.messageCount])), + ParseFixture.statusOption( + "STATUS (MESSAGES RECENT UNSEEN)", + expected: .success([.messageCount, .recentCount, .unseenCount]) + ), + ParseFixture.statusOption("STATUS (UIDNEXT)", expected: .success([.uidNext])), + ParseFixture.statusOption("", "", expected: .incompleteMessage), + ] + ) + func parseStatusOption(_ fixture: ParseFixture<[MailboxAttribute]>) { + fixture.checkParsing() + } } // MARK: - @@ -192,3 +207,18 @@ extension ParseFixture { ) } } + +extension ParseFixture<[MailboxAttribute]> { + fileprivate static func statusOption( + _ input: String, + _ terminator: String = "\r", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseStatusOption + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxData+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxData+Tests.swift index 486a0386..9420e37c 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxData+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxData+Tests.swift @@ -61,6 +61,11 @@ struct MailboxDataTests { .search([20, 23], ModificationSequenceValue(917_162_500)), "SEARCH 20 23 (MODSEQ 917162500)" ), + EncodeFixture.mailboxData(.recent(5678), "5678 RECENT"), + EncodeFixture.mailboxData( + .searchSort(.init(identifiers: [1, 2, 3], modificationSequence: 2)), + "SEARCH 1 2 3 (MODSEQ 2)" + ), EncodeFixture.mailboxData( .uidBatches( UIDBatchesResponse( @@ -187,6 +192,7 @@ struct MailboxDataTests { ParseFixture.mailboxData("SEARCH", "\r\n", expected: .success(.search([]))), ParseFixture.mailboxData("SEARCH 1", "\r\n", expected: .success(.search([1]))), ParseFixture.mailboxData("SEARCH 1 2 3 4 5", "\r\n", expected: .success(.search([1, 2, 3, 4, 5]))), + ParseFixture.mailboxData("SEARCH", " 4294967296\r\n", expected: .success(.search([]))), ParseFixture.mailboxData( "NAMESPACE NIL NIL NIL", "\r\n", diff --git a/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxGroup+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxGroup+Tests.swift new file mode 100644 index 00000000..627f392b --- /dev/null +++ b/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxGroup+Tests.swift @@ -0,0 +1,95 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import NIO +@_spi(NIOIMAPInternal) @testable import NIOIMAPCore +import Testing + +@Suite("MailboxGroup") +struct MailboxGroupTests { + @Test( + "encode email address group", + arguments: [ + EncodeFixture.emailAddressGroup( + EmailAddressGroup( + groupName: ByteBuffer(string: "Team"), + sourceRoot: ByteBuffer(string: "root"), + children: [ + .singleAddress( + EmailAddress( + personName: "Alice", + sourceRoot: nil, + mailbox: "alice", + host: "example.com" + ) + ) + ] + ), + #"(NIL "root" "Team" NIL)("Alice" NIL "alice" "example.com")(NIL "root" NIL NIL)"# + ) + ] + ) + func encodeEmailAddressGroup(_ fixture: EncodeFixture) { + fixture.checkEncoding() + } + + @Test( + "encode email address or group", + arguments: [ + EncodeFixture.emailAddressOrGroup( + .group( + EmailAddressGroup( + groupName: ByteBuffer(string: "Mgmt"), + sourceRoot: nil, + children: [] + ) + ), + #"(NIL NIL "Mgmt" NIL)(NIL NIL NIL NIL)"# + ) + ] + ) + func encodeEmailAddressOrGroup(_ fixture: EncodeFixture) { + fixture.checkEncoding() + } +} + +// MARK: - Fixtures + +extension EncodeFixture { + fileprivate static func emailAddressGroup( + _ input: EmailAddressGroup, + _ expectedString: String + ) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeEmailAddressGroup($1) } + ) + } +} + +extension EncodeFixture { + fileprivate static func emailAddressOrGroup( + _ input: EmailAddressListElement, + _ expectedString: String + ) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeEmailAddressOrGroup($1) } + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxID+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxID+Tests.swift new file mode 100644 index 00000000..7c9595bc --- /dev/null +++ b/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxID+Tests.swift @@ -0,0 +1,68 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import NIO +@_spi(NIOIMAPInternal) @testable import NIOIMAPCore +import Testing + +@Suite("MailboxID") +struct MailboxIDTests { + @Test( + "encode", + arguments: [ + EncodeFixture.mailboxID("Abc123", "Abc123"), + EncodeFixture.mailboxID("a-b_c", "a-b_c"), + ] + ) + func encode(_ fixture: EncodeFixture) { + fixture.checkEncoding() + } + + @Test( + "string literal init", + arguments: [ + ("ValidID123", true), + ("a", true), + ("", false), + ("has space", false), + ("has@symbol", false), + ] as [(String, Bool)] + ) + func stringInit(_ fixture: (String, Bool)) { + #expect((MailboxID(fixture.0) != nil) == fixture.1) + } + + @Test( + "string conversion", + arguments: [ + ("ValidID", "ValidID") + ] as [(MailboxID, String)] + ) + func stringConversion(_ fixture: (MailboxID, String)) { + #expect(String(fixture.0) == fixture.1) + } +} + +// MARK: - + +extension EncodeFixture { + fileprivate static func mailboxID(_ input: MailboxID, _ expectedString: String) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeMailboxID($1) } + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxInfo+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxInfo+Tests.swift index 6d411df3..5ddb7dc9 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxInfo+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxInfo+Tests.swift @@ -78,6 +78,22 @@ struct MailboxInfoTests { ), #"(\Subscribed \HasNoChildren) "." "Archive/2024""# ), + EncodeFixture.mailboxInfo( + MailboxInfo( + attributes: [.unmarked], + path: try! .init(name: MailboxName("Old"), pathSeparator: "\\"), + extensions: [:] + ), + #"(\Unmarked) "\" "Old""# + ), + EncodeFixture.mailboxInfo( + MailboxInfo( + attributes: [.nonExistent], + path: try! .init(name: MailboxName("Ghost"), pathSeparator: "\""), + extensions: [:] + ), + #"(\Nonexistent) "\\" "Ghost""# + ), ]) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() @@ -133,6 +149,39 @@ struct MailboxInfoTests { ), ParseFixture.mailboxInfo(#"() ""#, "", expected: .incompleteMessageIgnoringBufferModifications), ParseFixture.mailboxInfo(#"() "\" inbox"#, "", expected: .failureIgnoringBufferModifications), + // Extended list — empty extensions: covers parseMailboxListExtended entry + empty content path + ParseFixture.mailboxInfo( + "() NIL inbox ()", + "\r", + expected: .success(.init(attributes: [], path: try! .init(name: .inbox), extensions: [:])) + ), + // Extended list — one item: covers parseMailboxListExtendedItem and value parsing + ParseFixture.mailboxInfo( + "() NIL inbox (CHILDINFO (SUBSCRIBED))", + "\r", + expected: .success( + .init( + attributes: [], + path: try! .init(name: .inbox), + extensions: [ByteBuffer(string: "CHILDINFO"): .comp(["SUBSCRIBED"])] + ) + ) + ), + // Extended list — two items: covers parseZeroOrMore additional item path (line 244) + ParseFixture.mailboxInfo( + "() NIL inbox (KEY1 (VAL1) KEY2 (VAL2))", + "\r", + expected: .success( + .init( + attributes: [], + path: try! .init(name: .inbox), + extensions: [ + ByteBuffer(string: "KEY1"): .comp(["VAL1"]), + ByteBuffer(string: "KEY2"): .comp(["VAL2"]), + ] + ) + ) + ), ]) func parse(_ fixture: ParseFixture) { fixture.checkParsing() diff --git a/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxName+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxName+Tests.swift index 89e11e7a..ffdeed18 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxName+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Mailbox/MailboxName+Tests.swift @@ -136,6 +136,62 @@ private struct MailboxPathTests { } } + @Test("init with non-ASCII path separator throws InvalidPathSeparatorError") + func initWithNonASCIIPathSeparatorThrows() { + #expect(throws: InvalidPathSeparatorError.self) { + try MailboxPath(name: .init("box"), pathSeparator: "\u{00A3}") + } + } + + @Test("validateUTF8String with valid UTF-8") + func validateUTF8StringValid() { + let path = try! MailboxPath(name: .inbox) + let validBytes = ByteBuffer(string: "hello") + #expect(path.validateUTF8String(validBytes) == "hello") + } + + @Test("validateUTF8String with invalid UTF-8 returns nil") + func validateUTF8StringInvalid() { + let path = try! MailboxPath(name: .inbox) + var invalidBytes = ByteBuffer() + invalidBytes.writeBytes([0x80, 0xFF]) + #expect(path.validateUTF8String(invalidBytes) == nil) + } + + @Test("displayStringComponents with no path separator returns full name") + func displayStringComponentsNilPathSeparator() { + let path = try! MailboxPath(name: .init("INBOX")) + let components = path.displayStringComponents() + #expect(components == ["INBOX"]) + } + + @Test("decodeBufferToString falls back on invalid modified UTF-7") + func decodeBufferToStringFallback() { + // "&AQID-" in modified UTF-7 decodes base64 "AQID" → 3 bytes (odd count) → throws + // The catch falls back to UTF-8 interpretation of the original bytes + let path = try! MailboxPath( + name: MailboxName(ByteBuffer(string: "box/&AQID-/sub")), + pathSeparator: "/" + ) + let components = path.displayStringComponents() + #expect(components == ["box", "&AQID-", "sub"]) + } + + @Test("makeRootMailbox throws when name contains separator") + func makeRootMailboxThrowsWhenNameContainsSeparator() { + #expect(throws: InvalidMailboxNameError.self) { + try MailboxPath.makeRootMailbox(displayName: "box/subbox", pathSeparator: "/") + } + } + + @Test("makeSubMailbox throws when display name contains separator") + func makeSubMailboxThrowsWhenNameContainsSeparator() { + let path = try! MailboxPath(name: .init("INBOX"), pathSeparator: "/") + #expect(throws: InvalidMailboxNameError.self) { + try path.makeSubMailbox(displayName: "sub/folder") + } + } + @Test( "custom debug string convertible", arguments: [ diff --git a/Tests/NIOIMAPCoreTests/Grammar/Message/EmailID+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Message/EmailID+Tests.swift new file mode 100644 index 00000000..95aa307e --- /dev/null +++ b/Tests/NIOIMAPCoreTests/Grammar/Message/EmailID+Tests.swift @@ -0,0 +1,91 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import NIO +@_spi(NIOIMAPInternal) @testable import NIOIMAPCore +import Testing + +@Suite("EmailID") +struct EmailIDTests { + @Test( + "failable init", + arguments: [ + ("abc123", true), + ("ABC-XYZ_123", true), + ("a", true), + (String(repeating: "a", count: 255), true), + ("", false), + ("abc!", false), + (String(repeating: "a", count: 256), false), + ] as [(String, Bool)] + ) + func faillableInit(_ fixture: (String, Bool)) { + let result = EmailID(fixture.0) + #expect((result != nil) == fixture.1) + } + + @Test( + "string conversion", + arguments: [ + ("abc123", "abc123"), + ("ABC-XYZ_123", "ABC-XYZ_123"), + ] as [(String, String)] + ) + func stringConversion(_ fixture: (String, String)) { + let id = EmailID(fixture.0)! + #expect(String(id) == fixture.1) + } + + @Test("string literal init") + func stringLiteralInit() { + let id: EmailID = "abc123" + #expect(String(id) == "abc123") + } + + @Test( + "debug description", + arguments: [ + ("abc123", "(abc123)"), + ("XYZ-789", "(XYZ-789)"), + ] as [(String, String)] + ) + func debugDescription(_ fixture: (String, String)) { + let id = EmailID(fixture.0)! + #expect(id.debugDescription == fixture.1) + } + + @Test( + "encode", + arguments: [ + EncodeFixture.emailID("abc123", "abc123"), + EncodeFixture.emailID("XYZ-789_000", "XYZ-789_000"), + ] + ) + func encode(_ fixture: EncodeFixture) { + fixture.checkEncoding() + } +} + +// MARK: - Fixtures + +extension EncodeFixture { + fileprivate static func emailID(_ rawValue: String, _ expectedString: String) -> Self { + EncodeFixture( + input: EmailID(rawValue)!, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeEmailID($1) } + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Message/GmailLabel+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Message/GmailLabel+Tests.swift new file mode 100644 index 00000000..52cb14cf --- /dev/null +++ b/Tests/NIOIMAPCoreTests/Grammar/Message/GmailLabel+Tests.swift @@ -0,0 +1,99 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import NIO +@_spi(NIOIMAPInternal) @testable import NIOIMAPCore +import Testing + +@Suite("GmailLabel") +struct GmailLabelTests { + @Test( + "encode", + arguments: [ + EncodeFixture.gmailLabel(GmailLabel(ByteBuffer(string: "Inbox")), #""Inbox""#), + EncodeFixture.gmailLabel(GmailLabel(ByteBuffer(string: "\\Sent")), #"\Sent"#), + EncodeFixture.gmailLabel(GmailLabel(ByteBuffer(string: "My Label")), #""My Label""#), + ] + ) + func encode(_ fixture: EncodeFixture) { + fixture.checkEncoding() + } + + @Test("init from mailbox name") + func initFromMailboxName() { + let mailbox = MailboxName("Sent") + let label = GmailLabel(mailboxName: mailbox) + let encoded = EncodeBuffer.makeDescription { _ = $0.writeGmailLabel(label) } + #expect(encoded == "\"Sent\"") + } + + @Test("init from use attribute") + func initFromUseAttribute() { + let attr = UseAttribute("\\Sent") + let label = GmailLabel(useAttribute: attr) + let encoded = EncodeBuffer.makeDescription { _ = $0.writeGmailLabel(label) } + #expect(encoded == "\\Sent") + } + + @Test( + "makeDisplayString", + arguments: [ + (GmailLabel(ByteBuffer(string: "Inbox")), "Inbox"), + (GmailLabel(ByteBuffer(string: "&invalid-")), "&invalid-"), // invalid modified UTF-7 falls back to UTF-8 + ] as [(GmailLabel, String)] + ) + func makeDisplayString(_ fixture: (GmailLabel, String)) { + #expect(fixture.0.makeDisplayString() == fixture.1) + } + + @Test( + "parse", + arguments: [ + ParseFixture.gmailLabel(#""Inbox""#, expected: .success(GmailLabel(ByteBuffer(string: "Inbox")))), + ParseFixture.gmailLabel(#"\Sent"#, expected: .success(GmailLabel(ByteBuffer(string: "\\Sent")))), + ParseFixture.gmailLabel("", "", expected: .incompleteMessage), + ] + ) + func parse(_ fixture: ParseFixture) { + fixture.checkParsing() + } +} + +// MARK: - + +extension EncodeFixture { + fileprivate static func gmailLabel(_ input: GmailLabel, _ expectedString: String) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeGmailLabel($1) } + ) + } +} + +extension ParseFixture { + fileprivate static func gmailLabel( + _ input: String, + _ terminator: String = " ", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseGmailLabel + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Message/MessageAtributesTests.swift b/Tests/NIOIMAPCoreTests/Grammar/Message/MessageAtributesTests.swift index 4fb63cf5..e9ffc9e3 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Message/MessageAtributesTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Message/MessageAtributesTests.swift @@ -98,6 +98,14 @@ struct MessageAttributeTests { EncodeFixture.messageAttribute(.emailID(.init("123-456-789")!), "EMAILID (123-456-789)"), EncodeFixture.messageAttribute(.threadID(.init("123-456-789")!), "THREADID (123-456-789)"), EncodeFixture.messageAttribute(.threadID(nil), "THREADID NIL"), + EncodeFixture.messageAttribute(.body(.invalid, hasExtensionData: false), "BODY ()"), + EncodeFixture.messageAttribute(.body(.invalid, hasExtensionData: true), "BODYSTRUCTURE ()"), + EncodeFixture.messageAttribute(.nilBody(.rfc822Text), "RFC822.TEXT NIL"), + EncodeFixture.messageAttribute(.nilBody(.rfc822Header), "RFC822.HEADER NIL"), + EncodeFixture.messageAttribute( + .nilBody(.body(section: .init(part: [4], kind: .text), offset: 5)), + "BODY[4.TEXT]<5> NIL" + ), ]) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() @@ -138,7 +146,7 @@ struct MessageAttributeTests { fixture.check() } - @Test(arguments: Self.parseMessageAttributeFixtures()) + @Test("parse", arguments: Self.parseMessageAttributeFixtures()) func parse(_ fixture: ParseFixture) { fixture.checkParsing() } @@ -499,3 +507,133 @@ extension ParseFixture { ) } } + +// MARK: - writeMessageAttribute_rfc822 helpers + +extension MessageAttributeTests { + @Test( + "encode rfc822 helpers", + arguments: [ + Rfc822Fixture(method: .rfc822, string: nil, expected: "RFC822 NIL"), + Rfc822Fixture(method: .rfc822, string: ByteBuffer(string: "hi"), expected: "RFC822 \"hi\""), + Rfc822Fixture(method: .rfc822Text, string: nil, expected: "RFC822.TEXT NIL"), + Rfc822Fixture(method: .rfc822Text, string: ByteBuffer(string: "body"), expected: "RFC822.TEXT \"body\""), + Rfc822Fixture(method: .rfc822Header, string: nil, expected: "RFC822.HEADER NIL"), + Rfc822Fixture(method: .rfc822Header, string: ByteBuffer(string: "hdr"), expected: "RFC822.HEADER \"hdr\""), + ] + ) + func encodeRfc822Helpers(_ fixture: Rfc822Fixture) { + var buffer = EncodeBuffer.serverEncodeBuffer( + buffer: ByteBufferAllocator().buffer(capacity: 128), + options: ResponseEncodingOptions(), + loggingMode: false + ) + switch fixture.method { + case .rfc822: _ = buffer.writeMessageAttribute_rfc822(fixture.string) + case .rfc822Text: _ = buffer.writeMessageAttribute_rfc822Text(fixture.string) + case .rfc822Header: _ = buffer.writeMessageAttribute_rfc822Header(fixture.string) + } + var remaining = buffer + let chunk = remaining.nextChunk() + let actualString = String(buffer: chunk.bytes) + #expect(actualString.mappingControlPictures() == fixture.expected.mappingControlPictures()) + } + + @Test( + "encode body section text", + arguments: [ + BodySectionTextFixture(number: nil, size: 5, expected: "BODY[TEXT] {5}\r\n"), + BodySectionTextFixture(number: 3, size: 8, expected: "BODY[TEXT]<3> {8}\r\n"), + ] + ) + func encodeBodySectionText(_ fixture: BodySectionTextFixture) { + var buffer = EncodeBuffer.serverEncodeBuffer( + buffer: ByteBufferAllocator().buffer(capacity: 128), + options: ResponseEncodingOptions(), + loggingMode: false + ) + _ = buffer.writeMessageAttribute_bodySectionText(number: fixture.number, size: fixture.size) + var remaining = buffer + let chunk = remaining.nextChunk() + let actualString = String(buffer: chunk.bytes) + #expect(actualString.mappingControlPictures() == fixture.expected.mappingControlPictures()) + } +} + +enum Rfc822Method: Sendable { case rfc822, rfc822Text, rfc822Header } + +struct Rfc822Fixture: Sendable, CustomTestStringConvertible { + var method: Rfc822Method + var string: ByteBuffer? + var expected: String + + var testDescription: String { expected } +} + +struct BodySectionTextFixture: Sendable, CustomTestStringConvertible { + var number: Int? + var size: Int + var expected: String + + var testDescription: String { expected } +} + +extension MessageAttributeTests { + @Test( + "encode body section attribute", + arguments: [ + BodySectionFixture(section: nil, number: nil, string: nil, expected: "BODY[] NIL"), + BodySectionFixture( + section: .init(kind: .header), + number: nil, + string: "header data", + expected: #"BODY[HEADER] "header data""# + ), + BodySectionFixture( + section: .init(part: [1, 2], kind: .text), + number: 0, + string: "body text", + expected: #"BODY[1.2.TEXT]<0> "body text""# + ), + BodySectionFixture( + section: .init(kind: .complete), + number: 512, + string: nil, + expected: "BODY[]<512> NIL" + ), + ] + ) + func encodeBodySection(_ fixture: BodySectionFixture) { + fixture.checkEncoding() + } +} + +struct BodySectionFixture: Sendable, CustomTestStringConvertible { + var section: SectionSpecifier? + var number: Int? + var string: ByteBuffer? + var expected: String + + init(section: SectionSpecifier?, number: Int?, string: ByteBuffer?, expected: String) { + self.section = section + self.number = number + self.string = string + self.expected = expected + } + + var testDescription: String { expected } + + func checkEncoding() { + var buffer = EncodeBuffer.serverEncodeBuffer( + buffer: ByteBufferAllocator().buffer(capacity: 128), + options: ResponseEncodingOptions(), + loggingMode: false + ) + let size = buffer.writeMessageAttribute_bodySection(section, number: number, string: string) + var remaining = buffer + let chunk = remaining.nextChunk() + let actualString = String(buffer: chunk.bytes) + #expect(size == expected.utf8.count) + #expect(actualString.mappingControlPictures() == expected.mappingControlPictures()) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Message/MessageDataTests.swift b/Tests/NIOIMAPCoreTests/Grammar/Message/MessageDataTests.swift index 13d4dfa3..2a475d72 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Message/MessageDataTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Message/MessageDataTests.swift @@ -24,11 +24,26 @@ struct MessageDataTests { EncodeFixture.messageData(.vanishedEarlier(.all), "VANISHED (EARLIER) 1:*"), EncodeFixture.messageData(.generateAuthorizedURL(["test"]), #"GENURLAUTH "test""#), EncodeFixture.messageData(.generateAuthorizedURL(["test1", "test2"]), #"GENURLAUTH "test1" "test2""#), + EncodeFixture.messageData(.urlFetch([.init(url: "url", data: nil)]), #"URLFETCH("url" NIL)"#), + EncodeFixture.messageData( + .urlFetch([.init(url: "url1", data: nil), .init(url: "url2", data: "data")]), + #"URLFETCH("url1" NIL "url2" "data")"# + ), ]) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() } + @Test( + "encode end", + arguments: [ + EncodeFixture.messageDataEnd(.expunge(1), ")") + ] + ) + func encodeEnd(_ fixture: EncodeFixture) { + fixture.checkEncoding() + } + @Test(arguments: [ ParseFixture.messageData("3 EXPUNGE", expected: .success(.expunge(3))), ParseFixture.messageData("VANISHED 1:3", expected: .success(.vanished([1...3]))), @@ -67,6 +82,18 @@ extension EncodeFixture { encoder: { $0.writeMessageData($1) } ) } + + fileprivate static func messageDataEnd( + _ input: MessageData, + _ expectedString: String + ) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeMessageDataEnd($1) } + ) + } } extension ParseFixture { diff --git a/Tests/NIOIMAPCoreTests/Grammar/Message/ThreadID+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Message/ThreadID+Tests.swift new file mode 100644 index 00000000..e0f18c44 --- /dev/null +++ b/Tests/NIOIMAPCoreTests/Grammar/Message/ThreadID+Tests.swift @@ -0,0 +1,46 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import NIO +@_spi(NIOIMAPInternal) @testable import NIOIMAPCore +import Testing + +@Suite("ThreadID") +struct ThreadIDTests { + @Test("valid string init") + func validStringInit() { + let valid: String = "abc123" + #expect(ThreadID(valid) != nil) + } + + @Test("invalid string init returns nil") + func invalidStringInitReturnsNil() { + let empty: String = "" + #expect(ThreadID(empty) == nil) + let withSpace: String = "has space" + #expect(ThreadID(withSpace) == nil) + } + + @Test("string conversion") + func stringConversion() { + let id: ThreadID = "abc123" + #expect(String(id) == "abc123") + } + + @Test("debug description") + func debugDescription() { + let id: ThreadID = "abc123" + #expect(id.debugDescription == "(abc123)") + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/MessageID+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/MessageID+Tests.swift new file mode 100644 index 00000000..f3be7ce0 --- /dev/null +++ b/Tests/NIOIMAPCoreTests/Grammar/MessageID+Tests.swift @@ -0,0 +1,53 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import NIO +@_spi(NIOIMAPInternal) @testable import NIOIMAPCore +import Testing + +@Suite("MessageID") +struct MessageIDTests { + @Test( + "encode", + arguments: [ + EncodeFixture.messageID(.init(""), "\"\""), + EncodeFixture.messageID( + .init(""), + "\"\"" + ), + ] + ) + func encode(_ fixture: EncodeFixture) { + fixture.checkEncoding() + } + + @Test("string conversion") + func stringConversion() { + let id = MessageID("") + #expect(String(id) == "") + } +} + +// MARK: - + +extension EncodeFixture { + fileprivate static func messageID(_ input: MessageID, _ expectedString: String) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeMessageID($1) } + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/MessageIdentifierRange+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/MessageIdentifierRange+Tests.swift index a7a89269..9e2228f1 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/MessageIdentifierRange+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/MessageIdentifierRange+Tests.swift @@ -53,6 +53,36 @@ struct MessageIdentifierRangeTests { let output = MessageIdentifierRange(input) #expect(output == 5...6) } + + @Test("init from partial range through") + func initFromPartialRangeThrough() { + let range = MessageIdentifierRange(...UID(10)) + #expect(range.lowerBound == UID.min) + #expect(range.upperBound == UID(10)) + } + + @Test("init from partial range from") + func initFromPartialRangeFrom() { + let range = MessageIdentifierRange(UID(5)...) + #expect(range.lowerBound == UID(5)) + #expect(range.upperBound == UID.max) + } + + @Test("convert UID range to UnknownMessageIdentifier") + func convertUIDRangeToUnknownMessageIdentifier() { + let uidRange = MessageIdentifierRange(UID(3)...UID(7)) + let unknown = MessageIdentifierRange(uidRange) + #expect(unknown.lowerBound.rawValue == 3) + #expect(unknown.upperBound.rawValue == 7) + } + + @Test("convert SequenceNumber range to UnknownMessageIdentifier") + func convertSequenceNumberRangeToUnknownMessageIdentifier() { + let seqRange = MessageIdentifierRange(SequenceNumber(2)...SequenceNumber(5)) + let unknown = MessageIdentifierRange(seqRange) + #expect(unknown.lowerBound.rawValue == 2) + #expect(unknown.upperBound.rawValue == 5) + } } // MARK: - diff --git a/Tests/NIOIMAPCoreTests/Grammar/MessageIdentifierSet+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/MessageIdentifierSet+Tests.swift index 7ca8a69a..aef3a2b0 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/MessageIdentifierSet+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/MessageIdentifierSet+Tests.swift @@ -45,6 +45,7 @@ struct MessageIdentifierSetTests { ), ParseFixture.messageIdentifierSet("1:*", "\r\n", expected: .success(.all)), ParseFixture.messageIdentifierSet("a", " ", expected: .failure), + ParseFixture.messageIdentifierSet("0", "\r\n", expected: .failure), ParseFixture.messageIdentifierSet("1234", "", expected: .incompleteMessage), ParseFixture.messageIdentifierSet("", "", expected: .incompleteMessage), ]) @@ -98,6 +99,79 @@ struct MessageIdentifierSetTests { #expect(UIDSet.all.suffix(1) == UIDSet([4_294_967_295])) #expect(UIDSet.all.suffix(2) == UIDSet([4_294_967_294...4_294_967_295])) } + + @Test("RangeView array literal initializer") + func rangeViewArrayLiteral() { + let rv: MessageIdentifierSet.RangeView = [MessageIdentifierRange(1...5)] + let set = UIDSet([1...5]) + #expect(rv == set.ranges) + } + + @Test("RangeView equality") + func rangeViewEquality() { + let set1 = UIDSet([1...5, 10...15]) + let set2 = UIDSet([1...5, 10...15]) + let set3 = UIDSet([1...5]) + #expect(set1.ranges == set2.ranges) + #expect(set1.ranges != set3.ranges) + } + + @Test("init from ClosedRange") + func initFromClosedRange() { + let set = MessageIdentifierSet(1...10 as ClosedRange) + #expect(set == UIDSet([1...10])) + } + + @Test("init from PartialRangeThrough") + func initFromPartialRangeThrough() { + let set = MessageIdentifierSet(...10 as PartialRangeThrough) + #expect(set == UIDSet([1...10])) + } + + @Test("init from PartialRangeFrom") + func initFromPartialRangeFrom() { + let set = MessageIdentifierSet(1... as PartialRangeFrom) + #expect(set.contains(1)) + #expect(set.contains(UID(rawValue: 4_294_967_295))) + } + + @Test( + "init from Range", + arguments: [ + (1..<1 as Range, UIDSet()), + (1..<5 as Range, UIDSet([1...4])), + ] as [(Range, UIDSet)] + ) + func initFromRange(_ fixture: (Range, UIDSet)) { + #expect(MessageIdentifierSet(fixture.0) == fixture.1) + } + + @Test("Index comparison operators") + func indexComparison() { + let set = UIDSet([1...3, 10...12]) + let indices = Array(set.indices) + // indices[0] < indices[1] < indices[2] < indices[3] etc. + #expect(indices[0] < indices[1]) + #expect(indices[1] > indices[0]) + #expect(!(indices[0] > indices[1])) + // Compare across range boundaries + #expect(indices[2] < indices[3]) + #expect(indices[3] > indices[2]) + } + + @Test("convert UnknownMessageIdentifier from UID set") + func convertUnknownFromUID() { + let uidSet: MessageIdentifierSet = [1...5, 10...15] + let unknown = MessageIdentifierSet(uidSet) + #expect(unknown == [1...5, 10...15]) + } + + @Test("convert UnknownMessageIdentifier from SequenceNumber set") + func convertUnknownFromSequenceNumber() { + let seqSet: MessageIdentifierSet = [1...5, 10...15] + let unknown = MessageIdentifierSet(seqSet) + #expect(unknown == [1...5, 10...15]) + } } // MARK: - diff --git a/Tests/NIOIMAPCoreTests/Grammar/Metadata/MetadataEntryName+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Metadata/MetadataEntryName+Tests.swift new file mode 100644 index 00000000..4e2ff40f --- /dev/null +++ b/Tests/NIOIMAPCoreTests/Grammar/Metadata/MetadataEntryName+Tests.swift @@ -0,0 +1,44 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import NIO +@_spi(NIOIMAPInternal) @testable import NIOIMAPCore +import Testing + +@Suite("MetadataEntryName") +struct MetadataEntryNameTests { + @Test( + "string round trip", + arguments: [ + (MetadataEntryName("/private/vendor/example/color"), "/private/vendor/example/color"), + (MetadataEntryName(ByteBuffer(string: "/shared/admin/quota")), "/shared/admin/quota"), + ] as [(MetadataEntryName, String)] + ) + func stringRoundTrip(_ fixture: (MetadataEntryName, String)) { + #expect(String(fixture.0) == fixture.1) + } + + @Test("equality is based on content") + func equalityIsBasedOnContent() { + let a = MetadataEntryName("/private/comment") + let b: MetadataEntryName = "/private/comment" + #expect(a == b) + } + + @Test("init from String variable") + func initFromStringVariable() { + let a = "/private/variable" + #expect(String(MetadataEntryName(a)) == "/private/variable") + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Modifier/ModifierSequenceValue+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Modifier/ModifierSequenceValue+Tests.swift index 1d2695bf..46e1a0d7 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Modifier/ModifierSequenceValue+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Modifier/ModifierSequenceValue+Tests.swift @@ -30,6 +30,55 @@ struct ModificationSequenceValueTests { #expect(ModificationSequenceValue(exactly: UInt64.max) == nil) } + @Test("binary integer conversion") + func binaryIntegerConversion() { + let v = ModificationSequenceValue(integerLiteral: 42) + #expect(Int(v) == 42) + #expect(UInt64(v) == 42) + } + + @Test("ordering operators") + func orderingOperators() { + let a = ModificationSequenceValue(integerLiteral: 10) + let b = ModificationSequenceValue(integerLiteral: 20) + #expect(a <= b) + #expect(b <= b) + #expect(!(b <= a)) + } + + @Test( + "less-than operator", + arguments: [ + (ModificationSequenceValue(integerLiteral: 10), ModificationSequenceValue(integerLiteral: 20), true), + (ModificationSequenceValue(integerLiteral: 20), ModificationSequenceValue(integerLiteral: 10), false), + (ModificationSequenceValue(integerLiteral: 10), ModificationSequenceValue(integerLiteral: 10), false), + ] as [(ModificationSequenceValue, ModificationSequenceValue, Bool)] + ) + func lessThanOperator(_ fixture: (ModificationSequenceValue, ModificationSequenceValue, Bool)) { + #expect((fixture.0 < fixture.1) == fixture.2) + } + + @Test("distance and advanced") + func distanceAndAdvanced() { + let start = ModificationSequenceValue(integerLiteral: 10) + let end = ModificationSequenceValue(integerLiteral: 15) + #expect(start.distance(to: end) == 5) + #expect(end.distance(to: start) == -5) + let advanced = start.advanced(by: 5) + #expect(advanced == end) + } + + #if swift(>=6.2) + @Test("overflow triggers precondition failure") func overflowPreconditionFailure() async { + await #expect( + processExitsWith: ExitTest.Condition.failure, + performing: { + _ = ModificationSequenceValue(UInt64(Int64.max) + 1) + } + ) + } + #endif + @Test(arguments: [ EncodeFixture.modificationSequenceValue(.init(integerLiteral: 0), "0"), EncodeFixture.modificationSequenceValue(.init(integerLiteral: 1), "1"), diff --git a/Tests/NIOIMAPCoreTests/Grammar/Namespace/NamespaceDescription+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Namespace/NamespaceDescription+Tests.swift index bb5a95e9..b9985944 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Namespace/NamespaceDescription+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Namespace/NamespaceDescription+Tests.swift @@ -47,10 +47,51 @@ struct NamespaceDescriptionTests { " ", expected: .success(.init(string: "str", char: "a", responseExtensions: [:])) ), + ParseFixture.namespaceDescription( + "(\"str\" \"\r\")", + " ", + expected: .failureIgnoringBufferModifications + ), + ParseFixture.namespaceDescription( + "(\"str\" NIL \"ext-key\" (\"val1\" \"val2\"))", + " ", + expected: .success( + .init( + string: "str", + char: nil, + responseExtensions: ["ext-key": ["val1", "val2"]] + ) + ) + ), ]) func parse(_ fixture: ParseFixture) { fixture.checkParsing() } + + @Test( + "parse NAMESPACE", + arguments: [ + ParseFixture.namespace( + "NIL", + expected: .success([]) + ), + ParseFixture.namespace( + "((\"#mh/\" \"/\"))", + expected: .success([.init(string: "#mh/", char: "/", responseExtensions: [:])]) + ), + ParseFixture.namespace( + "((\"\" \"/\")(\"#mh/\" \"/\"))", + expected: .success([ + .init(string: "", char: "/", responseExtensions: [:]), + .init(string: "#mh/", char: "/", responseExtensions: [:]), + ]) + ), + ParseFixture.namespace("", "", expected: .incompleteMessage), + ] + ) + func parseNamespace(_ fixture: ParseFixture<[NamespaceDescription]>) { + fixture.checkParsing() + } } // MARK: - @@ -83,3 +124,18 @@ extension ParseFixture { ) } } + +extension ParseFixture<[NamespaceDescription]> { + fileprivate static func namespace( + _ input: String, + _ terminator: String = "\r", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseNamespace + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Notify/MailboxFilter+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Notify/MailboxFilter+Tests.swift index 374177cd..5b699420 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Notify/MailboxFilter+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Notify/MailboxFilter+Tests.swift @@ -56,31 +56,34 @@ struct MailboxFilterTests { fixture.checkEncoding() } - @Test(arguments: [ - ParseFixture.filterMailboxes("inboxes", " ", expected: .success(.inboxes)), - ParseFixture.filterMailboxes("personal", " ", expected: .success(.personal)), - ParseFixture.filterMailboxes("subscribed", " ", expected: .success(.subscribed)), - ParseFixture.filterMailboxes("selected", " ", expected: .success(.selected)), - ParseFixture.filterMailboxes("selected-delayed", " ", expected: .success(.selectedDelayed)), - ParseFixture.filterMailboxes( - "subtree \"box1\"", - " ", - expected: .success(.subtree(Mailboxes([.init("box1")])!)) - ), - ParseFixture.filterMailboxes( - "subtree-one \"box1\"", - " ", - expected: .success(.subtreeOne(Mailboxes([.init("box1")])!)) - ), - ParseFixture.filterMailboxes( - "mailboxes \"box1\"", - " ", - expected: .success(.mailboxes(Mailboxes([.init("box1")])!)) - ), - ParseFixture.filterMailboxes("subtree ", expected: .failure), - ParseFixture.filterMailboxes("subtree-one", expected: .failure), - ParseFixture.filterMailboxes("mailboxes", expected: .failure), - ]) + @Test( + "parse filter mailboxes", + arguments: [ + ParseFixture.filterMailboxes("inboxes", " ", expected: .success(.inboxes)), + ParseFixture.filterMailboxes("personal", " ", expected: .success(.personal)), + ParseFixture.filterMailboxes("subscribed", " ", expected: .success(.subscribed)), + ParseFixture.filterMailboxes("selected", " ", expected: .success(.selected)), + ParseFixture.filterMailboxes("selected-delayed", " ", expected: .success(.selectedDelayed)), + ParseFixture.filterMailboxes( + "subtree \"box1\"", + " ", + expected: .success(.subtree(Mailboxes([.init("box1")])!)) + ), + ParseFixture.filterMailboxes( + "subtree-one \"box1\"", + " ", + expected: .success(.subtreeOne(Mailboxes([.init("box1")])!)) + ), + ParseFixture.filterMailboxes( + "mailboxes \"box1\"", + " ", + expected: .success(.mailboxes(Mailboxes([.init("box1")])!)) + ), + ParseFixture.filterMailboxes("subtree ", expected: .failure), + ParseFixture.filterMailboxes("subtree-one", expected: .failure), + ParseFixture.filterMailboxes("mailboxes", expected: .failure), + ] + ) func parseFilterMailboxes(_ fixture: ParseFixture) { fixture.checkParsing() } diff --git a/Tests/NIOIMAPCoreTests/Grammar/Notify/Mailboxes+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Notify/Mailboxes+Tests.swift index 6595a3eb..dad23faf 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Notify/Mailboxes+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Notify/Mailboxes+Tests.swift @@ -38,15 +38,18 @@ struct MailboxesTests { fixture.checkEncoding() } - @Test(arguments: [ - ParseFixture.oneOrMoreMailbox("\"box1\"", expected: .success(Mailboxes([.init("box1")])!)), - ParseFixture.oneOrMoreMailbox("(\"box1\")", expected: .success(Mailboxes([.init("box1")])!)), - ParseFixture.oneOrMoreMailbox( - "(\"box1\" \"box2\")", - expected: .success(Mailboxes([.init("box1"), .init("box2")])!) - ), - ParseFixture.oneOrMoreMailbox("()", expected: .failure), - ]) + @Test( + "parse one or more mailboxes", + arguments: [ + ParseFixture.oneOrMoreMailbox("\"box1\"", expected: .success(Mailboxes([.init("box1")])!)), + ParseFixture.oneOrMoreMailbox("(\"box1\")", expected: .success(Mailboxes([.init("box1")])!)), + ParseFixture.oneOrMoreMailbox( + "(\"box1\" \"box2\")", + expected: .success(Mailboxes([.init("box1"), .init("box2")])!) + ), + ParseFixture.oneOrMoreMailbox("()", expected: .failure), + ] + ) func parseOneOrMoreMailbox(_ fixture: ParseFixture) { fixture.checkParsing() } diff --git a/Tests/NIOIMAPCoreTests/Grammar/ObjectID/ObjectID+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/ObjectID/ObjectID+Tests.swift new file mode 100644 index 00000000..d59cd2e3 --- /dev/null +++ b/Tests/NIOIMAPCoreTests/Grammar/ObjectID/ObjectID+Tests.swift @@ -0,0 +1,76 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import NIO +@_spi(NIOIMAPInternal) @testable import NIOIMAPCore +import Testing + +@Suite("ObjectID") +struct ObjectIDTests { + @Test( + "encode", + arguments: [ + EncodeFixture.objectID(ObjectID("abc123")!, "abc123"), + EncodeFixture.objectID(ObjectID("M1-abc_XY")!, "M1-abc_XY"), + ] + ) + func encode(_ fixture: EncodeFixture) { + fixture.checkEncoding() + } + + @Test( + "parse", + arguments: [ + ParseFixture.objectID("abc123", expected: .success(ObjectID("abc123")!)), + ParseFixture.objectID("M1-abc_XY", expected: .success(ObjectID("M1-abc_XY")!)), + ParseFixture.objectID("", "", expected: .failure), + ParseFixture.objectID( + String(repeating: "a", count: 256), + " ", + expected: .failureIgnoringBufferModifications + ), + ] + ) + func parse(_ fixture: ParseFixture) { + fixture.checkParsing() + } +} + +// MARK: - + +extension EncodeFixture { + fileprivate static func objectID(_ input: ObjectID, _ expectedString: String) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeObjectID($1) } + ) + } +} + +extension ParseFixture { + fileprivate static func objectID( + _ input: String, + _ terminator: String = " ", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseObjectID + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Option/OptionExtension+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Option/OptionExtension+Tests.swift index 1d4e9f81..b0753958 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Option/OptionExtension+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Option/OptionExtension+Tests.swift @@ -35,6 +35,28 @@ struct OptionExtensionTests { func encode(_ fixture: EncodeFixture>) { fixture.checkEncoding() } + + @Test(arguments: [ + ParseFixture.optionExtension( + "MYEXT", + ")", + expected: .success(.init(key: .standard("MYEXT"), value: nil)) + ), + ParseFixture.optionExtension( + "MYEXT (\"val\")", + ")", + expected: .success(.init(key: .standard("MYEXT"), value: .string("val"))) + ), + ParseFixture.optionExtension( + "ACME-SORT", + ")", + expected: .success(.init(key: .standard("ACME-SORT"), value: nil)) + ), + ParseFixture.optionExtension("", "", expected: .incompleteMessage), + ]) + func parse(_ fixture: ParseFixture>) { + fixture.checkParsing() + } } // MARK: - @@ -52,3 +74,18 @@ extension EncodeFixture> { ) } } + +extension ParseFixture> { + fileprivate static func optionExtension( + _ input: String, + _ terminator: String = ")", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseOptionExtension + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Option/OptionValue+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Option/OptionValue+Tests.swift index f9e62d8c..bf37e796 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Option/OptionValue+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Option/OptionValue+Tests.swift @@ -18,17 +18,32 @@ import Testing @Suite("OptionValueComp") struct OptionValueTests { - @Test(arguments: [ - EncodeFixture.optionValue(.string("test"), #"("test")"#), - EncodeFixture.optionValue(.array([.string("a"), .string("b")]), #"(("a" "b"))"#), - EncodeFixture.optionValue( - .array([.string("a"), .array([.string("E"), .string("F")]), .string("b")]), - #"(("a" ("E" "F") "b"))"# - ), - ]) + @Test( + "encode", + arguments: [ + EncodeFixture.optionValue(.string("test"), #"("test")"#), + EncodeFixture.optionValue(.array([.string("a"), .string("b")]), #"(("a" "b"))"#), + EncodeFixture.optionValue( + .array([.string("a"), .array([.string("E"), .string("F")]), .string("b")]), + #"(("a" ("E" "F") "b"))"# + ), + ] + ) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() } + + @Test( + "parse", + arguments: [ + ParseFixture.optionValue(#"("test")"#, ")", expected: .success(.string("test"))), + ParseFixture.optionValue("(atom)", ")", expected: .success(.string("atom"))), + ParseFixture.optionValue("", "", expected: .incompleteMessage), + ] + ) + func parse(_ fixture: ParseFixture) { + fixture.checkParsing() + } } // MARK: - @@ -43,3 +58,18 @@ extension EncodeFixture { ) } } + +extension ParseFixture { + fileprivate static func optionValue( + _ input: String, + _ terminator: String = ")", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseOptionValue + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Option/OptionValueComp+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Option/OptionValueComp+Tests.swift index 4fc93bb2..81b60cea 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Option/OptionValueComp+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Option/OptionValueComp+Tests.swift @@ -18,17 +18,33 @@ import Testing @Suite("OptionValueComp") struct OptionValueCompTests { - @Test(arguments: [ - EncodeFixture.optionValueComp(.string("test"), #""test""#), - EncodeFixture.optionValueComp([.string("test1"), .string("test2")], #"("test1" "test2")"#), - EncodeFixture.optionValueComp( - .array([.string("a"), .array([.string("E"), .string("F")]), .string("b")]), - #"("a" ("E" "F") "b")"# - ), - ]) + @Test( + "encode", + arguments: [ + EncodeFixture.optionValueComp(.string("test"), #""test""#), + EncodeFixture.optionValueComp([.string("test1"), .string("test2")], #"("test1" "test2")"#), + EncodeFixture.optionValueComp( + .array([.string("a"), .array([.string("E"), .string("F")]), .string("b")]), + #"("a" ("E" "F") "b")"# + ), + ] + ) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() } + + @Test( + "parse", + arguments: [ + ParseFixture.optionValueComp(#""test""#, expected: .success(.string("test"))), + ParseFixture.optionValueComp("atom", ")", expected: .success(.string("atom"))), + ParseFixture.optionValueComp(#"("val")"#, " ", expected: .success(.array([.string("val")]))), + ParseFixture.optionValueComp("", "", expected: .incompleteMessage), + ] + ) + func parse(_ fixture: ParseFixture) { + fixture.checkParsing() + } } // MARK: - @@ -43,3 +59,18 @@ extension EncodeFixture { ) } } + +extension ParseFixture { + fileprivate static func optionValueComp( + _ input: String, + _ terminator: String = " ", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseOptionValueComp + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Option/OptionVendorTag+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Option/OptionVendorTag+Tests.swift index 5becce33..4ce83d18 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Option/OptionVendorTag+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Option/OptionVendorTag+Tests.swift @@ -18,12 +18,27 @@ import Testing @Suite("KeyValue") struct OptionVendorTagTests { - @Test(arguments: [ - EncodeFixture.optionVendorTag(.init(key: "some", value: "thing"), "some-thing") - ]) + @Test( + "encode", + arguments: [ + EncodeFixture.optionVendorTag(.init(key: "some", value: "thing"), "some-thing") + ] + ) func encode(_ fixture: EncodeFixture>) { fixture.checkEncoding() } + + @Test( + "parse", + arguments: [ + ParseFixture.optionVendorTag("ACME-SORT", ")", expected: .success(.init(key: "ACME", value: "SORT"))), + ParseFixture.optionVendorTag("FOO-BAR", ")", expected: .success(.init(key: "FOO", value: "BAR"))), + ParseFixture.optionVendorTag("", "", expected: .incompleteMessage), + ] + ) + func parse(_ fixture: ParseFixture>) { + fixture.checkParsing() + } } // MARK: - @@ -41,3 +56,18 @@ extension EncodeFixture> { ) } } + +extension ParseFixture> { + fileprivate static func optionVendorTag( + _ input: String, + _ terminator: String = ")", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseOptionVendorTag + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Option/ParameterValue+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Option/ParameterValue+Tests.swift new file mode 100644 index 00000000..807b4aa9 --- /dev/null +++ b/Tests/NIOIMAPCoreTests/Grammar/Option/ParameterValue+Tests.swift @@ -0,0 +1,110 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import NIO +@_spi(NIOIMAPInternal) @testable import NIOIMAPCore +import Testing + +@Suite("ParameterValue") +struct ParameterValueTests { + @Test( + "encode", + arguments: [ + EncodeFixture.parameterValue(.sequence(.set(.init(range: .init(SequenceNumber(1))))), "1"), + EncodeFixture.parameterValue(.sequence(.lastCommand), "$"), + EncodeFixture.parameterValue(.comp(["foo", "bar"]), #"(("foo" "bar"))"#), + EncodeFixture.parameterValue(.comp([]), "()"), + ] + ) + func encode(_ fixture: EncodeFixture) { + fixture.checkEncoding() + } + + @Test( + "parse", + arguments: [ + ParseFixture.parameterValue( + "1", + expected: .success(.sequence(.set(.init(range: .init(SequenceNumber(1)))))) + ), + ParseFixture.parameterValue("$", expected: .success(.sequence(.lastCommand))), + ParseFixture.parameterValue(#"(("foo" "bar"))"#, ")", expected: .success(.comp(["foo", "bar"]))), + ParseFixture.parameterValue("()", ")", expected: .success(.comp([]))), + ParseFixture.parameterValue("", "", expected: .incompleteMessage), + ] + ) + func parse(_ fixture: ParseFixture) { + fixture.checkParsing() + } + + @Test( + "parse parameter", + arguments: [ + ParseFixture.parameter("USE", ")", expected: .success(.init(key: "USE", value: nil))), + ParseFixture.parameter( + "USE 1", + ")", + expected: .success(.init(key: "USE", value: .sequence(.set(.init(range: .init(SequenceNumber(1))))))) + ), + ParseFixture.parameter("USE $", ")", expected: .success(.init(key: "USE", value: .sequence(.lastCommand)))), + ParseFixture.parameter("", "", expected: .incompleteMessage), + ] + ) + func parseParameter(_ fixture: ParseFixture>) { + fixture.checkParsing() + } +} + +// MARK: - + +extension EncodeFixture { + fileprivate static func parameterValue(_ input: ParameterValue, _ expectedString: String) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeParameterValue($1) } + ) + } +} + +extension ParseFixture { + fileprivate static func parameterValue( + _ input: String, + _ terminator: String = " ", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseParameterValue + ) + } +} + +extension ParseFixture> { + fileprivate static func parameter( + _ input: String, + _ terminator: String = ")", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseParameter + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Quota/QuotaLimit+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Quota/QuotaLimit+Tests.swift index 454165f2..4e1c75a5 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Quota/QuotaLimit+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Quota/QuotaLimit+Tests.swift @@ -18,13 +18,39 @@ import Testing @Suite("QuotaLimit") struct QuotaLimitTests { - @Test(arguments: [ - EncodeFixture.quotaLimit(QuotaLimit(resourceName: "STORAGE", limit: 104), "STORAGE 104"), - EncodeFixture.quotaLimit(QuotaLimit(resourceName: "MESSAGE", limit: 42), "MESSAGE 42"), - ]) + @Test( + "encode", + arguments: [ + EncodeFixture.quotaLimit(QuotaLimit(resourceName: "STORAGE", limit: 104), "STORAGE 104"), + EncodeFixture.quotaLimit(QuotaLimit(resourceName: "MESSAGE", limit: 42), "MESSAGE 42"), + ] + ) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() } + + @Test( + "parse LIST", + arguments: [ + ParseFixture.quotaLimits("()", expected: .success([])), + ParseFixture.quotaLimits( + "(STORAGE 104)", + expected: .success([QuotaLimit(resourceName: "STORAGE", limit: 104)]) + ), + ParseFixture.quotaLimits( + "(STORAGE 104 MESSAGE 42)", + expected: .success([ + QuotaLimit(resourceName: "STORAGE", limit: 104), + QuotaLimit(resourceName: "MESSAGE", limit: 42), + ]) + ), + ParseFixture.quotaLimits("", "", expected: .incompleteMessage), + ParseFixture.quotaLimits("STORAGE 104", expected: .failure), + ] + ) + func parseList(_ fixture: ParseFixture<[QuotaLimit]>) { + fixture.checkParsing() + } } // MARK: - @@ -39,3 +65,18 @@ extension EncodeFixture { ) } } + +extension ParseFixture<[QuotaLimit]> { + fileprivate static func quotaLimits( + _ input: String, + _ terminator: String = " ", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseQuotaLimits + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Quota/QuotaRoot+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Quota/QuotaRoot+Tests.swift index 00fa1bc7..85326284 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Quota/QuotaRoot+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Quota/QuotaRoot+Tests.swift @@ -18,13 +18,59 @@ import Testing @Suite("QuotaRoot") struct QuotaRootTests { - @Test(arguments: [ - EncodeFixture.quotaRoot(QuotaRoot(""), #""""#), - EncodeFixture.quotaRoot(QuotaRoot("MassivePool"), #""MassivePool""#), - ]) + @Test( + "encode", + arguments: [ + EncodeFixture.quotaRoot(QuotaRoot(""), #""""#), + EncodeFixture.quotaRoot(QuotaRoot("MassivePool"), #""MassivePool""#), + ] + ) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() } + + @Test( + "parse", + arguments: [ + ParseFixture.quotaRoot(#""MassivePool""#, expected: .success(QuotaRoot("MassivePool"))), + ParseFixture.quotaRoot("inbox", expected: .success(QuotaRoot("inbox"))), + ParseFixture.quotaRoot(#""""#, expected: .success(QuotaRoot(""))), + ParseFixture.quotaRoot("", "", expected: .incompleteMessage), + ] + ) + func parse(_ fixture: ParseFixture) { + fixture.checkParsing() + } + + @Test( + "string conversion", + arguments: [ + (QuotaRoot("MassivePool"), "MassivePool" as String?), + (QuotaRoot(""), "" as String?), + (QuotaRoot(ByteBuffer(bytes: [0xFF, 0xFE])), nil as String?), + ] as [(QuotaRoot, String?)] + ) + func stringConversion(_ fixture: (QuotaRoot, String?)) { + #expect(String(fixture.0) == fixture.1) + } + + @Test( + "debug description", + arguments: [ + (QuotaRoot("MassivePool"), "MassivePool") + ] as [(QuotaRoot, String)] + ) + func debugDescription(_ fixture: (QuotaRoot, String)) { + #expect(fixture.0.debugDescription == fixture.1) + } + + @Test("debug description falls back for invalid UTF-8") func debugDescriptionInvalidUTF8() { + // Invalid UTF-8 falls back to String(buffer:), which produces a non-nil description. + let root = QuotaRoot(ByteBuffer(bytes: [0xFF, 0xFE])) + // String(self) returns nil, so debugDescription uses the fallback path. + #expect(String(root) == nil) + #expect(root.debugDescription.isEmpty == false) + } } // MARK: - @@ -39,3 +85,18 @@ extension EncodeFixture { ) } } + +extension ParseFixture { + fileprivate static func quotaRoot( + _ input: String, + _ terminator: String = " ", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseQuotaRoot + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Response/ESearchResponse+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Response/ESearchResponse+Tests.swift index 2f1e7e5a..ade3f36f 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Response/ESearchResponse+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Response/ESearchResponse+Tests.swift @@ -40,6 +40,15 @@ struct ExtendedSearchResponseTests { ExtendedSearchResponse(kind: .uid, returnData: [.partial(.last(34...10_000), [99...107, 200])]).matchedUIDs == [99...107, 200] ) + // Exercise the guard-else branch in the .partial fallback: non-partial elements + // precede the .partial element, so the guard fails for those elements first. + #expect( + ExtendedSearchResponse( + kind: .uid, + returnData: [.count(5), .partial(.last(34...10_000), [99...107, 200])] + ).matchedUIDs + == [99...107, 200] + ) #expect( ExtendedSearchResponse( kind: .uid, diff --git a/Tests/NIOIMAPCoreTests/Grammar/Response/PermanentFlagTests.swift b/Tests/NIOIMAPCoreTests/Grammar/Response/PermanentFlagTests.swift index 342c2a07..13b434bc 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Response/PermanentFlagTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Response/PermanentFlagTests.swift @@ -18,13 +18,41 @@ import Testing @Suite("PermanentFlag") struct PermanentFlagTests { - @Test(arguments: [ - EncodeFixture.permanentFlag(.wildcard, #"\*"#), - EncodeFixture.permanentFlag(.flag(.answered), #"\Answered"#), - ]) + @Test( + "encode", + arguments: [ + EncodeFixture.permanentFlag(.wildcard, #"\*"#), + EncodeFixture.permanentFlag(.flag(.answered), #"\Answered"#), + ] + ) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() } + + @Test( + "parse", + arguments: [ + ParseFixture.permanentFlag(#"\*"#, expected: .success(.wildcard)), + ParseFixture.permanentFlag(#"\Answered"#, expected: .success(.flag(.answered))), + ParseFixture.permanentFlag(#"\Seen"#, expected: .success(.flag(.seen))), + ParseFixture.permanentFlag("$Forwarded", expected: .success(.flag("$Forwarded"))), + ParseFixture.permanentFlag("", "", expected: .incompleteMessage), + ] + ) + func parse(_ fixture: ParseFixture) { + fixture.checkParsing() + } + + @Test( + "debug description", + arguments: [ + (PermanentFlag.wildcard, #"\*"#), + (PermanentFlag.flag(.answered), #"\Answered"#), + ] as [(PermanentFlag, String)] + ) + func debugDescription(_ fixture: (PermanentFlag, String)) { + #expect(fixture.0.debugDescription == fixture.1) + } } // MARK: - @@ -42,3 +70,18 @@ extension EncodeFixture { ) } } + +extension ParseFixture { + fileprivate static func permanentFlag( + _ input: String, + _ terminator: String = " ", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseFlagPerm + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Response/Response+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Response/Response+Tests.swift index c97eba7b..ba688de5 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Response/Response+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Response/Response+Tests.swift @@ -174,6 +174,69 @@ private struct ResponseTests { == fixture.expected.mappingControlPictures() ) } + + @Test( + "Response tag property", + arguments: [ + ResponseTagFixture(response: .untagged(.id([:])), expectedTag: nil), + ResponseTagFixture(response: .fetch(.start(1)), expectedTag: nil), + ResponseTagFixture(response: .fatal(.init(text: "fatal")), expectedTag: nil), + ResponseTagFixture(response: .authenticationChallenge("data"), expectedTag: nil), + ResponseTagFixture(response: .idleStarted, expectedTag: nil), + ResponseTagFixture( + response: .tagged(.init(tag: "A1", state: .ok(.init(text: "ok")))), + expectedTag: "A1" + ), + ] as [ResponseTagFixture] + ) + func responseTag(_ fixture: ResponseTagFixture) { + #expect(fixture.response.tag == fixture.expectedTag) + } + + @Test( + "StreamingKind sectionSpecifier", + arguments: [ + StreamingKindSectionSpecifierFixture( + kind: .binary(section: [1, 2], offset: nil), + expected: SectionSpecifier(part: [1, 2], kind: .text) + ), + StreamingKindSectionSpecifierFixture( + kind: .body(section: SectionSpecifier(part: [3], kind: .header), offset: nil), + expected: SectionSpecifier(part: [3], kind: .header) + ), + StreamingKindSectionSpecifierFixture( + kind: .rfc822, + expected: SectionSpecifier() + ), + StreamingKindSectionSpecifierFixture( + kind: .rfc822Text, + expected: SectionSpecifier(part: [], kind: .text) + ), + StreamingKindSectionSpecifierFixture( + kind: .rfc822Header, + expected: SectionSpecifier(part: [], kind: .header) + ), + ] as [StreamingKindSectionSpecifierFixture] + ) + func streamingKindSectionSpecifier(_ fixture: StreamingKindSectionSpecifierFixture) { + #expect(fixture.kind.sectionSpecifier == fixture.expected) + } + + @Test( + "StreamingKind offset", + arguments: [ + StreamingKindOffsetFixture(kind: .binary(section: [1], offset: 42), expected: 42), + StreamingKindOffsetFixture(kind: .binary(section: [1], offset: nil), expected: nil), + StreamingKindOffsetFixture(kind: .body(section: SectionSpecifier(), offset: 10), expected: 10), + StreamingKindOffsetFixture(kind: .body(section: SectionSpecifier(), offset: nil), expected: nil), + StreamingKindOffsetFixture(kind: .rfc822, expected: nil), + StreamingKindOffsetFixture(kind: .rfc822Text, expected: nil), + StreamingKindOffsetFixture(kind: .rfc822Header, expected: nil), + ] as [StreamingKindOffsetFixture] + ) + func streamingKindOffset(_ fixture: StreamingKindOffsetFixture) { + #expect(fixture.kind.offset == fixture.expected) + } } // MARK: - @@ -232,3 +295,24 @@ private struct PIIFixture: Sendable, CustomTestStringConvertible { var testDescription: String { expected.mappingControlPictures() } } + +private struct ResponseTagFixture: Sendable, CustomTestStringConvertible { + let response: Response + let expectedTag: String? + + var testDescription: String { expectedTag ?? "(nil)" } +} + +private struct StreamingKindSectionSpecifierFixture: Sendable, CustomTestStringConvertible { + let kind: StreamingKind + let expected: SectionSpecifier + + var testDescription: String { "\(kind)" } +} + +private struct StreamingKindOffsetFixture: Sendable, CustomTestStringConvertible { + let kind: StreamingKind + let expected: Int? + + var testDescription: String { "\(kind)" } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/Response/ResponseTextCodeTests.swift b/Tests/NIOIMAPCoreTests/Grammar/Response/ResponseTextCodeTests.swift index bb0d9c3c..7faae1c5 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Response/ResponseTextCodeTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Response/ResponseTextCodeTests.swift @@ -103,6 +103,15 @@ struct ResponseTextCodeTests { "URLMECH INTERNAL INTERNAL" ), EncodeFixture.responseTextCode(.urlMechanisms([]), "URLMECH INTERNAL"), + EncodeFixture.responseTextCode( + .uidCopy(.init(destinationUIDValidity: 443, sourceUIDs: [3...5], destinationUIDs: [6...8])), + "COPYUID 443 3:5 6:8" + ), + EncodeFixture.responseTextCode( + .uidAppend(.init(uidValidity: 1234, uids: [4, 5])), + "APPENDUID 1234 4:5" + ), + EncodeFixture.responseTextCode(.uidNotSticky, "UIDNOTSTICKY"), EncodeFixture.responseTextCode(.useAttribute, "USEATTR"), ]) func encode(_ fixture: EncodeFixture) { diff --git a/Tests/NIOIMAPCoreTests/Grammar/Search/SearchKey+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Search/SearchKey+Tests.swift index 6f658012..7cb70e3a 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Search/SearchKey+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Search/SearchKey+Tests.swift @@ -87,6 +87,8 @@ struct SearchKeyTests { ), EncodeFixture.searchKey(.emailID(.init("123-456-789")!), "EMAILID 123-456-789"), EncodeFixture.searchKey(.threadID(.init("123-456-789")!), "THREADID 123-456-789"), + EncodeFixture.searchKey(.younger(34), "YOUNGER 34"), + EncodeFixture.searchKey(.older(45), "OLDER 45"), ]) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() @@ -175,6 +177,26 @@ struct SearchKeyTests { func parse(_ fixture: ParseFixture) { fixture.checkParsing() } + + @Test( + "uses string", + arguments: [ + (SearchKey.not(.bcc("test")), true), + (SearchKey.not(.all), false), + (SearchKey.or(.bcc("x"), .all), true), + (SearchKey.or(.all, .deleted), false), + (SearchKey.and([.bcc("x"), .deleted]), true), + (SearchKey.and([.all, .deleted]), false), + ] as [(SearchKey, Bool)] + ) + func usesString(_ fixture: (SearchKey, Bool)) { + #expect(fixture.0.usesString == fixture.1) + } + + @Test("debug description") func debugDescription() { + #expect(SearchKey.all.debugDescription == "ALL") + #expect(SearchKey.not(.messageSizeLarger(444)).debugDescription == "NOT LARGER 444") + } } // MARK: - diff --git a/Tests/NIOIMAPCoreTests/Grammar/Search/SearchReturnData+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/Search/SearchReturnData+Tests.swift index 65e435aa..6e0b7cc7 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Search/SearchReturnData+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Search/SearchReturnData+Tests.swift @@ -71,6 +71,11 @@ struct SearchReturnDataTests { "PARTIAL (-55:-700 NIL)", expected: .success(.partial(.last(55...700), [])) ), + // $ (last-command-set) is invalid as a PARTIAL result set — triggers guard failure + ParseFixture.searchReturnDataPartial( + "PARTIAL (1:3 $)", + expected: .failureIgnoringBufferModifications + ), ] ) func parsePartial(_ fixture: ParseFixture) { diff --git a/Tests/NIOIMAPCoreTests/Grammar/Section/SectionSpecTests.swift b/Tests/NIOIMAPCoreTests/Grammar/Section/SectionSpecTests.swift index 9797554a..961a10b4 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Section/SectionSpecTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Section/SectionSpecTests.swift @@ -23,6 +23,16 @@ private struct SectionSpecifierTests { EncodeFixture.sectionSpecifier(.init(kind: .header), "HEADER"), EncodeFixture.sectionSpecifier(.init(part: [1, 2, 3, 4], kind: .complete), "1.2.3.4"), EncodeFixture.sectionSpecifier(.init(part: [1, 2, 3, 4], kind: .header), "1.2.3.4.HEADER"), + EncodeFixture.sectionSpecifier(.init(part: [1, 2], kind: .MIMEHeader), "1.2.MIME"), + EncodeFixture.sectionSpecifier(.init(part: [1], kind: .text), "1.TEXT"), + EncodeFixture.sectionSpecifier( + .init(part: [1, 2, 3], kind: .headerFieldsNot(["FROM", "DATE"])), + #"1.2.3.HEADER.FIELDS.NOT ("FROM" "DATE")"# + ), + EncodeFixture.sectionSpecifier( + .init(part: [1], kind: .headerFields(["SUBJECT"])), + #"1.HEADER.FIELDS ("SUBJECT")"# + ), ]) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() @@ -130,6 +140,9 @@ private struct SectionSpecifierTests { ComparableFixture(lhs: [1, 2, 3, 4], rhs: [1, 2, 3, 4], expected: false), ComparableFixture(lhs: [1, 2, 3, 4], rhs: [1, 2, 3, 4, 5, 6], expected: true), ComparableFixture(lhs: [1, 2, 3, 4, 5, 6], rhs: [1, 2, 3], expected: false), + // Elements differ at position i + ComparableFixture(lhs: [1, 3], rhs: [1, 4], expected: true), + ComparableFixture(lhs: [1, 4], rhs: [1, 3], expected: false), ] ) func comparableSectionSpecifierPart(_ fixture: ComparableFixture) { @@ -278,6 +291,33 @@ private struct SectionSpecifierTests { func parseSectionSpecifierKind(_ fixture: ParseFixture) { fixture.checkParsing() } + + @Test( + "static factory headerFields / headerFieldsNot", + arguments: [ + ( + SectionSpecifier.headerFields(["FROM", "DATE"]), + SectionSpecifier(kind: .headerFields(["FROM", "DATE"])) + ), + (SectionSpecifier.headerFieldsNot(["FROM"]), SectionSpecifier(kind: .headerFieldsNot(["FROM"]))), + ] as [(SectionSpecifier, SectionSpecifier)] + ) + func staticFactories(_ fixture: (SectionSpecifier, SectionSpecifier)) { + #expect(fixture.0 == fixture.1) + } + + #if swift(>=6.2) + @Test("MIME header with empty part triggers precondition failure") func mimeHeaderWithEmptyPartPreconditionFailure() + async + { + await #expect( + processExitsWith: ExitTest.Condition.failure, + performing: { + _ = SectionSpecifier(kind: .MIMEHeader) + } + ) + } + #endif } // MARK: - diff --git a/Tests/NIOIMAPCoreTests/Grammar/SelectParameter+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/SelectParameter+Tests.swift index da20f344..114e2141 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/SelectParameter+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/SelectParameter+Tests.swift @@ -86,6 +86,10 @@ struct SelectParameterTests { "test 1", expected: .success(.basic(.init(key: "test", value: .sequence(.set([1]))))) ), + ParseFixture.selectParameter( + "CONDSTORE", + expected: .success(.condStore) + ), ParseFixture.selectParameter( "QRESYNC (1 1)", expected: .success( diff --git a/Tests/NIOIMAPCoreTests/Grammar/Sequence/SequenceNumberTests.swift b/Tests/NIOIMAPCoreTests/Grammar/Sequence/SequenceNumberTests.swift index 436e16a0..ea96afdb 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/Sequence/SequenceNumberTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/Sequence/SequenceNumberTests.swift @@ -41,15 +41,18 @@ extension SequenceNumberTests { #expect(SequenceNumber(1) < 999) } - @Test(arguments: [ - EncodeFixture.sequenceNumber(1, "1"), - EncodeFixture.sequenceNumber(123, "123"), - EncodeFixture.sequenceNumber(1234, "1234"), - EncodeFixture.sequenceNumber(9999, "9999"), - EncodeFixture.sequenceNumber(65535, "65535"), - EncodeFixture.sequenceNumber(1_000_000, "1000000"), - EncodeFixture.sequenceNumber(.max, "4294967295"), - ]) + @Test( + "encode", + arguments: [ + EncodeFixture.sequenceNumber(1, "1"), + EncodeFixture.sequenceNumber(123, "123"), + EncodeFixture.sequenceNumber(1234, "1234"), + EncodeFixture.sequenceNumber(9999, "9999"), + EncodeFixture.sequenceNumber(65535, "65535"), + EncodeFixture.sequenceNumber(1_000_000, "1000000"), + EncodeFixture.sequenceNumber(.max, "4294967295"), + ] + ) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() } @@ -62,6 +65,13 @@ extension SequenceNumberTests { #expect(min.advanced(by: min.distance(to: max)) == max) #expect(max.advanced(by: max.distance(to: min)) == min) } + + @Test("conversion to UnknownMessageIdentifier") + func conversionToUnknownMessageIdentifier() { + let seq = SequenceNumber(42) + let unknown = UnknownMessageIdentifier(seq) + #expect(unknown.rawValue == 42) + } } // MARK: - diff --git a/Tests/NIOIMAPCoreTests/Grammar/SortData+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/SortData+Tests.swift index fdebc155..fe6bfd49 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/SortData+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/SortData+Tests.swift @@ -31,6 +31,25 @@ struct SortDataTests { func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() } + + @Test(arguments: [ + ParseFixture.sortData("SORT", "\r", expected: .success(nil)), + ParseFixture.sortData( + "SORT 1 (MODSEQ 2)", + "\r", + expected: .success(.init(identifiers: [1], modificationSequence: 2)) + ), + ParseFixture.sortData( + "SORT 1 3 5 (MODSEQ 42)", + "\r", + expected: .success(.init(identifiers: [1, 3, 5], modificationSequence: 42)) + ), + ParseFixture.sortData("", "", expected: .incompleteMessage), + ParseFixture.sortData("THREAD", "\r", expected: .failure), + ]) + func parse(_ fixture: ParseFixture) { + fixture.checkParsing() + } } // MARK: - @@ -48,3 +67,18 @@ extension EncodeFixture { ) } } + +extension ParseFixture { + fileprivate static func sortData( + _ input: String, + _ terminator: String = " ", + expected: Expected + ) -> Self { + ParseFixture( + input: input, + terminator: terminator, + expected: expected, + parser: GrammarParser().parseSortData + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/StoreData+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/StoreData+Tests.swift index b113e2c9..54ce5e41 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/StoreData+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/StoreData+Tests.swift @@ -18,6 +18,39 @@ import Testing @Suite("StoreData") struct StoreDataTests { + @Test( + "encode store data", + arguments: [ + EncodeFixture.storeData(.flags(.add(silent: false, list: [.answered])), "+FLAGS (\\Answered)"), + EncodeFixture.storeData(.flags(.remove(silent: true, list: [.draft])), "-FLAGS.SILENT (\\Draft)"), + EncodeFixture.storeData( + .gmailLabels(.add(silent: false, gmailLabels: [.init("\\Inbox")])), + "+X-GM-LABELS (\\Inbox)" + ), + ] + ) + func encode(_ fixture: EncodeFixture) { + fixture.checkEncoding() + } + + @Test( + "encode store gmail labels", + arguments: [ + EncodeFixture.storeGmailLabels(.add(silent: false, gmailLabels: [.init("foo")]), #"+X-GM-LABELS ("foo")"#), + EncodeFixture.storeGmailLabels( + .remove(silent: true, gmailLabels: [.init("foo"), .init("bar")]), + #"-X-GM-LABELS.SILENT ("foo" "bar")"# + ), + EncodeFixture.storeGmailLabels( + .replace(silent: false, gmailLabels: [.init("foo")]), + #"X-GM-LABELS ("foo")"# + ), + ] + ) + func encodeGmailLabels(_ fixture: EncodeFixture) { + fixture.checkEncoding() + } + @Test( "parse store modifier", arguments: [ @@ -138,3 +171,25 @@ extension ParseFixture { ) } } + +extension EncodeFixture { + fileprivate static func storeData(_ input: StoreData, _ expectedString: String) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeStoreData($1) } + ) + } +} + +extension EncodeFixture { + fileprivate static func storeGmailLabels(_ input: StoreGmailLabels, _ expectedString: String) -> Self { + EncodeFixture( + input: input, + bufferKind: .defaultServer, + expectedString: expectedString, + encoder: { $0.writeStoreGmailLabels($1) } + ) + } +} diff --git a/Tests/NIOIMAPCoreTests/Grammar/UAuthMechanism+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/UAuthMechanism+Tests.swift index f5b411a0..9c16ed01 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/UAuthMechanism+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/UAuthMechanism+Tests.swift @@ -47,6 +47,17 @@ struct URLAuthenticationMechanismTests { func parse(_ fixture: ParseFixture) { fixture.checkParsing() } + + @Test( + "string conversion", + arguments: [ + (URLAuthenticationMechanism.internal, "INTERNAL"), + (URLAuthenticationMechanism("CUSTOM"), "CUSTOM"), + ] as [(URLAuthenticationMechanism, String)] + ) + func stringConversion(_ fixture: (URLAuthenticationMechanism, String)) { + #expect(String(fixture.0) == fixture.1) + } } // MARK: - diff --git a/Tests/NIOIMAPCoreTests/Grammar/UID/UIDRangeTests.swift b/Tests/NIOIMAPCoreTests/Grammar/UID/UIDRangeTests.swift index da8a7b67..f61438fa 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/UID/UIDRangeTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/UID/UIDRangeTests.swift @@ -60,7 +60,7 @@ struct UIDRangeTests { #expect(MessageIdentifierRange(777...999).upperBound == 999) } - @Test func isEmpty() { + @Test("isEmpty") func isEmpty() { #expect(!MessageIdentifierRange(654...654).isEmpty) #expect(!MessageIdentifierRange(654).isEmpty) #expect(!MessageIdentifierRange(654...655).isEmpty) diff --git a/Tests/NIOIMAPCoreTests/Grammar/UID/UIDSetNonEmptyTests.swift b/Tests/NIOIMAPCoreTests/Grammar/UID/UIDSetNonEmptyTests.swift index 421cedcc..2367d93a 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/UID/UIDSetNonEmptyTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/UID/UIDSetNonEmptyTests.swift @@ -28,6 +28,29 @@ extension UIDSetNonEmptyTests { ) } + @Test("init with empty set returns nil") + func initWithEmptySetReturnsNil() { + #expect(MessageIdentifierSetNonEmpty(set: MessageIdentifierSet()) == nil) + } + + @Test("init unknown converts to typed set") + func initUnknownConvertsToTypedSet() { + let unknown = MessageIdentifierSetNonEmpty(set: MessageIdentifierSet([1...5]))! + let uids = MessageIdentifierSetNonEmpty(unknown: unknown) + #expect(uids.set == MessageIdentifierSet([1...5])) + } + + #if swift(>=6.2) + @Test("empty array literal triggers precondition failure") func emptyArrayLiteralPreconditionFailure() async { + await #expect( + processExitsWith: ExitTest.Condition.failure, + performing: { + let _: MessageIdentifierSetNonEmpty = [] + } + ) + } + #endif + @Test("init with range") func initWithRange() { #expect( diff --git a/Tests/NIOIMAPCoreTests/Grammar/UID/UIDSetTests.swift b/Tests/NIOIMAPCoreTests/Grammar/UID/UIDSetTests.swift index ea2626fa..78190195 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/UID/UIDSetTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/UID/UIDSetTests.swift @@ -87,7 +87,7 @@ struct UIDSetTests { #expect(MessageIdentifierSet.all.contains(.max)) } - @Test func isContiguous() { + @Test("isContiguous") func isContiguous() { #expect(MessageIdentifierSet.empty.isContiguous) #expect(MessageIdentifierSet(20 as UID).isContiguous) #expect(MessageIdentifierSet(20...22).isContiguous) @@ -123,7 +123,7 @@ struct UIDSetTests { ) } - @Test func symmetricDifference() { + @Test("symmetricDifference") func symmetricDifference() { #expect( "\(MessageIdentifierSet(20 as UID).symmetricDifference(MessageIdentifierSet(30 as UID)))" == "20,30" @@ -188,19 +188,19 @@ struct UIDSetTests { #expect(sut.count == 4) } - @Test func formUnion() { + @Test("formUnion") func formUnion() { var sut = MessageIdentifierSet(20 as UID) sut.formUnion(MessageIdentifierSet(30 as UID)) #expect("\(sut)" == "20,30") } - @Test func formIntersection() { + @Test("formIntersection") func formIntersection() { var sut = MessageIdentifierSet(20...35) sut.formIntersection(MessageIdentifierSet(30...40)) #expect("\(sut)" == "30:35") } - @Test func formSymmetricDifference() { + @Test("formSymmetricDifference") func formSymmetricDifference() { var sut = MessageIdentifierSet(20...35) sut.formSymmetricDifference(MessageIdentifierSet(30...40)) #expect("\(sut)" == "20:29,36:40") @@ -213,7 +213,7 @@ struct UIDSetTests { #expect("\(a)" == "20,25:35") } - @Test func isSubset() { + @Test("isSubset") func isSubset() { #expect( MessageIdentifierSet(20...35) .isSubset(of: MessageIdentifierSet(20...35)) @@ -236,7 +236,7 @@ struct UIDSetTests { ) } - @Test func isStrictSubset() { + @Test("isStrictSubset") func isStrictSubset() { #expect( !MessageIdentifierSet(20...35) .isStrictSubset(of: MessageIdentifierSet(20...35)) @@ -259,7 +259,7 @@ struct UIDSetTests { ) } - @Test func isDisjoint() { + @Test("isDisjoint") func isDisjoint() { #expect( !MessageIdentifierSet(20...35) .isDisjoint(with: MessageIdentifierSet(20...35)) @@ -282,7 +282,7 @@ struct UIDSetTests { ) } - @Test func isSuperset() { + @Test("isSuperset") func isSuperset() { #expect( MessageIdentifierSet(20...35) .isSuperset(of: MessageIdentifierSet(20...35)) @@ -305,7 +305,7 @@ struct UIDSetTests { ) } - @Test func isStrictSuperset() { + @Test("isStrictSuperset") func isStrictSuperset() { #expect( !MessageIdentifierSet(20...35) .isStrictSuperset(of: MessageIdentifierSet(20...35)) @@ -334,20 +334,20 @@ struct UIDSetTests { #expect("\(sut)" == "20,25:35") } - @Test func emptyCollection() { + @Test("empty collection") func emptyCollection() { #expect(MessageIdentifierSet().map { "\($0)" } == []) #expect(MessageIdentifierSet().count == 0) #expect(MessageIdentifierSet().isEmpty) } - @Test func singleElementCollection() { + @Test("single element collection") func singleElementCollection() { let sut = MessageIdentifierSet(55 as UID) #expect(sut.map { "\($0)" } == ["55"]) #expect(sut.count == 1) #expect(!sut.isEmpty) } - @Test func singleRangeCollection() { + @Test("single range collection") func singleRangeCollection() { let sut = MessageIdentifierSet(55...57) #expect(sut.map { "\($0)" } == ["55", "56", "57"]) #expect(sut.count == 3) @@ -575,7 +575,7 @@ struct UIDSetTests { #expect(sut.index(sut.startIndex, offsetBy: 31, limitedBy: sut.endIndex) == nil) } - @Test func rangeView() { + @Test("RangeView") func rangeView() { #expect(Array(MessageIdentifierSet().ranges) == []) #expect( Array(MessageIdentifierSet([1_234]).ranges) diff --git a/Tests/NIOIMAPCoreTests/Grammar/UID/UIDTests.swift b/Tests/NIOIMAPCoreTests/Grammar/UID/UIDTests.swift index 8f5e9f8a..17bd222e 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/UID/UIDTests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/UID/UIDTests.swift @@ -32,7 +32,7 @@ struct UIDTests { #expect(UID(exactly: 4_294_967_296) == nil) } - @Test + @Test("comparable") func comparable() { #expect((UID.max < UID.max) == false) #expect((UID.max < 999) == false) @@ -52,12 +52,15 @@ struct UIDTests { fixture.check() } - @Test(arguments: [ - EncodeFixture.uid(.min, "1"), - EncodeFixture.uid(.max, "*"), - EncodeFixture.uid(UID(1234), "1234"), - EncodeFixture.uid(UID(392_972_163), "392972163"), - ]) + @Test( + "encode", + arguments: [ + EncodeFixture.uid(.min, "1"), + EncodeFixture.uid(.max, "*"), + EncodeFixture.uid(UID(1234), "1234"), + EncodeFixture.uid(UID(392_972_163), "392972163"), + ] + ) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() } @@ -77,6 +80,24 @@ struct UIDTests { #expect(UID.min.advanced(by: UID.min.distance(to: UID.max)) == UID.max) #expect(UID.max.advanced(by: UID.max.distance(to: UID.min)) == UID.min) } + + @Test("conversion to UnknownMessageIdentifier") + func conversionToUnknownMessageIdentifier() { + let uid = UID(99) + let unknown = UnknownMessageIdentifier(uid) + #expect(unknown.rawValue == 99) + } + + #if swift(>=6.2) + @Test("advanced(by:) overflow triggers precondition failure") func advancedByOverflowPreconditionFailure() async { + await #expect( + processExitsWith: ExitTest.Condition.failure, + performing: { + _ = UID(1).advanced(by: Int64(UInt32.max) + 1) + } + ) + } + #endif } // MARK: - diff --git a/Tests/NIOIMAPCoreTests/Grammar/UID/UIDValidity+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/UID/UIDValidity+Tests.swift index cf324a24..85358d15 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/UID/UIDValidity+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/UID/UIDValidity+Tests.swift @@ -18,22 +18,28 @@ import Testing @Suite("UIDValidity") struct UIDValidityTests { - @Test(arguments: [ - EncodeFixture.uidValidity(1, "1"), - EncodeFixture.uidValidity(123, "123"), - EncodeFixture.uidValidity(4_294_967_295, "4294967295"), - ]) + @Test( + "encode", + arguments: [ + EncodeFixture.uidValidity(1, "1"), + EncodeFixture.uidValidity(123, "123"), + EncodeFixture.uidValidity(4_294_967_295, "4294967295"), + ] + ) func encode(_ fixture: EncodeFixture) { fixture.checkEncoding() } - @Test(arguments: [ - ParseFixture.uidValidity("1", " ", expected: .success(1)), - ParseFixture.uidValidity("12", " ", expected: .success(12)), - ParseFixture.uidValidity("123", " ", expected: .success(123)), - ParseFixture.uidValidity("0", " ", expected: .failure), - ParseFixture.uidValidity("1", "", expected: .incompleteMessage), - ]) + @Test( + "parse", + arguments: [ + ParseFixture.uidValidity("1", " ", expected: .success(1)), + ParseFixture.uidValidity("12", " ", expected: .success(12)), + ParseFixture.uidValidity("123", " ", expected: .success(123)), + ParseFixture.uidValidity("0", " ", expected: .failure), + ParseFixture.uidValidity("1", "", expected: .incompleteMessage), + ] + ) func parse(_ fixture: ParseFixture) { fixture.checkParsing() } @@ -45,6 +51,13 @@ struct UIDValidityTests { #expect(UIDValidity(exactly: 4_294_967_295)?.rawValue == 4_294_967_295) #expect(UIDValidity(exactly: 4_294_967_296) == nil) } + + @Test("binary integer conversion") + func binaryIntegerConversion() { + let v: UIDValidity = 42 + #expect(Int(v) == 42) + #expect(UInt64(v) == 42) + } } // MARK: - diff --git a/Tests/NIOIMAPCoreTests/Grammar/UseAttribute+Tests.swift b/Tests/NIOIMAPCoreTests/Grammar/UseAttribute+Tests.swift index 38b22421..992dce59 100644 --- a/Tests/NIOIMAPCoreTests/Grammar/UseAttribute+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Grammar/UseAttribute+Tests.swift @@ -46,10 +46,22 @@ struct UseAttributeTests { #expect(UseAttribute(MailboxInfo.Attribute(#"\All"#)).stringValue == #"\All"#) } + @Test( + "string conversion", + arguments: [ + (UseAttribute.trash, "\\Trash"), + (UseAttribute("\\Custom"), "\\Custom"), + ] as [(UseAttribute, String)] + ) + func stringConversion(_ fixture: (UseAttribute, String)) { + #expect(String(fixture.0) == fixture.1) + } + @Test(arguments: [ ParseFixture.useAttribute("\\All", "", expected: .success(.all)), ParseFixture.useAttribute("\\Archive", "", expected: .success(.archive)), ParseFixture.useAttribute("\\Flagged", "", expected: .success(.flagged)), + ParseFixture.useAttribute("\\Junk", "", expected: .success(.junk)), ParseFixture.useAttribute("\\Trash", "", expected: .success(.trash)), ParseFixture.useAttribute("\\Sent", "", expected: .success(.sent)), ParseFixture.useAttribute("\\Drafts", "", expected: .success(.drafts)), diff --git a/Tests/NIOIMAPCoreTests/Parser/CommandParser+Tests.swift b/Tests/NIOIMAPCoreTests/Parser/CommandParser+Tests.swift index ad7b48d0..60a6f886 100644 --- a/Tests/NIOIMAPCoreTests/Parser/CommandParser+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Parser/CommandParser+Tests.swift @@ -32,6 +32,22 @@ struct CommandParserTests { #expect(parser.bufferLimit == 80_000) } + @Test("isStreamingAppend is false for non-streaming modes") + func isStreamingAppendIsFalseForNonStreamingModes() { + #expect(!CommandParser.Mode.lines.isStreamingAppend) + #expect(!CommandParser.Mode.idle.isStreamingAppend) + #expect(!CommandParser.Mode.waitingForMessage.isStreamingAppend) + #expect(!CommandParser.Mode.streamingEnd.isStreamingAppend) + #expect(!CommandParser.Mode.waitingForCatenatePart(seenPreviousPart: false).isStreamingAppend) + #expect(!CommandParser.Mode.streamingCatenateBytes(1).isStreamingAppend) + #expect(!CommandParser.Mode.streamingCatenateEnd.isStreamingAppend) + } + + @Test("isStreamingAppend is true only for streamingBytes mode") + func isStreamingAppendIsTrueOnlyForStreamingBytesMode() { + #expect(CommandParser.Mode.streamingBytes(1).isStreamingAppend) + } + // MARK: - Integration Tests @Test("parse empty byte buffer for APPEND does not return empty bytes") diff --git a/Tests/NIOIMAPCoreTests/Parser/Grammar/GrammarParser+Primitives+Tests.swift b/Tests/NIOIMAPCoreTests/Parser/Grammar/GrammarParser+Primitives+Tests.swift index aaa3abdb..1330687a 100644 --- a/Tests/NIOIMAPCoreTests/Parser/Grammar/GrammarParser+Primitives+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Parser/Grammar/GrammarParser+Primitives+Tests.swift @@ -197,6 +197,17 @@ private struct GrammarParserPrimitivesTests { "", expected: .success([UInt8(ascii: "%"), UInt8(ascii: "F"), UInt8(ascii: "F")]) ), + // Lowercase hex digits get uppercased + ParseFixture.uchar( + "%1a", + "", + expected: .success([UInt8(ascii: "%"), UInt8(ascii: "1"), UInt8(ascii: "A")]) + ), + ParseFixture.uchar( + "%ff", + "", + expected: .success([UInt8(ascii: "%"), UInt8(ascii: "F"), UInt8(ascii: "F")]) + ), ParseFixture.uchar("%GG", " ", expected: .failure), ParseFixture.uchar("%", "", expected: .incompleteMessage), ] @@ -297,6 +308,47 @@ private struct GrammarParserPrimitivesTests { func parseVendorToken(_ fixture: ParseFixture) { fixture.checkParsing() } + + @Test("parseLiteralSize with and without tilde prefix") + func parseLiteralSizeVariants() throws { + let parser = GrammarParser() + + // Standard {N}\r\n — single-arg overload (covers lines 1467-1468) + var b1 = ParseBuffer("{5}\r\n") + let size1 = try parser.parseLiteralSize(buffer: &b1, tracker: .makeNewDefault) + #expect(size1 == 5) + + // Binary ~{N}\r\n — covers the ~ optional branch in the two-arg overload (line 1474) + var b2 = ParseBuffer("~{5}\r\n") + let size2 = try parser.parseLiteralSize(buffer: &b2, tracker: .makeNewDefault) + #expect(size2 == 5) + } + + @Test("parseLiteral with NUL byte throws") + func parseLiteralNULByte() { + let parser = GrammarParser() + // Literal containing a NUL byte (0x00) — covers line 1495 + var b = ParseBuffer("{3}\r\na\0b") + #expect(throws: (any Error).self) { + try parser.parseLiteral(buffer: &b, tracker: .makeNewDefault) + } + } + + @Test("parseLiteral8 non-synchronizing literal and NUL byte") + func parseLiteral8Variants() throws { + let parser = GrammarParser() + + // Non-synchronizing ~{N+}\r\n — covers the + optional branch (line 1508) + var b1 = ParseBuffer("~{3+}\r\nabc") + let result = try parser.parseLiteral8(buffer: &b1, tracker: .makeNewDefault) + #expect(String(buffer: result) == "abc") + + // Literal8 containing a NUL byte — covers line 1513 + var b2 = ParseBuffer("~{3}\r\na\0b") + #expect(throws: (any Error).self) { + try parser.parseLiteral8(buffer: &b2, tracker: .makeNewDefault) + } + } } // MARK: - diff --git a/Tests/NIOIMAPCoreTests/Parser/ResponseParser+Tests.swift b/Tests/NIOIMAPCoreTests/Parser/ResponseParser+Tests.swift index 3e8e9ebb..f5b20340 100644 --- a/Tests/NIOIMAPCoreTests/Parser/ResponseParser+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Parser/ResponseParser+Tests.swift @@ -231,4 +231,14 @@ struct ResponseParserTests { try parser.parseResponseStream(buffer: &input) } } + + @Test("parse untagged non-fetch response") + func parseUntaggedNonFetchResponse() throws { + // An EXISTS response is not a FETCH, so parseResponse_fetch fails and + // parseResponse_normal succeeds, exercising the .untaggedResponse branch. + var parser = ResponseParser() + var buffer: ByteBuffer = "* 5 EXISTS\r\n" + let result = try parser.parseResponseStream(buffer: &buffer) + #expect(result == .response(.untagged(.mailboxData(.exists(5))))) + } } diff --git a/Tests/NIOIMAPCoreTests/Parser/SynchronizedCommand+Tests.swift b/Tests/NIOIMAPCoreTests/Parser/SynchronizedCommand+Tests.swift index 1cf18b74..94c38220 100644 --- a/Tests/NIOIMAPCoreTests/Parser/SynchronizedCommand+Tests.swift +++ b/Tests/NIOIMAPCoreTests/Parser/SynchronizedCommand+Tests.swift @@ -268,6 +268,182 @@ struct SynchronizedCommandTests { #expect(c2_5 == SynchronizedCommand(.append(.finish))) } + @Test("CATENATE with non-synchronizing literal TEXT part") + func catenateWithNonSynchronizingLiteralTextPart() throws { + // Uses TEXT {N+}\r\n (non-synchronizing literal with '+') + var buffer = ByteBuffer( + string: "A1 APPEND Drafts CATENATE (TEXT {5+}\r\nhello)\r\n" + ) + + var parser = CommandParser() + + let c1 = try parser.parseCommandStream(buffer: &buffer) + let c2 = try parser.parseCommandStream(buffer: &buffer) + let c3 = try parser.parseCommandStream(buffer: &buffer) + let c4 = try parser.parseCommandStream(buffer: &buffer) + let c5 = try parser.parseCommandStream(buffer: &buffer) + let c6 = try parser.parseCommandStream(buffer: &buffer) + let c7 = try parser.parseCommandStream(buffer: &buffer) + + #expect(buffer.readableBytes == 0) + #expect(c1 == SynchronizedCommand(.append(.start(tag: "A1", appendingTo: MailboxName("Drafts"))))) + #expect(c2 == SynchronizedCommand(.append(.beginCatenate(options: .none)))) + #expect(c3 == SynchronizedCommand(.append(.catenateData(.begin(size: 5))))) + #expect(c4 == SynchronizedCommand(.append(.catenateData(.bytes("hello"))))) + #expect(c5 == SynchronizedCommand(.append(.catenateData(.end)))) + #expect(c6 == SynchronizedCommand(.append(.endCatenate))) + #expect(c7 == SynchronizedCommand(.append(.finish))) + } + + // MARK: - IDLE Command Tests + + // MARK: - Streaming byte chunking + + @Test("partial APPEND streaming bytes triggers intermediate streaming mode") + func partialAppendStreamingBytesTriggersIntermediateStreamingMode() throws { + var parser = CommandParser() + // Start APPEND with 10-byte non-synchronising literal, but only provide 5 bytes + var buf = ByteBuffer("1 APPEND INBOX {10+}\r\nHello") + + let c1 = try parser.parseCommandStream(buffer: &buf) + #expect(c1 == SynchronizedCommand(.append(.start(tag: "1", appendingTo: .inbox)))) + + let c2 = try parser.parseCommandStream(buffer: &buf) + #expect( + c2 + == SynchronizedCommand( + .append(.beginMessage(message: .init(options: .none, data: .init(byteCount: 10)))) + ) + ) + #expect(parser.mode == .streamingBytes(10)) + + // Only 5 bytes available — should enter the else branch and leave 5 remaining + let c3 = try parser.parseCommandStream(buffer: &buf) + #expect(c3 == SynchronizedCommand(.append(.messageBytes(ByteBuffer(string: "Hello"))))) + #expect(parser.mode == .streamingBytes(5)) + + // Provide the remaining 5 bytes + buf.writeString("World") + let c4 = try parser.parseCommandStream(buffer: &buf) + #expect(c4 == SynchronizedCommand(.append(.messageBytes(ByteBuffer(string: "World"))))) + #expect(parser.mode == .streamingEnd) + + buf.writeString("\r\n") + let c5 = try parser.parseCommandStream(buffer: &buf) + #expect(c5 == SynchronizedCommand(.append(.endMessage))) + + let c6 = try parser.parseCommandStream(buffer: &buf) + #expect(c6 == SynchronizedCommand(.append(.finish))) + } + + @Test("partial CATENATE streaming bytes triggers intermediate streaming mode") + func partialCatenateStreamingBytesTriggersIntermediateStreamingMode() throws { + var parser = CommandParser() + // CATENATE with 5-byte TEXT literal but only 3 bytes provided initially + var buf = ByteBuffer("A1 APPEND Drafts CATENATE (TEXT {5+}\r\nhel") + + let c1 = try parser.parseCommandStream(buffer: &buf) + #expect(c1 == SynchronizedCommand(.append(.start(tag: "A1", appendingTo: MailboxName("Drafts"))))) + + let c2 = try parser.parseCommandStream(buffer: &buf) + #expect(c2 == SynchronizedCommand(.append(.beginCatenate(options: .none)))) + + let c3 = try parser.parseCommandStream(buffer: &buf) + #expect(c3 == SynchronizedCommand(.append(.catenateData(.begin(size: 5))))) + + // Only 3 of 5 bytes available — enters the else branch + let c4 = try parser.parseCommandStream(buffer: &buf) + #expect(c4 == SynchronizedCommand(.append(.catenateData(.bytes(ByteBuffer(string: "hel")))))) + #expect(parser.mode == .streamingCatenateBytes(2)) + + // Provide the remaining 2 bytes + buf.writeString("lo") + let c5 = try parser.parseCommandStream(buffer: &buf) + #expect(c5 == SynchronizedCommand(.append(.catenateData(.bytes(ByteBuffer(string: "lo")))))) + #expect(parser.mode == .streamingCatenateEnd) + + buf.writeString(")\r\n") + let c6 = try parser.parseCommandStream(buffer: &buf) + #expect(c6 == SynchronizedCommand(.append(.catenateData(.end)))) + + let c7 = try parser.parseCommandStream(buffer: &buf) + #expect(c7 == SynchronizedCommand(.append(.endCatenate))) + + let c8 = try parser.parseCommandStream(buffer: &buf) + #expect(c8 == SynchronizedCommand(.append(.finish))) + } + + // MARK: - Incomplete input and synchronising literals + + @Test("incomplete command with no synchronising literals returns nil") + func incompleteCommandWithNoSynchronisingLiteralsReturnsNil() throws { + // Buffer has bytes but no complete command line yet — no newline found + var parser = CommandParser() + var buf = ByteBuffer("1 NOO") + let result = try parser.parseCommandStream(buffer: &buf) + #expect(result == nil) + } + + @Test("synchronising literal without literal data returns SynchronizedCommand with count only") + func synchronisingLiteralWithoutLiteralDataReturnsSynchronizedCommandWithCountOnly() throws { + // The framing parser finds 1 synchronising literal but the literal bytes are absent. + // parseCommand() returns nil (IncompleteMessage), but synchronizingLiteralCount == 1. + var parser = CommandParser() + var buf = ByteBuffer("1 LOGIN {5}\r\n") + let result = try parser.parseCommandStream(buffer: &buf) + #expect(result == SynchronizedCommand(numberOfSynchronisingLiterals: 1)) + } + + // MARK: - Continuation response + + @Test("authentication continuation response is parsed from base64 line") + func authenticationContinuationResponseIsParsedFromBase64Line() throws { + // A base64-encoded line (not a tagged command or APPEND) is parsed as a + // continuationResponse via parseAuthenticationChallengeResponse. + var parser = CommandParser() + // "AHRlc3R1c2VyAHRlc3RwYXNz" is base64 for "\0testuser\0testpass" + var buf = ByteBuffer("AHRlc3R1c2VyAHRlc3RwYXNz\r\n") + let result = try parser.parseCommandStream(buffer: &buf) + guard case .continuationResponse = result?.commandPart else { + Issue.record("Expected continuationResponse, got \(String(describing: result))") + return + } + #expect(buf.readableBytes == 0) + } + + // MARK: - Incomplete CRLF in waitingForMessage mode + + @Test("invalid bytes in waitingForMessage triggers buffer restore and rethrow") + func invalidBytesInWaitingForMessageTriggersBufferRestoreAndRethrow() throws { + // After all message bytes are streamed, the parser is in .waitingForMessage. + // If the next line is neither a new message header nor a CRLF (e.g. garbage text), + // parseAppendOrCatenateMessage throws ParserError, then parseNewline also fails + // on the non-newline byte — triggering the buffer-restore path (line 231 in + // CommandParser.swift) before rethrowing. + var parser = CommandParser() + var buf = ByteBuffer("1 APPEND INBOX {0+}\r\ngarbage\r\n") + + let c1 = try parser.parseCommandStream(buffer: &buf) + #expect(c1 == SynchronizedCommand(.append(.start(tag: "1", appendingTo: .inbox)))) + + let c2 = try parser.parseCommandStream(buffer: &buf) + #expect( + c2 == SynchronizedCommand(.append(.beginMessage(message: .init(options: .none, data: .init(byteCount: 0))))) + ) + + let c3 = try parser.parseCommandStream(buffer: &buf) // .messageBytes(empty) — 0-byte literal + #expect(c3 == SynchronizedCommand(.append(.messageBytes(ByteBuffer())))) + + let c4 = try parser.parseCommandStream(buffer: &buf) // .endMessage, mode = .waitingForMessage + #expect(c4 == SynchronizedCommand(.append(.endMessage))) + + // "garbage" is not a valid append-continue token or newline; parseNewline fails on "g", + // which triggers the buffer restore (line 231) and a rethrow. + #expect(throws: (any Error).self) { + try parser.parseCommandStream(buffer: &buf) + } + } + // MARK: - IDLE Command Tests @Test("IDLE command lifecycle with mode transitions") diff --git a/Tests/NIOIMAPCoreTests/Parser/SynchronizingLiteralParserTests.swift b/Tests/NIOIMAPCoreTests/Parser/SynchronizingLiteralParserTests.swift index 23538642..8addfee1 100644 --- a/Tests/NIOIMAPCoreTests/Parser/SynchronizingLiteralParserTests.swift +++ b/Tests/NIOIMAPCoreTests/Parser/SynchronizingLiteralParserTests.swift @@ -177,6 +177,30 @@ struct SynchronizingLiteralParserTests { ) } + @Test( + "invalid literal syntax throws", + arguments: [ + // "}" immediately before newline — after stripping "}" the buffer is empty, + // so reverseParseIf("+") hits the .none branch and throws. + "}\r\n", + // "{}" — no digits between braces; reverseParseNumber encounters a + // non-digit on the first attempt with magnitude == 1 and throws. + "{}\r\n", + // "+}" — after stripping "}" and "+" the buffer is empty when + // reverseParseNumber is called, so the .none branch throws. + "+}\r\n", + // Literal size that overflows Int (19 nines on 64-bit = > Int.max). + "{9999999999999999999}\r\n", + ] as [String] + ) + func invalidLiteralSyntaxThrows(input: String) { + var parser = SynchronizingLiteralParser() + let buffer = ByteBuffer(string: input) + #expect(throws: (any Error).self) { + try parser.parseContinuationsNecessary(buffer) + } + } + @Test("append followed by half command") func appendFollowedByHalfCommand() { var helper = Helper() diff --git a/Tests/NIOIMAPCoreTests/Parser/UInt8+ParseTypeMembership.swift b/Tests/NIOIMAPCoreTests/Parser/UInt8+ParseTypeMembership.swift index 3847e7d6..3b449a5e 100644 --- a/Tests/NIOIMAPCoreTests/Parser/UInt8+ParseTypeMembership.swift +++ b/Tests/NIOIMAPCoreTests/Parser/UInt8+ParseTypeMembership.swift @@ -19,7 +19,7 @@ import Testing struct UInt8ParseTypeMembershipTests { let allChars = Set(UInt8.min...UInt8.max) - @Test + @Test("CR") func CR() { let valid: Set = [UInt8(ascii: "\r")] let invalid = allChars.subtracting(valid) @@ -27,7 +27,7 @@ struct UInt8ParseTypeMembershipTests { #expect(invalid.allSatisfy { !$0.isCR }) } - @Test + @Test("LF") func LF() { let valid: Set = [UInt8(ascii: "\n")] let invalid = allChars.subtracting(valid) diff --git a/Tests/NIOIMAPCoreTests/PipeliningTests.swift b/Tests/NIOIMAPCoreTests/PipeliningTests.swift index 81588555..f16782df 100644 --- a/Tests/NIOIMAPCoreTests/PipeliningTests.swift +++ b/Tests/NIOIMAPCoreTests/PipeliningTests.swift @@ -52,6 +52,7 @@ extension SearchKey { .or(.uid(.set([1])), .sequenceNumbers(.set([1]))), .and([.unseen, .sequenceNumbers(.set([1]))]), .and([.uid(.set([1])), .sequenceNumbers(.set([1]))]), + .not(.sequenceNumbers(.set([1]))), ] fileprivate static let keysWithoutUID: [SearchKey] = [ @@ -68,6 +69,7 @@ extension SearchKey { .or(.uid(.set([1])), .sequenceNumbers(.set([1]))), .and([.unseen, .uid(.set([1]))]), .and([.uid(.set([1])), .sequenceNumbers(.set([1]))]), + .not(.uid(.set([1]))), ] fileprivate static let keysWithoutFlags: [SearchKey] = [ @@ -78,6 +80,8 @@ extension SearchKey { .subject("foo"), .or(.bcc("foo"), .uid(.set([1]))), .and([.uid(.set([1])), .sequenceNumbers(.set([1]))]), + // modificationSequence with no extensions does not reference flags + .modificationSequence(.init(extensions: [:], sequenceValue: 1)), ] fileprivate static let keysWithFlags: [SearchKey] = [ @@ -95,6 +99,9 @@ extension SearchKey { .undraft, .or(.answered, .uid(.set([1]))), .and([.answered, .sequenceNumbers(.set([1]))]), + .not(.answered), + // modificationSequence with non-empty extensions references flags + .modificationSequence(.init(extensions: [EntryFlagName(flag: .answered): .shared], sequenceValue: 1)), ] fileprivate static let arbitraryKeys: [SearchKey] = [ @@ -1605,4 +1612,248 @@ struct PipeliningTests { haveBehavior: .barrier ) } + + // MARK: CommandStreamPart pipelining + + @Test("command stream part pipelining requirements and behavior") + func commandStreamPartPipelining() { + // idleDone has no requirements + #expect(CommandStreamPart.idleDone.pipeliningRequirements == []) + // continuationResponse has no requirements + #expect(CommandStreamPart.continuationResponse(ByteBuffer(string: "")).pipeliningRequirements == []) + + // idleDone has specific behaviors + #expect(CommandStreamPart.idleDone.pipeliningBehavior.contains(.barrier)) + #expect(CommandStreamPart.idleDone.pipeliningBehavior.contains(.mayTriggerUntaggedExpunge)) + + // tagged part delegates to the wrapped command's behavior + let tagged = CommandStreamPart.tagged(TaggedCommand(tag: "A1", command: .capability)) + #expect(tagged.pipeliningBehavior == Command.capability.pipeliningBehavior) + + // non-start/non-catenateURL append commands have empty behavior + #expect(CommandStreamPart.append(.endMessage).pipeliningBehavior == []) + + // continuationResponse has no behavior + #expect(CommandStreamPart.continuationResponse(ByteBuffer(string: "")).pipeliningBehavior == []) + } + + // MARK: Gmail-label store pipelining + + @Test("store with gmail labels pipelining requirements") + func commandGmailLabelsRequirements() { + // Silent store with gmail labels requires noFlagReadsFromAnyMessage but NOT noFlagChangesToAnyMessage + expect( + commands: [ + (#_sourceLocation, .store(.set([1]), [], .gmailLabels(.add(silent: true, gmailLabels: [])))) + ], + require: .noFlagReadsFromAnyMessage + ) + expect( + commands: [ + (#_sourceLocation, .store(.set([1]), [], .gmailLabels(.add(silent: true, gmailLabels: [])))) + ], + doNotRequire: .noFlagChangesToAnyMessage + ) + + // Non-silent store with gmail labels requires both + expect( + commands: [ + (#_sourceLocation, .store(.set([1]), [], .gmailLabels(.add(silent: false, gmailLabels: [])))) + ], + require: .noFlagReadsFromAnyMessage + ) + expect( + commands: [ + (#_sourceLocation, .store(.set([1]), [], .gmailLabels(.add(silent: false, gmailLabels: [])))) + ], + require: .noFlagChangesToAnyMessage + ) + + // uidStore(.lastCommand) with flags, silent=true — requires noFlagReadsFromAnyMessage only + expect( + commands: [ + (#_sourceLocation, .uidStore(.lastCommand, [], .flags(.add(silent: true, list: [.answered])))) + ], + require: .noFlagReadsFromAnyMessage + ) + expect( + commands: [ + (#_sourceLocation, .uidStore(.lastCommand, [], .flags(.add(silent: true, list: [.answered])))) + ], + doNotRequire: .noFlagChangesToAnyMessage + ) + + // uidStore(.lastCommand) with gmail labels, both silent variants + expect( + commands: [ + (#_sourceLocation, .uidStore(.lastCommand, [], .gmailLabels(.add(silent: true, gmailLabels: [])))) + ], + require: .noFlagReadsFromAnyMessage + ) + expect( + commands: [ + (#_sourceLocation, .uidStore(.lastCommand, [], .gmailLabels(.add(silent: true, gmailLabels: [])))) + ], + doNotRequire: .noFlagChangesToAnyMessage + ) + expect( + commands: [ + (#_sourceLocation, .uidStore(.lastCommand, [], .gmailLabels(.add(silent: false, gmailLabels: [])))) + ], + require: .noFlagReadsFromAnyMessage + ) + expect( + commands: [ + (#_sourceLocation, .uidStore(.lastCommand, [], .gmailLabels(.add(silent: false, gmailLabels: [])))) + ], + require: .noFlagChangesToAnyMessage + ) + + // uidStore(.set) with gmail labels + MessageIdentifierSetNonEmpty.arbitrarySets.forEach { uids in + expect( + commands: [ + (#_sourceLocation, .uidStore(.set(uids), [], .gmailLabels(.add(silent: true, gmailLabels: [])))) + ], + require: .noFlagReads(uids) + ) + expect( + commands: [ + (#_sourceLocation, .uidStore(.set(uids), [], .gmailLabels(.add(silent: true, gmailLabels: [])))) + ], + doNotRequire: .noFlagChanges(uids) + ) + expect( + commands: [ + (#_sourceLocation, .uidStore(.set(uids), [], .gmailLabels(.add(silent: false, gmailLabels: [])))) + ], + require: .noFlagReads(uids) + ) + expect( + commands: [ + (#_sourceLocation, .uidStore(.set(uids), [], .gmailLabels(.add(silent: false, gmailLabels: [])))) + ], + require: .noFlagChanges(uids) + ) + } + } + + @Test("store with gmail labels pipelining behavior") + func commandGmailLabelsBehavior() { + // store gmailLabels silent=true changes flags but doesn't read them + expect( + commands: [ + (#_sourceLocation, .store(.set([1]), [], .gmailLabels(.add(silent: true, gmailLabels: [])))) + ], + haveBehavior: .changesFlagsOnAnyMessage + ) + expect( + commands: [ + (#_sourceLocation, .store(.set([1]), [], .gmailLabels(.add(silent: true, gmailLabels: [])))) + ], + doNotHaveBehavior: .readsFlagsFromAnyMessage + ) + // store gmailLabels silent=false changes and reads flags + expect( + commands: [ + (#_sourceLocation, .store(.set([1]), [], .gmailLabels(.add(silent: false, gmailLabels: [])))) + ], + haveBehavior: .readsFlagsFromAnyMessage + ) + + // uidStore(.lastCommand) flags silent=true + expect( + commands: [ + (#_sourceLocation, .uidStore(.lastCommand, [], .flags(.add(silent: true, list: [.answered])))) + ], + haveBehavior: .changesFlagsOnAnyMessage + ) + expect( + commands: [ + (#_sourceLocation, .uidStore(.lastCommand, [], .flags(.add(silent: true, list: [.answered])))) + ], + doNotHaveBehavior: .readsFlagsFromAnyMessage + ) + // uidStore(.lastCommand) flags silent=false + expect( + commands: [ + (#_sourceLocation, .uidStore(.lastCommand, [], .flags(.add(silent: false, list: [.answered])))) + ], + haveBehavior: .changesFlagsOnAnyMessage + ) + expect( + commands: [ + (#_sourceLocation, .uidStore(.lastCommand, [], .flags(.add(silent: false, list: [.answered])))) + ], + haveBehavior: .readsFlagsFromAnyMessage + ) + // uidStore(.lastCommand) gmailLabels both silent variants + expect( + commands: [ + (#_sourceLocation, .uidStore(.lastCommand, [], .gmailLabels(.add(silent: true, gmailLabels: [])))) + ], + haveBehavior: .changesFlagsOnAnyMessage + ) + expect( + commands: [ + (#_sourceLocation, .uidStore(.lastCommand, [], .gmailLabels(.add(silent: true, gmailLabels: [])))) + ], + doNotHaveBehavior: .readsFlagsFromAnyMessage + ) + expect( + commands: [ + (#_sourceLocation, .uidStore(.lastCommand, [], .gmailLabels(.add(silent: false, gmailLabels: [])))) + ], + haveBehavior: .readsFlagsFromAnyMessage + ) + + // uidStore(.set) gmailLabels + MessageIdentifierSetNonEmpty.arbitrarySets.forEach { uids in + expect( + commands: [ + (#_sourceLocation, .uidStore(.set(uids), [], .gmailLabels(.add(silent: true, gmailLabels: [])))) + ], + doNotHaveBehavior: .readsFlags(uids) + ) + expect( + commands: [ + (#_sourceLocation, .uidStore(.set(uids), [], .gmailLabels(.add(silent: false, gmailLabels: [])))) + ], + haveBehavior: .readsFlags(uids) + ) + } + } + + // MARK: uidFetch(.lastCommand) behavior + + @Test("uidFetch last command pipelining behavior") + func commandUIDFetchLastCommandBehavior() { + // Without flags — does not read flags + expect( + commands: [ + (#_sourceLocation, .uidFetch(.lastCommand, [.envelope, .uid], [])) + ], + doNotHaveBehavior: .readsFlagsFromAnyMessage + ) + // With flags — reads flags from any message + expect( + commands: [ + (#_sourceLocation, .uidFetch(.lastCommand, [.uid, .flags], [])) + ], + haveBehavior: .readsFlagsFromAnyMessage + ) + } + + // MARK: Command.custom pipelining + + @Test("custom command pipelining requirements and behavior") + func commandCustomPipelining() { + let custom = Command.custom(name: "X-TEST", payloads: []) + // Custom commands require many things + #expect(custom.pipeliningRequirements.contains(.noMailboxCommandsRunning)) + #expect(custom.pipeliningRequirements.contains(.noUntaggedExpungeResponse)) + #expect(custom.pipeliningRequirements.contains(.noUIDBasedCommandRunning)) + // Custom command behavior is a barrier + #expect(custom.pipeliningBehavior.contains(.barrier)) + } } diff --git a/Tests/NIOIMAPCoreTests/ResponseEncodeBuffer+Tests.swift b/Tests/NIOIMAPCoreTests/ResponseEncodeBuffer+Tests.swift index 21986983..01cb036b 100644 --- a/Tests/NIOIMAPCoreTests/ResponseEncodeBuffer+Tests.swift +++ b/Tests/NIOIMAPCoreTests/ResponseEncodeBuffer+Tests.swift @@ -44,4 +44,25 @@ struct ResponseEncodeBufferTests { let outputString = String(buffer: buffer.readBytes()) #expect(outputString == "* 1 FETCH (BODY[] {10}\r\n0123456789)\r\n") } + + @Test("init with capabilities") + func initWithCapabilities() { + var buffer = ResponseEncodeBuffer(buffer: ByteBuffer(), capabilities: [.imap4rev1], loggingMode: false) + buffer.writeFetchResponse(.start(1)) + buffer.writeFetchResponse(.finish) + let outputString = String(buffer: buffer.readBytes()) + #expect(outputString == "* 1 FETCH ()\r\n") + } + + @Test("correctly streams binary attribute") + func correctlyStreamsBinaryAttribute() { + var buffer = ResponseEncodeBuffer(buffer: ByteBuffer(string: ""), options: .rfc3501, loggingMode: false) + buffer.writeFetchResponse(.start(1)) + buffer.writeFetchResponse(.streamingBegin(kind: .binary(section: [], offset: nil), byteCount: 5)) + buffer.writeFetchResponse(.streamingBytes(ByteBuffer(string: "hello"))) + buffer.writeFetchResponse(.streamingEnd) + buffer.writeFetchResponse(.finish) + let outputString = String(buffer: buffer.readBytes()) + #expect(outputString == "* 1 FETCH (BINARY {5}\r\nhello)\r\n") + } }