<commit_before>/**
 * Copyright IBM Corporation 2016
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

import XCTest
import Foundation
import DialogV1

class DialogTests: XCTestCase {

    private var dialog: Dialog!
    private let prefix = "swift-sdk-unit-test-"
    private var dialogID: DialogID?
    private var dialogName: String?
    private let timeout: TimeInterval = 10.0

    // MARK: - Test Configuration

	private func generateRandomNumber(max: UInt32) -> Int {
		#if os(Linux)
			return Int(rand() % Int32(max))
		#else
			return Int(arc4random_uniform(max))
		#endif
	}

    /** Set up for each test by instantiating the service. */
    override func setUp() {
        super.setUp()
        continueAfterFailure = false
        instantiateDialog()
        lookupDialog()
    }
    
    static var allTests : [(String, (DialogTests) -> () throws -> Void)] {
        return [
            ("testGetDialogs", testGetDialogs),
            ("testCreateDelete", testCreateDelete),
            ("testGetDialogFile", testGetDialogFile),
            ("testGetDialogFileOctetStream", testGetDialogFileOctetStream),
            ("testGetDialogFileJSON", testGetDialogFileJSON),
            ("testGetDialogFileXML", testGetDialogFileXML),
            ("testUpdateDialog", testUpdateDialog),
            ("testGetContent", testGetContent),
            ("testUpdateContent", testUpdateContent),
            ("testGetConversationHistory", testGetConversationHistory),
            ("testGetConversationHistoryWithOffset", testGetConversationHistoryWithOffset),
            ("testGetConversationHistoryWithLimit", testGetConversationHistoryWithLimit),
            ("testConverse", testConverse),
            ("testGetProfile", testGetProfile),
            ("testUpdateNewProfile", testUpdateNewProfile),
            ("testUpdateExistingProfile", testUpdateExistingProfile),
            ("testCreateDialogWithInvalidFile", testCreateDialogWithInvalidFile),
            ("testCreateDialogWithConflictingName", testCreateDialogWithConflictingName),
            ("testCreateDialogWithLongName", testCreateDialogWithLongName),
            ("testCreateDialogWithNonexistentFile", testCreateDialogWithNonexistentFile),
            ("testDeleteInvalidDialogID", testDeleteInvalidDialogID),
            ("testGetDialogFileForInvalidDialogID", testGetDialogFileForInvalidDialogID),
            ("testUpdateDialogWithInvalidFile", testUpdateDialogWithInvalidFile),
            ("testUpdateDialogWithNonexistentFile", testUpdateDialogWithNonexistentFile),
            ("testUpdateDialogForInvalidDialogID", testUpdateDialogForInvalidDialogID),
            ("testGetContentForInvalidDialogID", testGetContentForInvalidDialogID),
            ("testUpdateContentInvalid", testUpdateContentInvalid),
            ("testUpdateContentForInvalidDialogID", testUpdateContentForInvalidDialogID),
            ("testGetConversationHistoryForInvalidDialogID", testGetConversationHistoryForInvalidDialogID),
            ("testConverseWithInvalidDialogID", testConverseWithInvalidDialogID),
            ("testConverseWithInvalidIDs", testConverseWithInvalidIDs),
            ("testGetProfileWithInvalidDialogID", testGetProfileWithInvalidDialogID),
            ("testGetProfileWithInvalidClientID", testGetProfileWithInvalidClientID),
            ("testGetProfileWithInvalidParameterNames", testGetProfileWithInvalidParameterNames),
            ("testUpdateProfileWithInvalidDialogID", testUpdateProfileWithInvalidDialogID),
            ("testUpdateProfileWithInvalidClientID", testUpdateProfileWithInvalidClientID)
        ]
    }

    /** Instantiate Dialog. */
    func instantiateDialog() {
        let username = Credentials.DialogUsername
        let password = <PASSWORD>.DialogPassword
        dialog = Dialog(username: username, password: password)
    }

    /** Look up (or create) the test dialog application. */
    func lookupDialog() {
        let description = "Look up (or create) the test dialog application."
        let expectation = self.expectation(description: description)
        
        let failure = { (error: Error) in
            XCTFail("Failed to list the dialog applications.")
        }
        
        dialog.getDialogs(failure: failure) { dialogs in
            for dialog in dialogs {
                if dialog.name.hasPrefix(self.prefix) {
                    self.dialogID = dialog.dialogID
                    self.dialogName = dialog.name
                    expectation.fulfill()
                    return
                }
            }
            expectation.fulfill()
        }
        waitForExpectations()
        
        if (self.dialogID == nil) || (self.dialogName == nil) {
            createDialog()
        }
    }
    
    /** Create the test dialog application. */
    func createDialog() {
        let description = "Create the test dialog application."
        let expectation = self.expectation(description: description)
        
        let dialogName = createDialogName()
        
        guard let fileURL = loadDialogFile(name: "pizza_sample", withExtension: "xml") else {
            XCTFail("Failed to load dialog file.")
            return
        }
        
        let failure = { (error: Error) in
            XCTFail("Failed to create the test dialog application.")
        }

        dialog.createDialog(withName: dialogName, fromFile: fileURL, failure: failure) { id in
            self.dialogID = id
            self.dialogName = dialogName
            expectation.fulfill()
        }
        waitForExpectations()
    }

    /** Fail false negatives. */
    func failWithError(error: Error) {
        XCTFail("Positive test failed with error: \(error)")
    }

    /** Fail false positives. */
    func failWithResult<T>(result: T) {
        XCTFail("Negative test returned a result.")
    }

    /** Wait for expectation */
    func waitForExpectations() {
        waitForExpectations(timeout: timeout) { error in
            XCTAssertNil(error, "Timeout")
        }
    }

    // MARK: - Helper Functions

    /** Generate a random alpha-numeric string. (Courtesy of Dschee on StackOverflow.) */
    func randomAlphaNumericString(length: Int) -> String {
        let allowedChars = "abcdefghijklmnopqrstuvwxyz0123456789"
        let allowedCharsCount = UInt32(allowedChars.characters.count)
        var randomString = ""

        for _ in (0..<length) {
            let randomNum = generateRandomNumber(max: allowedCharsCount)
            let newCharacter = allowedChars[allowedChars.index(allowedChars.startIndex, offsetBy: randomNum)]
            randomString += String(newCharacter)
        }

        return randomString
    }

    /** Generate the name for a dialog application. */
    func createDialogName() -> String {
        return prefix + randomAlphaNumericString(length: 5)
    }

    /** Load a dialog file. */
    func loadDialogFile(name: String, withExtension: String) -> URL? {
        let bundle = Bundle(for: type(of: self))
        guard let url = bundle.url(forResource: name, withExtension: withExtension) else {
            return nil
        }
        return url
    }

    // MARK: - Positive Tests - Content Operations

    /** List the dialog applications associated with this service instance. */
    func testGetDialogs() {
        let description = "List the dialog applications associated with this service instance."
        let expectation = self.expectation(description: description)

        dialog.getDialogs(failure: failWithError) { dialogs in
            for dialog in dialogs {
                let idMatch = (dialog.dialogID == self.dialogID)
                let nameMatch = (dialog.name == self.dialogName)
                if idMatch && nameMatch {
                    expectation.fulfill()
                    return
                }
            }
            XCTFail("Could not retrieve the test dialog application.")
        }
        waitForExpectations()
    }
<commit_msg>Workaround for Bundle not implemented error in Linux for Dialog<commit_after>/**
 * Copyright IBM Corporation 2016
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

import XCTest
import Foundation
import DialogV1

class DialogTests: XCTestCase {

    private var dialog: Dialog!
    private let prefix = "swift-sdk-unit-test-"
    private var dialogID: DialogID?
    private var dialogName: String?
    private let timeout: TimeInterval = 10.0

    // MARK: - Test Configuration

	private func generateRandomNumber(max: UInt32) -> Int {
		#if os(Linux)
			return Int(rand() % Int32(max))
		#else
			return Int(arc4random_uniform(max))
		#endif
	}

    /** Set up for each test by instantiating the service. */
    override func setUp() {
        super.setUp()
        continueAfterFailure = false
        instantiateDialog()
        lookupDialog()
    }
    
    static var allTests : [(String, (DialogTests) -> () throws -> Void)] {
        return [
            ("testGetDialogs", testGetDialogs),
            ("testCreateDelete", testCreateDelete),
            ("testGetDialogFile", testGetDialogFile),
            ("testGetDialogFileOctetStream", testGetDialogFileOctetStream),
            ("testGetDialogFileJSON", testGetDialogFileJSON),
            ("testGetDialogFileXML", testGetDialogFileXML),
            ("testUpdateDialog", testUpdateDialog),
            ("testGetContent", testGetContent),
            ("testUpdateContent", testUpdateContent),
            ("testGetConversationHistory", testGetConversationHistory),
            ("testGetConversationHistoryWithOffset", testGetConversationHistoryWithOffset),
            ("testGetConversationHistoryWithLimit", testGetConversationHistoryWithLimit),
            ("testConverse", testConverse),
            ("testGetProfile", testGetProfile),
            ("testUpdateNewProfile", testUpdateNewProfile),
            ("testUpdateExistingProfile", testUpdateExistingProfile),
            ("testCreateDialogWithInvalidFile", testCreateDialogWithInvalidFile),
            ("testCreateDialogWithConflictingName", testCreateDialogWithConflictingName),
            ("testCreateDialogWithLongName", testCreateDialogWithLongName),
            ("testCreateDialogWithNonexistentFile", testCreateDialogWithNonexistentFile),
            ("testDeleteInvalidDialogID", testDeleteInvalidDialogID),
            ("testGetDialogFileForInvalidDialogID", testGetDialogFileForInvalidDialogID),
            ("testUpdateDialogWithInvalidFile", testUpdateDialogWithInvalidFile),
            ("testUpdateDialogWithNonexistentFile", testUpdateDialogWithNonexistentFile),
            ("testUpdateDialogForInvalidDialogID", testUpdateDialogForInvalidDialogID),
            ("testGetContentForInvalidDialogID", testGetContentForInvalidDialogID),
            ("testUpdateContentInvalid", testUpdateContentInvalid),
            ("testUpdateContentForInvalidDialogID", testUpdateContentForInvalidDialogID),
            ("testGetConversationHistoryForInvalidDialogID", testGetConversationHistoryForInvalidDialogID),
            ("testConverseWithInvalidDialogID", testConverseWithInvalidDialogID),
            ("testConverseWithInvalidIDs", testConverseWithInvalidIDs),
            ("testGetProfileWithInvalidDialogID", testGetProfileWithInvalidDialogID),
            ("testGetProfileWithInvalidClientID", testGetProfileWithInvalidClientID),
            ("testGetProfileWithInvalidParameterNames", testGetProfileWithInvalidParameterNames),
            ("testUpdateProfileWithInvalidDialogID", testUpdateProfileWithInvalidDialogID),
            ("testUpdateProfileWithInvalidClientID", testUpdateProfileWithInvalidClientID)
        ]
    }

    /** Instantiate Dialog. */
    func instantiateDialog() {
        let username = Credentials.DialogUsername
        let password = <PASSWORD>
        dialog = Dialog(username: username, password: password)
    }

    /** Look up (or create) the test dialog application. */
    func lookupDialog() {
        let description = "Look up (or create) the test dialog application."
        let expectation = self.expectation(description: description)
        
        let failure = { (error: Error) in
            XCTFail("Failed to list the dialog applications.")
        }
        
        dialog.getDialogs(failure: failure) { dialogs in
            for dialog in dialogs {
                if dialog.name.hasPrefix(self.prefix) {
                    self.dialogID = dialog.dialogID
                    self.dialogName = dialog.name
                    expectation.fulfill()
                    return
                }
            }
            expectation.fulfill()
        }
        waitForExpectations()
        
        if (self.dialogID == nil) || (self.dialogName == nil) {
            createDialog()
        }
    }
    
    /** Create the test dialog application. */
    func createDialog() {
        let description = "Create the test dialog application."
        let expectation = self.expectation(description: description)
        
        let dialogName = createDialogName()
        
        guard let fileURL = loadDialogFile(name: "pizza_sample", withExtension: "xml") else {
            XCTFail("Failed to load dialog file.")
            return
        }
        
        let failure = { (error: Error) in
            XCTFail("Failed to create the test dialog application.")
        }

        dialog.createDialog(withName: dialogName, fromFile: fileURL, failure: failure) { id in
            self.dialogID = id
            self.dialogName = dialogName
            expectation.fulfill()
        }
        waitForExpectations()
    }

    /** Fail false negatives. */
    func failWithError(error: Error) {
        XCTFail("Positive test failed with error: \(error)")
    }

    /** Fail false positives. */
    func failWithResult<T>(result: T) {
        XCTFail("Negative test returned a result.")
    }

    /** Wait for expectation */
    func waitForExpectations() {
        waitForExpectations(timeout: timeout) { error in
            XCTAssertNil(error, "Timeout")
        }
    }

    // MARK: - Helper Functions

    /** Generate a random alpha-numeric string. (Courtesy of Dschee on StackOverflow.) */
    func randomAlphaNumericString(length: Int) -> String {
        let allowedChars = "abcdefghijklmnopqrstuvwxyz0123456789"
        let allowedCharsCount = UInt32(allowedChars.characters.count)
        var randomString = ""

        for _ in (0..<length) {
            let randomNum = generateRandomNumber(max: allowedCharsCount)
            let newCharacter = allowedChars[allowedChars.index(allowedChars.startIndex, offsetBy: randomNum)]
            randomString += String(newCharacter)
        }

        return randomString
    }

    /** Generate the name for a dialog application. */
    func createDialogName() -> String {
        return prefix + randomAlphaNumericString(length: 5)
    }

    /** Load a dialog file. */
    func loadDialogFile(name: String, withExtension: String) -> URL? {
        
        let url:URL
        
        #if os(iOS)
            let bundle = Bundle(for: type(of: self))
            guard url = bundle.url(forResource: name, withExtension: withExtension) else {
                return nil
            }
        #else
            url = URL(fileURLWithPath: "DialogV1Tests/"+name+"."+withExtension)
        #endif
        
        return url
    }

    // MARK: - Positive Tests - Content Operations

    /** List the dialog applications associated with this service instance. */
    func testGetDialogs() {
        let description = "List the dialog applications associated with this service instance."
        let expectation = self.expectation(description: description)

        dialog.getDialogs(failure: failWithError) { dialogs in
            for dialog in dialogs {
                let idMatch = (dialog.dialogID == self.dialogID)
                let nameMatch = (dialog.name == self.dialogName)
                if idMatch && nameMatch {
                    expectation.fulfill()
                    return
                }
            }
            XCTFail("Could not retrieve the test dialog application.")
        }
        waitForExpectations()
    }

{'fraction_non_alphanumeric': 0.08624803584938602, 'fraction_numerical': 0.003666414479427341, 'mean_word_length': 2.583733055265902, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3613337', 'n_tokens_mistral': 4304, 'n_tokens_neox': 4142, 'n_words': 1093}