#!/usr/bin/env python

# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Unit tests for the MSVSSettings.py file."""

import unittest
import gyp.MSVS.MSVSSettings as MSVSSettings
try:
  # noinspection PyCompatibility
  from cStringIO import StringIO
except ImportError:
  from io import StringIO

class TestSequenceFunctions(unittest.TestCase):

  def setUp(self):
    self.stderr = StringIO()

  def _ExpectedWarnings(self, expected):
    """Compares recorded lines to expected warnings."""
    self.stderr.seek(0)
    actual = self.stderr.read().split('\n')
    actual = [line for line in actual if line]
    self.assertEqual(sorted(expected), sorted(actual))

  def testValidateMSVSSettings_tool_names(self):
    """Tests that only MSVS tool names are allowed."""
    MSVSSettings.ValidateMSVSSettings(
        {'VCCLCompilerTool': {},
         'VCLinkerTool': {},
         'VCMIDLTool': {},
         'foo': {},
         'VCResourceCompilerTool': {},
         'VCLibrarianTool': {},
         'VCManifestTool': {},
         'ClCompile': {}},
        self.stderr)
    self._ExpectedWarnings([
        'Warning: unrecognized tool foo',
        'Warning: unrecognized tool ClCompile'])

  def testValidateMSVSSettings_settings(self):
    """Tests that for invalid MSVS settings."""
    MSVSSettings.ValidateMSVSSettings(
        {'VCCLCompilerTool': {
            'AdditionalIncludeDirectories': 'folder1;folder2',
            'AdditionalOptions': ['string1', 'string2'],
            'AdditionalUsingDirectories': 'folder1;folder2',
            'AssemblerListingLocation': 'a_file_name',
            'AssemblerOutput': '0',
            'BasicRuntimeChecks': '5',
            'BrowseInformation': 'fdkslj',
            'BrowseInformationFile': 'a_file_name',
            'BufferSecurityCheck': 'true',
            'CallingConvention': '-1',
            'CompileAs': '1',
            'DebugInformationFormat': '2',
            'DefaultCharIsUnsigned': 'true',
            'Detect64BitPortabilityProblems': 'true',
            'DisableLanguageExtensions': 'true',
            'DisableSpecificWarnings': 'string1;string2',
            'EnableEnhancedInstructionSet': '1',
            'EnableFiberSafeOptimizations': 'true',
            'EnableFunctionLevelLinking': 'true',
            'EnableIntrinsicFunctions': 'true',
            'EnablePREfast': 'true',
            'Enableprefast': 'bogus',
            'ErrorReporting': '1',
            'ExceptionHandling': '1',
            'ExpandAttributedSource': 'true',
            'FavorSizeOrSpeed': '1',
            'FloatingPointExceptions': 'true',
            'FloatingPointModel': '1',
            'ForceConformanceInForLoopScope': 'true',
            'ForcedIncludeFiles': 'file1;file2',
            'ForcedUsingFiles': 'file1;file2',
            'GeneratePreprocessedFile': '1',
            'GenerateXMLDocumentationFiles': 'true',
            'IgnoreStandardIncludePath': 'true',
            'InlineFunctionExpansion': '1',
            'KeepComments': 'true',
            'MinimalRebuild': 'true',
            'ObjectFile': 'a_file_name',
            'OmitDefaultLibName': 'true',
            'OmitFramePointers': 'true',
            'OpenMP': 'true',
            'Optimization': '1',
            'PrecompiledHeaderFile': 'a_file_name',
            'PrecompiledHeaderThrough': 'a_file_name',
            'PreprocessorDefinitions': 'string1;string2',
            'ProgramDataBaseFileName': 'a_file_name',
            'RuntimeLibrary': '1',
            'RuntimeTypeInfo': 'true',
            'ShowIncludes': 'true',
            'SmallerTypeCheck': 'true',
            'StringPooling': 'true',
            'StructMemberAlignment': '1',
            'SuppressStartupBanner': 'true',
            'TreatWChar_tAsBuiltInType': 'true',
            'UndefineAllPreprocessorDefinitions': 'true',
            'UndefinePreprocessorDefinitions': 'string1;string2',
            'UseFullPaths': 'true',
            'UsePrecompiledHeader': '1',
            'UseUnicodeResponseFiles': 'true',
            'WarnAsError': 'true',
            'WarningLevel': '1',
            'WholeProgramOptimization': 'true',
            'XMLDocumentationFileName': 'a_file_name',
            'ZZXYZ': 'bogus'},
         'VCLinkerTool': {
             'AdditionalDependencies': 'file1;file2',
             'AdditionalDependencies_excluded': 'file3',
             'AdditionalLibraryDirectories': 'folder1;folder2',
             'AdditionalManifestDependencies': 'file1;file2',
             'AdditionalOptions': 'a string1',
             'AddModuleNamesToAssembly': 'file1;file2',
             'AllowIsolation': 'true',
             'AssemblyDebug': '2',
             'AssemblyLinkResource': 'file1;file2',
             'BaseAddress': 'a string1',
             'CLRImageType': '2',
             'CLRThreadAttribute': '2',
             'CLRUnmanagedCodeCheck': 'true',
             'DataExecutionPrevention': '2',
             'DelayLoadDLLs': 'file1;file2',
             'DelaySign': 'true',
             'Driver': '2',
             'EmbedManagedResourceFile': 'file1;file2',
             'EnableCOMDATFolding': '2',
             'EnableUAC': 'true',
             'EntryPointSymbol': 'a string1',
             'ErrorReporting': '2',
             'FixedBaseAddress': '2',
             'ForceSymbolReferences': 'file1;file2',
             'FunctionOrder': 'a_file_name',
             'GenerateDebugInformation': 'true',
             'GenerateManifest': 'true',
             'GenerateMapFile': 'true',
             'HeapCommitSize': 'a string1',
             'HeapReserveSize': 'a string1',
             'IgnoreAllDefaultLibraries': 'true',
             'IgnoreDefaultLibraryNames': 'file1;file2',
             'IgnoreEmbeddedIDL': 'true',
             'IgnoreImportLibrary': 'true',
             'ImportLibrary': 'a_file_name',
             'KeyContainer': 'a_file_name',
             'KeyFile': 'a_file_name',
             'LargeAddressAware': '2',
             'LinkIncremental': '2',
             'LinkLibraryDependencies': 'true',
             'LinkTimeCodeGeneration': '2',
             'ManifestFile': 'a_file_name',
             'MapExports': 'true',
             'MapFileName': 'a_file_name',
             'MergedIDLBaseFileName': 'a_file_name',
             'MergeSections': 'a string1',
             'MidlCommandFile': 'a_file_name',
             'ModuleDefinitionFile': 'a_file_name',
             'OptimizeForWindows98': '1',
             'OptimizeReferences': '2',
             'OutputFile': 'a_file_name',
             'PerUserRedirection': 'true',
             'Profile': 'true',
             'ProfileGuidedDatabase': 'a_file_name',
             'ProgramDatabaseFile': 'a_file_name',
             'RandomizedBaseAddress': '2',
             'RegisterOutput': 'true',
             'ResourceOnlyDLL': 'true',
             'SetChecksum': 'true',
             'ShowProgress': '2',
             'StackCommitSize': 'a string1',
             'StackReserveSize': 'a string1',
             'StripPrivateSymbols': 'a_file_name',
             'SubSystem': '2',
             'SupportUnloadOfDelayLoadedDLL': 'true',
             'SuppressStartupBanner': 'true',
             'SwapRunFromCD': 'true',
             'SwapRunFromNet': 'true',
             'TargetMachine': '2',
             'TerminalServerAware': '2',
             'TurnOffAssemblyGeneration': 'true',
             'TypeLibraryFile': 'a_file_name',
             'TypeLibraryResourceID': '33',
             'UACExecutionLevel': '2',
             'UACUIAccess': 'true',
             'UseLibraryDependencyInputs': 'true',
             'UseUnicodeResponseFiles': 'true',
             'Version': 'a string1'},
         'VCMIDLTool': {
             'AdditionalIncludeDirectories': 'folder1;folder2',
             'AdditionalOptions': 'a string1',
             'CPreprocessOptions': 'a string1',
             'DefaultCharType': '1',
             'DLLDataFileName': 'a_file_name',
             'EnableErrorChecks': '1',
             'ErrorCheckAllocations': 'true',
             'ErrorCheckBounds': 'true',
             'ErrorCheckEnumRange': 'true',
             'ErrorCheckRefPointers': 'true',
             'ErrorCheckStubData': 'true',
             'GenerateStublessProxies': 'true',
             'GenerateTypeLibrary': 'true',
             'HeaderFileName': 'a_file_name',
             'IgnoreStandardIncludePath': 'true',
             'InterfaceIdentifierFileName': 'a_file_name',
             'MkTypLibCompatible': 'true',
             'notgood': 'bogus',
             'OutputDirectory': 'a string1',
             'PreprocessorDefinitions': 'string1;string2',
             'ProxyFileName': 'a_file_name',
             'RedirectOutputAndErrors': 'a_file_name',
             'StructMemberAlignment': '1',
             'SuppressStartupBanner': 'true',
             'TargetEnvironment': '1',
             'TypeLibraryName': 'a_file_name',
             'UndefinePreprocessorDefinitions': 'string1;string2',
             'ValidateParameters': 'true',
             'WarnAsError': 'true',
             'WarningLevel': '1'},
         'VCResourceCompilerTool': {
             'AdditionalOptions': 'a string1',
             'AdditionalIncludeDirectories': 'folder1;folder2',
             'Culture': '1003',
             'IgnoreStandardIncludePath': 'true',
             'notgood2': 'bogus',
             'PreprocessorDefinitions': 'string1;string2',
             'ResourceOutputFileName': 'a string1',
             'ShowProgress': 'true',
             'SuppressStartupBanner': 'true',
             'UndefinePreprocessorDefinitions': 'string1;string2'},
         'VCLibrarianTool': {
             'AdditionalDependencies': 'file1;file2',
             'AdditionalLibraryDirectories': 'folder1;folder2',
             'AdditionalOptions': 'a string1',
             'ExportNamedFunctions': 'string1;string2',
             'ForceSymbolReferences': 'a string1',
             'IgnoreAllDefaultLibraries': 'true',
             'IgnoreSpecificDefaultLibraries': 'file1;file2',
             'LinkLibraryDependencies': 'true',
             'ModuleDefinitionFile': 'a_file_name',
             'OutputFile': 'a_file_name',
             'SuppressStartupBanner': 'true',
             'UseUnicodeResponseFiles': 'true'},
         'VCManifestTool': {
             'AdditionalManifestFiles': 'file1;file2',
             'AdditionalOptions': 'a string1',
             'AssemblyIdentity': 'a string1',
             'ComponentFileName': 'a_file_name',
             'DependencyInformationFile': 'a_file_name',
             'GenerateCatalogFiles': 'true',
             'InputResourceManifests': 'a string1',
             'ManifestResourceFile': 'a_file_name',
             'OutputManifestFile': 'a_file_name',
             'RegistrarScriptFile': 'a_file_name',
             'ReplacementsFile': 'a_file_name',
             'SuppressStartupBanner': 'true',
             'TypeLibraryFile': 'a_file_name',
             'UpdateFileHashes': 'truel',
             'UpdateFileHashesSearchPath': 'a_file_name',
             'UseFAT32Workaround': 'true',
             'UseUnicodeResponseFiles': 'true',
             'VerboseOutput': 'true'}},
        self.stderr)
    self._ExpectedWarnings([
        'Warning: for VCCLCompilerTool/BasicRuntimeChecks, '
        'index value (5) not in expected range [0, 4)',
        'Warning: for VCCLCompilerTool/BrowseInformation, '
        "invalid literal for int() with base 10: 'fdkslj'",
        'Warning: for VCCLCompilerTool/CallingConvention, '
        'index value (-1) not in expected range [0, 4)',
        'Warning: for VCCLCompilerTool/DebugInformationFormat, '
        'converted value for 2 not specified.',
        'Warning: unrecognized setting VCCLCompilerTool/Enableprefast',
        'Warning: unrecognized setting VCCLCompilerTool/ZZXYZ',
        'Warning: for VCLinkerTool/TargetMachine, '
        'converted value for 2 not specified.',
        'Warning: unrecognized setting VCMIDLTool/notgood',
        'Warning: unrecognized setting VCResourceCompilerTool/notgood2',
        'Warning: for VCManifestTool/UpdateFileHashes, '
        "expected bool; got 'truel'"
        ''])

  def testValidateMSBuildSettings_settings(self):
    """Tests that for invalid MSBuild settings."""
    settings_fixture = {
      'ClCompile': {
        'AdditionalIncludeDirectories': 'folder1;folder2',
        'AdditionalOptions': ['string1', 'string2'],
        'AdditionalUsingDirectories': 'folder1;folder2',
        'AssemblerListingLocation': 'a_file_name',
        'AssemblerOutput': 'NoListing',
        'BasicRuntimeChecks': 'StackFrameRuntimeCheck',
        'BrowseInformation': 'false',
        'BrowseInformationFile': 'a_file_name',
        'BufferSecurityCheck': 'true',
        'BuildingInIDE': 'true',
        'CallingConvention': 'Cdecl',
        'CompileAs': 'CompileAsC',
        'CompileAsManaged': 'true',
        'CreateHotpatchableImage': 'true',
        'DebugInformationFormat': 'ProgramDatabase',
        'DisableLanguageExtensions': 'true',
        'DisableSpecificWarnings': 'string1;string2',
        'EnableEnhancedInstructionSet': 'StreamingSIMDExtensions',
        'EnableFiberSafeOptimizations': 'true',
        'EnablePREfast': 'true',
        'Enableprefast': 'bogus',
        'ErrorReporting': 'Prompt',
        'ExceptionHandling': 'SyncCThrow',
        'ExpandAttributedSource': 'true',
        'FavorSizeOrSpeed': 'Neither',
        'FloatingPointExceptions': 'true',
        'FloatingPointModel': 'Precise',
        'ForceConformanceInForLoopScope': 'true',
        'ForcedIncludeFiles': 'file1;file2',
        'ForcedUsingFiles': 'file1;file2',
        'FunctionLevelLinking': 'false',
        'GenerateXMLDocumentationFiles': 'true',
        'IgnoreStandardIncludePath': 'true',
        'InlineFunctionExpansion': 'OnlyExplicitInline',
        'IntrinsicFunctions': 'false',
        'MinimalRebuild': 'true',
        'MultiProcessorCompilation': 'true',
        'ObjectFileName': 'a_file_name',
        'OmitDefaultLibName': 'true',
        'OmitFramePointers': 'true',
        'OpenMPSupport': 'true',
        'Optimization': 'Disabled',
        'PrecompiledHeader': 'NotUsing',
        'PrecompiledHeaderFile': 'a_file_name',
        'PrecompiledHeaderOutputFile': 'a_file_name',
        'PreprocessKeepComments': 'true',
        'PreprocessorDefinitions': 'string1;string2',
        'PreprocessOutputPath': 'a string1',
        'PreprocessSuppressLineNumbers': 'false',
        'PreprocessToFile': 'false',
        'ProcessorNumber': '33',
        'ProgramDataBaseFileName': 'a_file_name',
        'RuntimeLibrary': 'MultiThreaded',
        'RuntimeTypeInfo': 'true',
        'ShowIncludes': 'true',
        'SmallerTypeCheck': 'true',
        'StringPooling': 'true',
        'StructMemberAlignment': '1Byte',
        'SuppressStartupBanner': 'true',
        'TrackerLogDirectory': 'a_folder',
        'TreatSpecificWarningsAsErrors': 'string1;string2',
        'TreatWarningAsError': 'true',
        'TreatWChar_tAsBuiltInType': 'true',
        'UndefineAllPreprocessorDefinitions': 'true',
        'UndefinePreprocessorDefinitions': 'string1;string2',
        'UseFullPaths': 'true',
        'UseUnicodeForAssemblerListing': 'true',
        'WarningLevel': 'TurnOffAllWarnings',
        'WholeProgramOptimization': 'true',
        'XMLDocumentationFileName': 'a_file_name',
        'ZZXYZ': 'bogus'
      },
      'Link': {
        'AdditionalDependencies': 'file1;file2',
        'AdditionalLibraryDirectories': 'folder1;folder2',
        'AdditionalManifestDependencies': 'file1;file2',
        'AdditionalOptions': 'a string1',
        'AddModuleNamesToAssembly': 'file1;file2',
        'AllowIsolation': 'true',
        'AssemblyDebug': '',
        'AssemblyLinkResource': 'file1;file2',