<commit_before>/*
 
 *********************************************************************************
 THIS FILE WAS MODIFIED!
 *********************************************************************************
 
 This version is not the original version you can find at
 https://github.com/apple/swift/blob/1e110b8f63836734113cdb28970ebcea8fd383c2/test/stdlib/TestJSONEncoder.swift
 
 Large parts of the original content were modified.
 
 The original license is included in this repository
 in the file APACHE-LICENSE.txt.
 
 */

// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Swift
import Foundation
@testable import MetaSerialization

// MARK: - Test Suite
import XCTest

class TestMetaSerializationByJSONEncoderTests : XCTestCase {
    
    let translator = PrimitivesEnumTranslator(primitives: [ .nil, .bool, .string, .int, .double ],
                                              encode: encodeToContainer,
                                              decode: decodeFromContainer)
    
    lazy var serialization: SimpleSerialization<Container> = {
        return SimpleSerialization<Container>(translator: translator)
    }()
    
    // MARK: - Encoding Top-Level Empty Types
    
    func testEncodingTopLevelEmptyStruct() {
        let empty = EmptyStruct()
        _testRoundTrip(of: empty, expected: emptyContainer)
    }
    
    func testEncodingTopLevelEmptyClass() {
        let empty = EmptyClass()
        _testRoundTrip(of: empty, expected: emptyContainer)
    }
    
    let emptyContainer = Container.dictionary([:])
    
    // MARK: - Encoding Top-Level Single-Value Types
    func testEncodingTopLevelSingleValueEnum() {
        _testEncodeFailure(of: Switch.off)
        _testEncodeFailure(of: Switch.on)
        
        _testRoundTrip(of: TopLevelWrapper(Switch.off))
        _testRoundTrip(of: TopLevelWrapper(Switch.on))
    }
    
    func testEncodingTopLevelSingleValueStruct() {
        _testEncodeFailure(of: Timestamp(3141592653))
        _testRoundTrip(of: TopLevelWrapper(Timestamp(3141592653)))
    }
    
    func testEncodingTopLevelSingleValueClass() {
        _testEncodeFailure(of: Counter())
        _testRoundTrip(of: TopLevelWrapper(Counter()))
    }
    
    // MARK: - Encoding Top-Level Structured Types
    func testEncodingTopLevelStructuredStruct() {
        // Address is a struct type with multiple fields.
        let address = Address.testValue
        _testRoundTrip(of: address)
    }
    
    func testEncodingTopLevelStructuredClass() {
        // Person is a class with multiple fields.
        // let expectedJSON = "{\"name\":\"<NAME>\",\"email\":\"<EMAIL>\"}"
        let expectedContainer = Container.dictionary( [ "name": Container.string( "<NAME>" ),
                                                        "email": Container.string( "<EMAIL>" )] )
        let person = Person.testValue
        _testRoundTrip(of: person, expected: expectedContainer)
    }
    
    func testEncodingTopLevelStructuredSingleStruct() {
        // Numbers is a struct which encodes as an array through a single value container.
        let numbers = Numbers.testValue
        _testRoundTrip(of: numbers)
    }
    
    func testEncodingTopLevelStructuredSingleClass() {
        // Mapping is a class which encodes as a dictionary through a single value container.
        let mapping = Mapping.testValue
        _testRoundTrip(of: mapping)
    }
    
    func testEncodingTopLevelDeepStructuredType() {
        // Company is a type with fields which are Codable themselves.
        let company = Company.testValue
        _testRoundTrip(of: company)
    }
    
    func testEncodingClassWhichSharesEncoderWithSuper() {
        // Employee is a type which shares its encoder & decoder with its superclass, Person.
        let employee = Employee.testValue
        _testRoundTrip(of: employee)
    }
    
    func testEncodingTopLevelNullableType() {
        // EnhancedBool is a type which encodes either as a Bool or as nil.
        _testEncodeFailure(of: EnhancedBool.true)
        _testEncodeFailure(of: EnhancedBool.false)
        _testEncodeFailure(of: EnhancedBool.fileNotFound)
        
        _testRoundTrip(of: TopLevelWrapper(EnhancedBool.true), expected: Container.dictionary( ["value": Container.bool(true)] ) )
        _testRoundTrip(of: TopLevelWrapper(EnhancedBool.false), expected: Container.dictionary( ["value": Container.bool(false)] ) )
        _testRoundTrip(of: TopLevelWrapper(EnhancedBool.fileNotFound), expected: Container.dictionary( ["value": Container.nil] ) )
    }
    
    // MARK: - Encoder Features
    func testNestedContainerCodingPaths() {
        do {
            let _ = try serialization.encode(NestedContainersTestType())
        } catch let error as NSError {
            expectUnreachable("Caught error during encoding nested container types: \(error)")
        }
    }
    
    func testSuperEncoderCodingPaths() {
        do {
            let _ = try serialization.encode(NestedContainersTestType(testSuperEncoder: true))
        } catch let error as NSError {
            expectUnreachable("Caught error during encoding nested container types: \(error)")
        }
    }
    
    // MARK: - Type coercion
    func testTypeCoercion() {
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int8].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int16].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int32].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int64].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt8].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt16].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt32].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt64].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [Float].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [Double].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int8], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int16], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int32], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int64], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt8], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt16], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt32], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt64], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0.0, 1.0] as [Float], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0.0, 1.0] as [Double], as: [Bool].self)
    }
    
    func testDecodingConcreteTypeParameter() {
        guard let json = try? serialization.encode(Employee.testValue) else {
            expectUnreachable("Unable to encode Employee.")
            return
        }
        
        guard let decoded = try? serialization.decode(toType: Employee.self as Person.Type, from: json) else {
            expectUnreachable("Failed to decode Employee as Person from JSON.")
            return
        }
        
        // FIXME: fix this error
        // I don't quite know how to do this, respectively how JSONDecoder does it...
        assert(decoded is Employee, "Expected decoded value to be of type Employee; got \(type(of: decoded)) instead.")
    }
    
    // MARK: - Encoder State
    // SR-6078
    func testEncoderStateThrowOnEncode() {
        struct ReferencingEncoderWrapper<T : Encodable> : Encodable {
            let value: T
            init(_ value: T) { self.value = value }
            
            func encode(to encoder: Encoder) throws {
                // This approximates a subclass calling into its superclass, where the superclass encodes a value that might throw.
                // The key here is that getting the superEncoder creates a referencing encoder.
                var container = encoder.unkeyedContainer()
                let superEncoder = container.superEncoder()
                
                // Pushing a nested container on leaves the referencing encoder with multiple containers.
                var nestedContainer = superEncoder.unkeyedContainer()
                try nestedContainer.encode(value)<commit_msg>Found another bug<commit_after>/*
 
 *********************************************************************************
 THIS FILE WAS MODIFIED!
 *********************************************************************************
 
 This version is not the original version you can find at
 https://github.com/apple/swift/blob/1e110b8f63836734113cdb28970ebcea8fd383c2/test/stdlib/TestJSONEncoder.swift
 
 Large parts of the original content were modified.
 
 The original license is included in this repository
 in the file APACHE-LICENSE.txt.
 
 */

// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Swift
import Foundation
@testable import MetaSerialization

// MARK: - Test Suite
import XCTest

class TestMetaSerializationByJSONEncoderTests : XCTestCase {
    
    let translator = PrimitivesEnumTranslator(primitives: [ .nil, .bool, .string, .int, .double ],
                                              encode: encodeToContainer,
                                              decode: decodeFromContainer)
    
    lazy var serialization: SimpleSerialization<Container> = {
        return SimpleSerialization<Container>(translator: translator)
    }()
    
    // MARK: - Encoding Top-Level Empty Types
    
    func testEncodingTopLevelEmptyStruct() {
        let empty = EmptyStruct()
        _testRoundTrip(of: empty, expected: emptyContainer)
    }
    
    func testEncodingTopLevelEmptyClass() {
        let empty = EmptyClass()
        _testRoundTrip(of: empty, expected: emptyContainer)
    }
    
    let emptyContainer = Container.dictionary([:])
    
    // MARK: - Encoding Top-Level Single-Value Types
    func testEncodingTopLevelSingleValueEnum() {
        _testEncodeFailure(of: Switch.off)
        _testEncodeFailure(of: Switch.on)
        
        _testRoundTrip(of: TopLevelWrapper(Switch.off))
        _testRoundTrip(of: TopLevelWrapper(Switch.on))
    }
    
    func testEncodingTopLevelSingleValueStruct() {
        _testEncodeFailure(of: Timestamp(3141592653))
        _testRoundTrip(of: TopLevelWrapper(Timestamp(3141592653)))
    }
    
    func testEncodingTopLevelSingleValueClass() {
        _testEncodeFailure(of: Counter())
        _testRoundTrip(of: TopLevelWrapper(Counter()))
    }
    
    // MARK: - Encoding Top-Level Structured Types
    func testEncodingTopLevelStructuredStruct() {
        // Address is a struct type with multiple fields.
        let address = Address.testValue
        _testRoundTrip(of: address)
    }
    
    func testEncodingTopLevelStructuredClass() {
        // Person is a class with multiple fields.
        // let expectedJSON = "{\"name\":\"<NAME>\",\"email\":\"<EMAIL>\"}"
        let expectedContainer = Container.dictionary( [ "name": Container.string( "<NAME>" ),
                                                        "email": Container.string( "<EMAIL>" )] )
        let person = Person.testValue
        _testRoundTrip(of: person, expected: expectedContainer)
    }
    
    func testEncodingTopLevelStructuredSingleStruct() {
        // Numbers is a struct which encodes as an array through a single value container.
        let numbers = Numbers.testValue
        _testRoundTrip(of: numbers)
    }
    
    func testEncodingTopLevelStructuredSingleClass() {
        // Mapping is a class which encodes as a dictionary through a single value container.
        let mapping = Mapping.testValue
        _testRoundTrip(of: mapping)
    }
    
    func testEncodingTopLevelDeepStructuredType() {
        // Company is a type with fields which are Codable themselves.
        let company = Company.testValue
        _testRoundTrip(of: company)
    }
    
    func testEncodingClassWhichSharesEncoderWithSuper() {
        // Employee is a type which shares its encoder & decoder with its superclass, Person.
        let employee = Employee.testValue
        _testRoundTrip(of: employee)
    }
    
    func testEncodingTopLevelNullableType() {
        // EnhancedBool is a type which encodes either as a Bool or as nil.
        _testEncodeFailure(of: EnhancedBool.true)
        _testEncodeFailure(of: EnhancedBool.false)
        _testEncodeFailure(of: EnhancedBool.fileNotFound)
        
        _testRoundTrip(of: TopLevelWrapper(EnhancedBool.true), expected: Container.dictionary( ["value": Container.bool(true)] ) )
        _testRoundTrip(of: TopLevelWrapper(EnhancedBool.false), expected: Container.dictionary( ["value": Container.bool(false)] ) )
        _testRoundTrip(of: TopLevelWrapper(EnhancedBool.fileNotFound), expected: Container.dictionary( ["value": Container.nil] ) )
    }
    
    // MARK: - Encoder Features
    func testNestedContainerCodingPaths() {
        do {
            let _ = try serialization.encode(NestedContainersTestType())
        } catch let error as NSError {
            expectUnreachable("Caught error during encoding nested container types: \(error)")
        }
    }
    
    func testSuperEncoderCodingPaths() {
        do {
            let _ = try serialization.encode(NestedContainersTestType(testSuperEncoder: true))
        } catch let error as NSError {
            expectUnreachable("Caught error during encoding nested container types: \(error)")
        }
    }
    
    // MARK: - Type coercion
    func testTypeCoercion() {
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int8].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int16].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int32].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [Int64].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt8].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt16].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt32].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [UInt64].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [Float].self)
        _testRoundTripTypeCoercionFailure(of: [false, true], as: [Double].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int8], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int16], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int32], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [Int64], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt8], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt16], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt32], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0, 1] as [UInt64], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0.0, 1.0] as [Float], as: [Bool].self)
        _testRoundTripTypeCoercionFailure(of: [0.0, 1.0] as [Double], as: [Bool].self)
    }
    
    func testDecodingConcreteTypeParameter() {
        guard let encoded = try? serialization.encode(Employee.testValue) else {
            expectUnreachable("Unable to encode Employee.")
            return
        }
        
        guard let decoded = try? serialization.decode(toType: Employee.self as Person.Type, from: encoded) else {
            expectUnreachable("Failed to decode Employee as Person.")
            return
        }
        
        // FIXME: fix this error
        assert(decoded is Employee, "Expected decoded value to be of type Employee; got \(type(of: decoded)) instead.")
    }
    
    // MARK: - Encoder State
    // SR-6078
    func testEncoderStateThrowOnEncode() {
        struct ReferencingEncoderWrapper<T : Encodable> : Encodable {
            let value: T
            init(_ value: T) { self.value = value }
            
            func encode(to encoder: Encoder) throws {
                // This approximates a subclass calling into its superclass, where the superclass encodes a value that might throw.
                // The key here is that getting the superEncoder creates a referencing encoder.
                var container = encoder.unkeyedContainer()
                let superEncoder = container.superEncoder()
                
                // Pushing a nested container on leaves the referencing encoder with multiple containers.
                var nestedContainer = superEncoder.unkeyedContainer()
                try nestedContainer.encode(value)
{'fraction_non_alphanumeric': 0.12156113537117903, 'fraction_numerical': 0.012663755458515284, 'mean_word_length': 2.7466257668711656, 'pattern_counts': {'":': 14, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '212023', 'n_tokens_mistral': 5344, 'n_tokens_neox': 5051, 'n_words': 1308}