From c49c378861c7d7755a64bbd04116d5ef9322f34d Mon Sep 17 00:00:00 2001 From: John Mertic Date: Tue, 26 Apr 2011 14:19:08 -0400 Subject: [PATCH] Added unit tests. --- tests/ModuleInstall/Bug41829Test.php | 41 + tests/ModuleInstall/ModuleScannerTest.php | 80 + .../PackageManager/Bug39980Test.php | 101 + .../Extensions/Database/AbstractTester.php | 206 ++ .../Database/Constraint/DataSetIsEqual.php | 132 + .../Database/Constraint/TableIsEqual.php | 133 + .../Extensions/Database/DB/DataSet.php | 174 + .../Database/DB/DefaultDatabaseConnection.php | 232 ++ .../Database/DB/FilteredDataSet.php | 95 + .../Database/DB/IDatabaseConnection.php | 145 + .../Extensions/Database/DB/IMetaData.php | 114 + .../Extensions/Database/DB/MetaData.php | 215 ++ .../DB/MetaData/InformationSchema.php | 184 + .../Extensions/Database/DB/MetaData/MySQL.php | 137 + .../Extensions/Database/DB/MetaData/Oci.php | 164 + .../Extensions/Database/DB/MetaData/PgSQL.php | 164 + .../Database/DB/MetaData/Sqlite.php | 152 + .../Extensions/Database/DB/ResultSetTable.php | 92 + .../PHPUnit/Extensions/Database/DB/Table.php | 84 + .../Extensions/Database/DB/TableIterator.php | 176 + .../Extensions/Database/DB/TableMetaData.php | 75 + .../Database/DataSet/AbstractDataSet.php | 178 + .../Database/DataSet/AbstractTable.php | 218 ++ .../DataSet/AbstractTableMetaData.php | 136 + .../Database/DataSet/AbstractXmlDataSet.php | 150 + .../Database/DataSet/CompositeDataSet.php | 130 + .../Database/DataSet/CsvDataSet.php | 158 + .../Database/DataSet/DataSetFilter.php | 144 + .../Database/DataSet/DefaultDataSet.php | 109 + .../Database/DataSet/DefaultTable.php | 124 + .../Database/DataSet/DefaultTableIterator.php | 173 + .../Database/DataSet/DefaultTableMetaData.php | 91 + .../Database/DataSet/FlatXmlDataSet.php | 111 + .../Extensions/Database/DataSet/IDataSet.php | 104 + .../Database/DataSet/IPersistable.php | 77 + .../Extensions/Database/DataSet/ITable.php | 104 + .../Database/DataSet/ITableIterator.php | 81 + .../Database/DataSet/ITableMetaData.php | 95 + .../Database/DataSet/Persistors/Abstract.php | 137 + .../Database/DataSet/Persistors/FlatXml.php | 157 + .../Database/DataSet/Persistors/Xml.php | 161 + .../Database/DataSet/QueryDataSet.php | 142 + .../Database/DataSet/QueryTable.php | 172 + .../Database/DataSet/ReplacementDataSet.php | 140 + .../Database/DataSet/ReplacementTable.php | 250 ++ .../DataSet/ReplacementTableIterator.php | 197 + .../Database/DataSet/TableFilter.php | 107 + .../Database/DataSet/TableMetaDataFilter.php | 125 + .../Database/DataSet/XmlDataSet.php | 141 + .../Extensions/Database/DefaultTester.php | 95 + tests/PHPUnit/Extensions/Database/ITester.php | 128 + .../Database/Operation/Composite.php | 106 + .../Extensions/Database/Operation/Delete.php | 98 + .../Database/Operation/DeleteAll.php | 87 + .../Database/Operation/Exception.php | 137 + .../Extensions/Database/Operation/Factory.php | 157 + .../Database/Operation/IDatabaseOperation.php | 78 + .../Extensions/Database/Operation/Insert.php | 108 + .../Extensions/Database/Operation/Null.php | 74 + .../Extensions/Database/Operation/Replace.php | 148 + .../Database/Operation/RowBased.php | 125 + .../Database/Operation/Truncate.php | 96 + .../Extensions/Database/Operation/Update.php | 103 + .../PHPUnit/Extensions/Database/TestCase.php | 254 ++ tests/PHPUnit/Extensions/GroupTestSuite.php | 110 + tests/PHPUnit/Extensions/OutputTestCase.php | 195 + .../Extensions/PerformanceTestCase.php | 118 + tests/PHPUnit/Extensions/PhptTestCase.php | 271 ++ .../Extensions/PhptTestCase/Logger.php | 69 + tests/PHPUnit/Extensions/PhptTestSuite.php | 95 + tests/PHPUnit/Extensions/RepeatedTest.php | 153 + tests/PHPUnit/Extensions/SeleniumTestCase.php | 1317 +++++++ .../Extensions/SeleniumTestCase/Driver.php | 1048 ++++++ .../Extensions/SeleniumTestCase/append.php | 66 + .../SeleniumTestCase/phpunit_coverage.php | 86 + .../Extensions/SeleniumTestCase/prepend.php | 54 + tests/PHPUnit/Extensions/Story/Given.php | 79 + .../Extensions/Story/ResultPrinter.php | 110 + .../Extensions/Story/ResultPrinter/HTML.php | 209 ++ .../ResultPrinter/Template/scenario.html.dist | 13 + .../Template/scenario_header.html.dist | 6 + .../Template/scenarios.html.dist | 60 + .../ResultPrinter/Template/step.html.dist | 6 + .../Extensions/Story/ResultPrinter/Text.php | 158 + tests/PHPUnit/Extensions/Story/Scenario.php | 200 ++ .../Extensions/Story/SeleniumTestCase.php | 209 ++ tests/PHPUnit/Extensions/Story/Step.php | 135 + tests/PHPUnit/Extensions/Story/TestCase.php | 217 ++ tests/PHPUnit/Extensions/Story/Then.php | 79 + tests/PHPUnit/Extensions/Story/When.php | 79 + tests/PHPUnit/Extensions/TestDecorator.php | 158 + tests/PHPUnit/Framework.php | 72 + tests/PHPUnit/Framework/Assert.php | 2084 +++++++++++ .../Framework/AssertionFailedError.php | 102 + tests/PHPUnit/Framework/ComparisonFailure.php | 297 ++ .../Framework/ComparisonFailure/Array.php | 145 + .../Framework/ComparisonFailure/Object.php | 150 + .../Framework/ComparisonFailure/Scalar.php | 108 + .../Framework/ComparisonFailure/String.php | 120 + .../Framework/ComparisonFailure/Type.php | 82 + tests/PHPUnit/Framework/Constraint.php | 176 + tests/PHPUnit/Framework/Constraint/And.php | 141 + .../Framework/Constraint/ArrayHasKey.php | 112 + .../Framework/Constraint/Attribute.php | 121 + .../Constraint/ClassHasAttribute.php | 112 + .../Constraint/ClassHasStaticAttribute.php | 105 + .../Framework/Constraint/FileExists.php | 121 + .../Framework/Constraint/GreaterThan.php | 99 + .../Framework/Constraint/IsAnything.php | 101 + .../PHPUnit/Framework/Constraint/IsEqual.php | 332 ++ .../PHPUnit/Framework/Constraint/IsFalse.php | 88 + .../Framework/Constraint/IsIdentical.php | 138 + .../Framework/Constraint/IsInstanceOf.php | 131 + tests/PHPUnit/Framework/Constraint/IsNull.php | 88 + tests/PHPUnit/Framework/Constraint/IsTrue.php | 88 + tests/PHPUnit/Framework/Constraint/IsType.php | 178 + .../PHPUnit/Framework/Constraint/LessThan.php | 99 + tests/PHPUnit/Framework/Constraint/Not.php | 128 + .../Constraint/ObjectHasAttribute.php | 91 + tests/PHPUnit/Framework/Constraint/Or.php | 144 + .../Framework/Constraint/PCREMatch.php | 108 + .../Framework/Constraint/StringContains.php | 121 + .../Constraint/TraversableContains.php | 121 + .../Constraint/TraversableContainsOnly.php | 110 + tests/PHPUnit/Framework/Constraint/Xor.php | 149 + tests/PHPUnit/Framework/Error.php | 87 + tests/PHPUnit/Framework/Error/Notice.php | 76 + tests/PHPUnit/Framework/Error/Warning.php | 76 + .../Framework/ExpectationFailedException.php | 106 + tests/PHPUnit/Framework/IncompleteTest.php | 71 + .../PHPUnit/Framework/IncompleteTestError.php | 72 + .../Framework/MockObject/Builder/Identity.php | 80 + .../MockObject/Builder/InvocationMocker.php | 156 + .../Framework/MockObject/Builder/Match.php | 77 + .../MockObject/Builder/MethodNameMatch.php | 79 + .../MockObject/Builder/Namespace.php | 88 + .../MockObject/Builder/ParametersMatch.php | 100 + .../Framework/MockObject/Builder/Stub.php | 77 + .../Framework/MockObject/Invocation.php | 138 + .../Framework/MockObject/InvocationMocker.php | 165 + .../Framework/MockObject/Invokable.php | 91 + .../PHPUnit/Framework/MockObject/Matcher.php | 280 ++ .../MockObject/Matcher/AnyInvokedCount.php | 79 + .../MockObject/Matcher/AnyParameters.php | 79 + .../MockObject/Matcher/Invocation.php | 99 + .../MockObject/Matcher/InvokedAtIndex.php | 115 + .../MockObject/Matcher/InvokedAtLeastOnce.php | 87 + .../MockObject/Matcher/InvokedCount.php | 134 + .../MockObject/Matcher/InvokedRecorder.php | 100 + .../MockObject/Matcher/MethodName.php | 95 + .../MockObject/Matcher/Parameters.php | 145 + .../Matcher/StatelessInvocation.php | 81 + tests/PHPUnit/Framework/MockObject/Mock.php | 445 +++ .../Framework/MockObject/MockObject.php | 88 + tests/PHPUnit/Framework/MockObject/Stub.php | 90 + .../MockObject/Stub/ConsecutiveCalls.php | 97 + .../Framework/MockObject/Stub/Exception.php | 90 + .../MockObject/Stub/MatcherCollection.php | 76 + .../Framework/MockObject/Stub/Return.php | 90 + .../MockObject/Stub/ReturnArgument.php | 87 + .../MockObject/Stub/ReturnCallback.php | 102 + .../Framework/MockObject/Verifiable.php | 75 + tests/PHPUnit/Framework/SelfDescribing.php | 76 + tests/PHPUnit/Framework/SkippedTest.php | 70 + tests/PHPUnit/Framework/SkippedTestError.php | 72 + .../Framework/SkippedTestSuiteError.php | 72 + tests/PHPUnit/Framework/Test.php | 78 + tests/PHPUnit/Framework/TestCase.php | 1043 ++++++ tests/PHPUnit/Framework/TestFailure.php | 251 ++ tests/PHPUnit/Framework/TestListener.php | 138 + tests/PHPUnit/Framework/TestResult.php | 729 ++++ tests/PHPUnit/Framework/TestSuite.php | 855 +++++ tests/PHPUnit/Framework/Warning.php | 100 + tests/PHPUnit/Runner/BaseTestRunner.php | 304 ++ .../Runner/IncludePathTestCollector.php | 160 + .../Runner/StandardTestSuiteLoader.php | 166 + tests/PHPUnit/Runner/TestCollector.php | 71 + tests/PHPUnit/Runner/TestSuiteLoader.php | 78 + tests/PHPUnit/Runner/Version.php | 83 + .../Samples/BankAccount/BankAccount.php | 121 + .../Samples/BankAccount/BankAccountTest.php | 138 + .../Samples/BankAccountDB/BankAccount.php | 210 ++ .../BankAccountDB/BankAccountDBTest.php | 150 + .../BankAccountDB/BankAccountDBTestMySQL.php | 150 + .../_files/bank-account-after-deposits.xml | 6 + .../_files/bank-account-after-new-account.xml | 7 + .../_files/bank-account-after-withdrawals.xml | 6 + .../_files/bank-account-seed.xml | 6 + .../Samples/BowlingGame/BowlingGame.php | 107 + .../Samples/BowlingGame/BowlingGameSpec.php | 183 + .../Samples/BowlingGame/BowlingGameTest.php | 110 + tests/PHPUnit/Samples/FailureTest.php | 114 + tests/PHPUnit/Samples/Money/IMoney.php | 73 + tests/PHPUnit/Samples/Money/Money.php | 151 + tests/PHPUnit/Samples/Money/MoneyBag.php | 250 ++ tests/PHPUnit/Samples/Money/MoneyTest.php | 248 ++ tests/PHPUnit/Tests/AllTests.php | 91 + tests/PHPUnit/Tests/Extensions/AllTests.php | 88 + .../Tests/Extensions/Database/AllTests.php | 84 + .../Extensions/Database/DataSet/AllTests.php | 96 + .../Database/DataSet/CompositeDataSetTest.php | 174 + .../Database/DataSet/CsvDataSetTest.php | 134 + .../Database/DataSet/FilterTest.php | 89 + .../Database/DataSet/PersistorTest.php | 116 + .../Database/DataSet/QueryDataSetTest.php | 144 + .../Database/DataSet/QueryTableTest.php | 144 + .../DataSet/ReplacementDataSetTest.php | 330 ++ .../Database/DataSet/ReplacementTableTest.php | 265 ++ .../Database/DataSet/XmlDataSetsTest.php | 144 + .../Database/Operation/AllTests.php | 82 + .../Database/Operation/OperationsTest.php | 195 + .../Database/Operation/RowBasedTest.php | 187 + .../Database/_files/CsvDataSets/table1.csv | 4 + .../Database/_files/CsvDataSets/table2.csv | 5 + .../Database/_files/DatabaseTestUtility.php | 116 + .../XmlDataSets/AllEmptyTableInsertResult.xml | 9 + .../XmlDataSets/AllEmptyTableInsertTest.xml | 4 + .../XmlDataSets/DeleteAllOperationTest.xml | 6 + .../XmlDataSets/DeleteOperationResult.xml | 7 + .../XmlDataSets/DeleteOperationTest.xml | 5 + .../XmlDataSets/EmptyTableInsertResult.xml | 11 + .../XmlDataSets/EmptyTableInsertTest.xml | 6 + .../XmlDataSets/FilteredTestComparison.xml | 9 + .../XmlDataSets/FilteredTestFixture.xml | 8 + .../_files/XmlDataSets/FlatXmlDataSet.xml | 9 + .../_files/XmlDataSets/FlatXmlWriter.xml | 32 + .../XmlDataSets/InsertOperationResult.xml | 12 + .../XmlDataSets/InsertOperationTest.xml | 6 + .../XmlDataSets/OperationsTestFixture.xml | 9 + .../_files/XmlDataSets/QueryDataSetTest.xml | 31 + .../XmlDataSets/ReplaceOperationResult.xml | 12 + .../XmlDataSets/ReplaceOperationTest.xml | 9 + .../_files/XmlDataSets/RowBasedExecute.xml | 6 + .../XmlDataSets/UpdateOperationResult.xml | 9 + .../XmlDataSets/UpdateOperationTest.xml | 6 + .../_files/XmlDataSets/XmlDataSet.xml | 65 + .../Database/_files/XmlDataSets/XmlWriter.xml | 28 + .../Tests/Extensions/OutputTestCaseTest.php | 101 + .../Extensions/PerformanceTestCaseTest.php | 85 + .../Tests/Extensions/RepeatedTestTest.php | 118 + .../Tests/Extensions/SeleniumTestCaseTest.php | 659 ++++ tests/PHPUnit/Tests/Framework/AllTests.php | 96 + tests/PHPUnit/Tests/Framework/AssertTest.php | 3161 +++++++++++++++++ .../Tests/Framework/ComparisonFailureTest.php | 144 + .../Tests/Framework/ConstraintTest.php | 1253 +++++++ .../Tests/Framework/MockObjectTest.php | 251 ++ tests/PHPUnit/Tests/Framework/SuiteTest.php | 198 ++ .../PHPUnit/Tests/Framework/TestCaseTest.php | 297 ++ .../Tests/Framework/TestFailureTest.php | 1090 ++++++ .../Tests/Framework/TestImplementorTest.php | 87 + .../Tests/Framework/TestListenerTest.php | 154 + tests/PHPUnit/Tests/Regression/578.phpt | 36 + tests/PHPUnit/Tests/Regression/684.phpt | 25 + .../PHPUnit/Tests/Regression/Issue578Test.php | 22 + .../PHPUnit/Tests/Regression/Issue684Test.php | 4 + tests/PHPUnit/Tests/Runner/AllTests.php | 80 + .../Tests/Runner/BaseTestRunnerTest.php | 72 + .../Tests/TextUI/abstract-test-class.phpt | 26 + .../Tests/TextUI/concrete-test-class.phpt | 19 + .../coverage-clover-class-extended.phpt | 55 + .../Tests/TextUI/coverage-clover-class.phpt | 55 + .../Tests/TextUI/coverage-clover-method.phpt | 55 + .../TextUI/coverage-clover-not-private.phpt | 55 + .../TextUI/coverage-clover-not-protected.phpt | 55 + .../TextUI/coverage-clover-not-public.phpt | 55 + .../Tests/TextUI/coverage-clover-private.phpt | 55 + .../TextUI/coverage-clover-protected.phpt | 55 + .../Tests/TextUI/coverage-clover-public.phpt | 55 + .../PHPUnit/Tests/TextUI/coverage-clover.phpt | 50 + .../PHPUnit/Tests/TextUI/coverage-source.phpt | 842 +++++ .../PHPUnit/Tests/TextUI/dataset-log-xml.phpt | 47 + tests/PHPUnit/Tests/TextUI/debug.phpt | 25 + tests/PHPUnit/Tests/TextUI/default.phpt | 18 + tests/PHPUnit/Tests/TextUI/exclude-group.phpt | 20 + tests/PHPUnit/Tests/TextUI/filter-class.phpt | 20 + tests/PHPUnit/Tests/TextUI/filter-method.phpt | 20 + tests/PHPUnit/Tests/TextUI/group.phpt | 20 + tests/PHPUnit/Tests/TextUI/help.phpt | 63 + tests/PHPUnit/Tests/TextUI/help2.phpt | 65 + tests/PHPUnit/Tests/TextUI/list-groups.phpt | 18 + tests/PHPUnit/Tests/TextUI/log-graphviz.phpt | 35 + tests/PHPUnit/Tests/TextUI/log-json.phpt | 20 + tests/PHPUnit/Tests/TextUI/log-tap.phpt | 25 + tests/PHPUnit/Tests/TextUI/log-xml.phpt | 28 + tests/PHPUnit/Tests/TextUI/repeat.phpt | 21 + tests/PHPUnit/Tests/TextUI/skeleton.phpt | 18 + tests/PHPUnit/Tests/TextUI/story.phpt | 79 + tests/PHPUnit/Tests/TextUI/tap.phpt | 17 + tests/PHPUnit/Tests/TextUI/testdox-html.phpt | 20 + tests/PHPUnit/Tests/TextUI/testdox-text.phpt | 24 + tests/PHPUnit/Tests/TextUI/testdox.phpt | 18 + tests/PHPUnit/Tests/TextUI/verbose.phpt | 20 + tests/PHPUnit/Tests/Util/AllTests.php | 86 + .../PHPUnit/Tests/Util/ConfigurationTest.php | 324 ++ tests/PHPUnit/Tests/Util/TestDox/AllTests.php | 80 + .../Tests/Util/TestDox/NamePrettifierTest.php | 108 + tests/PHPUnit/Tests/Util/TestTest.php | 102 + tests/PHPUnit/Tests/Util/TimerTest.php | 78 + tests/PHPUnit/Tests/Util/XMLTest.php | 332 ++ tests/PHPUnit/Tests/_files/AbstractTest.php | 7 + tests/PHPUnit/Tests/_files/AnInterface.php | 6 + tests/PHPUnit/Tests/_files/Calculator.php | 15 + .../_files/ClassWithNonPublicAttributes.php | 30 + tests/PHPUnit/Tests/_files/ConcreteTest.php | 9 + .../_files/CoverageClassExtendedTest.php | 14 + .../Tests/_files/CoverageClassTest.php | 14 + .../Tests/_files/CoverageMethodTest.php | 14 + .../Tests/_files/CoverageNotPrivateTest.php | 14 + .../Tests/_files/CoverageNotProtectedTest.php | 14 + .../Tests/_files/CoverageNotPublicTest.php | 14 + .../Tests/_files/CoveragePrivateTest.php | 14 + .../Tests/_files/CoverageProtectedTest.php | 14 + .../Tests/_files/CoveragePublicTest.php | 14 + tests/PHPUnit/Tests/_files/CoveredClass.php | 37 + tests/PHPUnit/Tests/_files/DataSetTest.php | 21 + tests/PHPUnit/Tests/_files/DoubleTestCase.php | 26 + tests/PHPUnit/Tests/_files/Error.php | 9 + tests/PHPUnit/Tests/_files/Failure.php | 9 + .../PHPUnit/Tests/_files/FunctionCallback.php | 10 + .../Tests/_files/InheritedTestCase.php | 10 + tests/PHPUnit/Tests/_files/MethodCallback.php | 22 + tests/PHPUnit/Tests/_files/MockRunner.php | 22 + .../Tests/_files/NoArgTestCaseTest.php | 8 + .../PHPUnit/Tests/_files/NoTestCaseClass.php | 5 + tests/PHPUnit/Tests/_files/NoTestCases.php | 8 + tests/PHPUnit/Tests/_files/NonStatic.php | 9 + .../Tests/_files/NotPublicTestCase.php | 12 + .../PHPUnit/Tests/_files/NotVoidTestCase.php | 5 + tests/PHPUnit/Tests/_files/OneTestCase.php | 12 + tests/PHPUnit/Tests/_files/OutputTestCase.php | 30 + .../PHPUnit/Tests/_files/OverrideTestCase.php | 10 + .../Tests/_files/PartialMockTestClass.php | 12 + tests/PHPUnit/Tests/_files/SampleClass.php | 15 + .../_files/SelectorAssertionsFixture.html | 41 + tests/PHPUnit/Tests/_files/SetupFailure.php | 11 + tests/PHPUnit/Tests/_files/SleepTest.php | 11 + tests/PHPUnit/Tests/_files/Struct.php | 11 + tests/PHPUnit/Tests/_files/Success.php | 8 + .../PHPUnit/Tests/_files/TearDownFailure.php | 11 + tests/PHPUnit/Tests/_files/TestIterator.php | 37 + .../Tests/_files/ThrowExceptionTestCase.php | 9 + .../Tests/_files/ThrowNoExceptionTestCase.php | 8 + tests/PHPUnit/Tests/_files/TornDown.php | 16 + tests/PHPUnit/Tests/_files/TornDown2.php | 17 + tests/PHPUnit/Tests/_files/TornDown3.php | 11 + tests/PHPUnit/Tests/_files/TornDown4.php | 11 + tests/PHPUnit/Tests/_files/TornDown5.php | 11 + tests/PHPUnit/Tests/_files/WasRun.php | 11 + tests/PHPUnit/Tests/_files/bar.xml | 1 + tests/PHPUnit/Tests/_files/configuration.xml | 101 + tests/PHPUnit/Tests/_files/foo.xml | 1 + ...uctureAttributesAreSameButValuesAreNot.xml | 10 + .../Tests/_files/structureExpected.xml | 10 + .../Tests/_files/structureIgnoreTextNodes.xml | 13 + .../_files/structureIsSameButDataIsNot.xml | 10 + .../structureWrongNumberOfAttributes.xml | 10 + .../_files/structureWrongNumberOfNodes.xml | 9 + tests/PHPUnit/Tests/phpunit.xml.dist | 23 + tests/PHPUnit/TextUI/Command.php | 731 ++++ tests/PHPUnit/TextUI/ResultPrinter.php | 626 ++++ tests/PHPUnit/TextUI/TestRunner.php | 784 ++++ tests/PHPUnit/Util/Class.php | 472 +++ tests/PHPUnit/Util/CodeCoverage.php | 332 ++ tests/PHPUnit/Util/Configuration.php | 636 ++++ tests/PHPUnit/Util/ErrorHandler.php | 130 + tests/PHPUnit/Util/Fileloader.php | 203 ++ tests/PHPUnit/Util/Filesystem.php | 313 ++ tests/PHPUnit/Util/Filter.php | 561 +++ tests/PHPUnit/Util/FilterIterator.php | 89 + tests/PHPUnit/Util/Getopt.php | 183 + tests/PHPUnit/Util/Log/CPD.php | 134 + .../Util/Log/CodeCoverage/Database.php | 594 ++++ .../Util/Log/CodeCoverage/XML/Clover.php | 328 ++ .../Util/Log/CodeCoverage/XML/Source.php | 304 ++ tests/PHPUnit/Util/Log/Database.php | 516 +++ tests/PHPUnit/Util/Log/Database/MySQL.sql | 206 ++ tests/PHPUnit/Util/Log/Database/SQLite3.sql | 206 ++ tests/PHPUnit/Util/Log/GraphViz.php | 301 ++ tests/PHPUnit/Util/Log/JSON.php | 282 ++ tests/PHPUnit/Util/Log/Metrics.php | 182 + tests/PHPUnit/Util/Log/PEAR.php | 245 ++ tests/PHPUnit/Util/Log/PMD.php | 337 ++ tests/PHPUnit/Util/Log/PMD/Rule.php | 89 + tests/PHPUnit/Util/Log/PMD/Rule/Class.php | 67 + .../PMD/Rule/Class/DepthOfInheritanceTree.php | 83 + .../Log/PMD/Rule/Class/EfferentCoupling.php | 86 + .../PMD/Rule/Class/ExcessiveClassLength.php | 86 + .../PMD/Rule/Class/ExcessivePublicCount.php | 87 + .../Util/Log/PMD/Rule/Class/TooManyFields.php | 88 + tests/PHPUnit/Util/Log/PMD/Rule/File.php | 67 + tests/PHPUnit/Util/Log/PMD/Rule/Function.php | 68 + .../Util/Log/PMD/Rule/Function/CRAP.php | 88 + .../Log/PMD/Rule/Function/CodeCoverage.php | 91 + .../Rule/Function/CyclomaticComplexity.php | 89 + .../Rule/Function/ExcessiveMethodLength.php | 86 + .../Rule/Function/ExcessiveParameterList.php | 86 + .../Log/PMD/Rule/Function/NPathComplexity.php | 87 + tests/PHPUnit/Util/Log/PMD/Rule/Project.php | 67 + .../Util/Log/PMD/Rule/Project/CRAP.php | 110 + tests/PHPUnit/Util/Log/TAP.php | 231 ++ tests/PHPUnit/Util/Log/XML.php | 477 +++ tests/PHPUnit/Util/Metrics.php | 71 + tests/PHPUnit/Util/Metrics/Class.php | 731 ++++ tests/PHPUnit/Util/Metrics/File.php | 328 ++ tests/PHPUnit/Util/Metrics/Function.php | 504 +++ tests/PHPUnit/Util/Metrics/Project.php | 476 +++ tests/PHPUnit/Util/PDO.php | 357 ++ tests/PHPUnit/Util/Printer.php | 211 ++ tests/PHPUnit/Util/Report.php | 246 ++ tests/PHPUnit/Util/Report/Node.php | 489 +++ tests/PHPUnit/Util/Report/Node/Directory.php | 394 ++ tests/PHPUnit/Util/Report/Node/File.php | 874 +++++ tests/PHPUnit/Util/Report/Template/butter.png | Bin 0 -> 150 bytes .../Util/Report/Template/chameleon.png | Bin 0 -> 150 bytes .../Util/Report/Template/close12_1.gif | Bin 0 -> 85 bytes .../Util/Report/Template/container-min.js | 19 + .../Util/Report/Template/container.css | 325 ++ .../Util/Report/Template/directory.html.dist | 71 + .../Report/Template/directory_item.html.dist | 31 + .../Util/Report/Template/file.html.dist | 120 + .../Util/Report/Template/file_item.html.dist | 31 + .../Report/Template/file_no_yui.html.dist | 79 + tests/PHPUnit/Util/Report/Template/glass.png | Bin 0 -> 167 bytes .../Report/Template/method_item.html.dist | 22 + .../Util/Report/Template/scarlet_red.png | Bin 0 -> 150 bytes tests/PHPUnit/Util/Report/Template/snow.png | Bin 0 -> 141 bytes tests/PHPUnit/Util/Report/Template/style.css | 450 +++ .../Util/Report/Template/yahoo-dom-event.js | 12 + .../PHPUnit/Util/Report/Template/yui_item.js | 5 + tests/PHPUnit/Util/Skeleton.php | 121 + tests/PHPUnit/Util/Skeleton/Class.php | 257 ++ .../Util/Skeleton/Template/Class.tpl.dist | 7 + .../Template/IncompleteTestMethod.tpl.dist | 11 + .../Util/Skeleton/Template/Method.tpl.dist | 9 + .../Util/Skeleton/Template/TestClass.tpl.dist | 37 + .../Skeleton/Template/TestMethod.tpl.dist | 11 + .../Skeleton/Template/TestMethodBool.tpl.dist | 10 + .../Template/TestMethodBoolStatic.tpl.dist | 10 + .../Template/TestMethodException.tpl.dist | 9 + .../TestMethodExceptionStatic.tpl.dist | 9 + .../Template/TestMethodStatic.tpl.dist | 11 + tests/PHPUnit/Util/Skeleton/Test.php | 348 ++ tests/PHPUnit/Util/Template.php | 179 + tests/PHPUnit/Util/Test.php | 371 ++ tests/PHPUnit/Util/TestDox/NamePrettifier.php | 180 + tests/PHPUnit/Util/TestDox/ResultPrinter.php | 324 ++ .../Util/TestDox/ResultPrinter/HTML.php | 128 + .../Util/TestDox/ResultPrinter/Text.php | 103 + tests/PHPUnit/Util/TestSuiteIterator.php | 153 + tests/PHPUnit/Util/Timer.php | 128 + tests/PHPUnit/Util/Type.php | 197 + tests/PHPUnit/Util/XML.php | 784 ++++ tests/SugarTestAccountUtilities.php | 51 + tests/SugarTestCampaignUtilities.php | 44 + tests/SugarTestContactUtilities.php | 58 + tests/SugarTestEmailUtilities.php | 67 + tests/SugarTestHelper.php | 103 + tests/SugarTestImportUtilities.php | 62 + tests/SugarTestLangPackCreator.php | 127 + tests/SugarTestLeadUtilities.php | 58 + tests/SugarTestMeetingUtilities.php | 46 + tests/SugarTestMergeUtilities.php | 68 + tests/SugarTestStudioUtilities.php | 47 + tests/SugarTestThemeUtilities.php | 158 + tests/SugarTestTrackerUtility.php | 77 + tests/SugarTestUserUtilities.php | 58 + tests/codecoverage.xml | 34 + tests/data/Bug39780Test.php | 35 + tests/data/Bug40739Test.php | 28 + tests/data/fixUpFormatting.php | 111 + tests/expressions/expression_engine_eval.php | 61 + tests/expressions/expression_engine_test.html | 219 ++ tests/include/Dashlets/Bug41013Test.php | 56 + .../Dashlets/DashletLoadLanguageTest.php | 111 + .../Expressions/Actions/ActionFactory.php | 105 + .../Expressions/Expression/Parser/Parser.php | 68 + tests/include/JSONTest.php | 27 + .../include/Localization/LocalizationTest.php | 211 ++ .../MVC/Controller/SugarControllerTest.php | 180 + tests/include/MVC/SugarApplicationTest.php | 142 + tests/include/MVC/SugarModuleTest.php | 49 + tests/include/MVC/View/Bug40019Test.php | 71 + tests/include/MVC/View/LoadMenuTest.php | 223 ++ tests/include/MassUpdateTest.php | 72 + tests/include/OutboundEmail/Bug23140Test.php | 207 ++ tests/include/OutboundEmail/Bug32487Test.php | 59 + tests/include/Popup/Bug36329Test.php | 100 + tests/include/SearchForm/SugarSpotTest.php | 55 + .../plugins/FunctionMultienumToArrayTest.php | 55 + .../Smarty/plugins/FunctionSugarHelpTest.php | 45 + .../Smarty/plugins/FunctionSugarLinkTest.php | 82 + .../plugins/FunctionSugarTranslateTest.php | 59 + tests/include/SubPanel/Bug40171Test.php | 136 + tests/include/SubPanel/Bug41738Test.php | 106 + .../include/SubPanel/GetUnionRelatedTest.php | 79 + .../SugarEmailAddress/Bug40068Test.php | 39 + .../SugarEmailAddressRegexTest.php | 32 + .../Fields/Enum/SugarFieldEnumTest.php | 39 + .../Fields/Relate/SugarFieldRelateTest.php | 132 + tests/include/SugarFolders/Bug33404Test.php | 74 + tests/include/SugarFolders/Bug33906Test.php | 54 + .../include/SugarFolders/SugarFoldersTest.php | 312 ++ tests/include/SugarLogger/SugarLoggerTest.php | 71 + .../SugarObjects/BasicTemplateTest.php | 70 + .../SugarObjects/PersonTemplateTest.php | 46 + .../include/SugarObjects/SugarConfigTest.php | 213 ++ .../SugarObjects/SugarRegistryTest.php | 91 + .../SugarTheme/SugarThemeRegistryTest.php | 129 + tests/include/SugarTheme/SugarThemeTest.php | 395 ++ tests/include/TimeDateTest.php | 783 ++++ .../connectors/ConnectorsTestUtility.php | 33 + tests/include/database/DBHelperTest.php | 614 ++++ .../include/database/DBManagerFactoryTest.php | 112 + tests/include/database/DBManagerTest.php | 1375 +++++++ tests/include/database/FreeTDSManagerTest.php | 28 + tests/include/javascript/JSAlertsTest.php | 70 + tests/include/javascript/JavascriptTest.php | 36 + tests/include/utils/Bug22882Test.php | 303 ++ tests/include/utils/Bug33284_Test.php | 52 + tests/include/utils/Bug42427Test.php | 44 + tests/include/utils/CheckPhpVersionTest.php | 32 + tests/include/utils/CheckPlatformTest.php | 16 + .../utils/CreateCacheDirectoryTest.php | 64 + tests/include/utils/DbUtilsTest.php | 61 + tests/include/utils/DeepArrayDiffTest.php | 36 + tests/include/utils/ExternalCacheAPITest.php | 69 + .../utils/SugarArrayMergeRecursiveTest.php | 82 + tests/include/utils/SugarArrayMergeTest.php | 72 + tests/include/utils/SugarArrayTest.php | 72 + tests/include/utils/SugarFileUtilsTest.php | 160 + tests/include/utils/SugarVersionTest.php | 55 + tests/include/utils/XssTest.php | 45 + tests/include/vCard/ISO88591SampleFile.vcf | 15 + tests/include/vCard/SimpleVCard.vcf | 13 + tests/include/vCard/UTF8SampleFile.vcf | 15 + tests/include/vCard/vCardBug40629Test.php | 45 + tests/include/vCard/vCardTest.php | 77 + .../workflow/testfiles/logic_hooks.php | 12 + .../testfiles/workflow/actions_array.php | 55 + .../testfiles/workflow/alerts_array.php | 9 + .../testfiles/workflow/plugins_array.php | 9 + .../testfiles/workflow/triggers_array.php | 9 + .../workflow/testfiles/workflow/workflow.php | 74 + tests/install/QuotesSeedDataTest.php | 97 + tests/modules/Administration/Bug36978Test.php | 264 ++ .../Administration/UpgradeHistoryTest.php | 26 + tests/modules/Calendar/Bug20626Test.php | 42 + tests/modules/Calls/Bug39161Test.php | 17 + tests/modules/Calls/CallHelperTest.php | 236 ++ tests/modules/CampaignLog/CampaignLogTest.php | 194 + .../CampaignTrackers/CampaignTrackersTest.php | 83 + tests/modules/Campaigns/Bug35014Test.php | 162 + tests/modules/Campaigns/Bug40233Test.php | 269 ++ .../modules/Configurator/ConfiguratorTest.php | 24 + tests/modules/Contacts/Bug15255Test.php | 65 + tests/modules/Contacts/Bug7825Test.php | 24 + tests/modules/DynamicFields/Bug24095Test.php | 61 + tests/modules/DynamicFields/Bug39766Test.php | 20 + .../DynamicFields/RepairCustomFieldsTest.php | 122 + tests/modules/DynamicFields/URLFieldTest.php | 47 + .../EmailAddresses/EmailAddressTest.php | 61 + tests/modules/Emails/Bug32489Test.php | 107 + tests/modules/Emails/Bug40527Test.php | 40 + tests/modules/Emails/ComposePackageTest.php | 73 + tests/modules/Emails/EmailTest.php | 88 + tests/modules/Emails/EmailUITest.php | 108 + .../Emails/FindEmailFromBeanIdsTest.php | 45 + .../Emails/HandleBodyInHTMLformatTest.php | 45 + tests/modules/Home/QuickSearchTests.php | 48 + .../Home/UnifiedSearchAdvancedTest.php | 66 + tests/modules/Import/Bug39494ImportFile.txt | 2 + tests/modules/Import/ImportCacheFilesTest.php | 50 + .../Import/ImportDuplicateCheckTest.php | 117 + .../Import/ImportFieldSanitizeTest.php | 1183 ++++++ .../modules/Import/ImportFileSplitterTest.php | 98 + tests/modules/Import/ImportFileTest.php | 263 ++ tests/modules/Import/ImportFormsTest.php | 177 + tests/modules/Import/ImportMapTest.php | 281 ++ tests/modules/Import/UsersLastImportTest.php | 173 + .../AutoCreateImportFolderTest.php | 52 + .../modules/InboundEmail/InboundEmailTest.php | 162 + tests/modules/Leads/ConvertLeadTests.php | 63 + .../ModuleBuilder/Module/StudioModuleTest.php | 39 + .../parsers/AbstractMetaDataParserTest.php | 58 + .../ModuleBuilder/views/ViewListVIewTest.php | 38 + tests/modules/MySettings/StoreQueryTest.php | 20 + tests/modules/Notes/NotesTest.php | 41 + tests/modules/Tasks/TasksTest.php | 29 + tests/modules/Trackers/Bug40019_Test.php | 110 + .../Trackers/TrackerCreateDefaultUserTest.php | 100 + tests/modules/Trackers/TrackerManagerTest.php | 61 + tests/modules/Trackers/TrackerMetricsTest.php | 31 + tests/modules/Trackers/TrackerMonitorTest.php | 49 + .../Trackers/TrackerReportsUsageTest.php | 88 + tests/modules/Trackers/TrackerSaveTest.php | 16 + tests/modules/Trackers/TrackerTestUtility.php | 29 + .../Trackers/TrackerUpgradeDashletTest.php | 95 + tests/modules/UpgradeWizard/Bug30709Test.php | 171 + .../UpgradeWizard/Bug30709_Part_2_Test.php | 150 + tests/modules/UpgradeWizard/Bug32003_Test.php | 592 +++ tests/modules/UpgradeWizard/Bug32382Test.php | 166 + tests/modules/UpgradeWizard/Bug42643Test.php | 46 + .../SilentUpgradeSessionVarsTest.php | 76 + .../UpgradeWizard/SugarMerge/Bug36257Test.php | 98 + .../UpgradeWizard/SugarMerge/Bug36481Test.php | 67 + .../UpgradeWizard/SugarMerge/Bug37231Test.php | 245 ++ .../UpgradeWizard/SugarMerge/Bug37295Test.php | 131 + .../UpgradeWizard/SugarMerge/Bug37461Test.php | 139 + .../UpgradeWizard/SugarMerge/Bug37597Test.php | 139 + .../UpgradeWizard/SugarMerge/Bug37692Test.php | 82 + .../UpgradeWizard/SugarMerge/Bug37704Test.php | 118 + .../UpgradeWizard/SugarMerge/Bug37725Test.php | 120 + .../UpgradeWizard/SugarMerge/Bug37841Test.php | 147 + .../UpgradeWizard/SugarMerge/Bug37850Test.php | 66 + .../UpgradeWizard/SugarMerge/Bug37862Test.php | 127 + .../UpgradeWizard/SugarMerge/Bug37917Test.php | 48 + .../UpgradeWizard/SugarMerge/Bug37921Test.php | 48 + .../UpgradeWizard/SugarMerge/Bug39057Test.php | 57 + .../UpgradeWizard/SugarMerge/Bug39059Test.php | 38 + .../SugarMerge/LeadsMergeTest.php | 169 + .../Contacts/metadata/detailviewdefs.php | 216 ++ .../Contacts/metadata/editviewdefs.php | 220 ++ .../Contacts/metadata/listviewdefs.php | 169 + .../modules/Contacts/metadata/popupdefs.php | 93 + .../Contacts/metadata/quickcreatedefs.php | 147 + .../modules/Contacts/metadata/searchdefs.php | 153 + .../Contacts/metadata/detailviewdefs.php | 234 ++ .../Contacts/metadata/editviewdefs.php | 231 ++ .../Contacts/metadata/listviewdefs.php | 223 ++ .../modules/Contacts/metadata/popupdefs.php | 173 + .../Contacts/metadata/quickcreatedefs.php | 124 + .../modules/Contacts/metadata/searchdefs.php | 160 + .../modules/Leads/metadata/detailviewdefs.php | 184 + .../modules/Leads/metadata/detailviewdefs.php | 194 + .../Quotes/metadata/detailviewdefs.php | 138 + .../Contacts/metadata/editviewdefs.php | 184 + .../Contacts/metadata/editviewdefs.php | 146 + .../modules/Contacts/metadata/searchdefs.php | 66 + .../modules/Leads/metadata/detailviewdefs.php | 220 ++ .../modules/Leads/metadata/editviewdefs.php | 155 + .../551/modules/Notes/metadata/searchdefs.php | 59 + .../Contacts/metadata/editviewdefs.php | 286 ++ .../modules/Leads/metadata/detailviewdefs.php | 175 + .../modules/Leads/metadata/editviewdefs.php | 155 + .../Quotes/metadata/detailviewdefs.php | 208 ++ .../Meetings/metadata/detailviewdefs.php | 107 + .../modules/Leads/metadata/detailviewdefs.php | 194 + .../Opportunities/metadata/listviewdefs.php | 76 + .../Accounts/metadata/detailviewdefs.php | 199 ++ .../Accounts/metadata/detailviewdefs.php | 206 ++ .../Accounts/metadata/detailviewdefs.php | 167 + .../Accounts/metadata/listviewdefs.php | 150 + .../Contacts/metadata/editviewdefs.php | 270 ++ .../modules/Contacts/metadata/searchdefs.php | 170 + .../modules/Leads/metadata/detailviewdefs.php | 223 ++ .../Meetings/metadata/detailviewdefs.php | 128 + .../modules/Notes/metadata/searchdefs.php | 77 + .../Opportunities/metadata/listviewdefs.php | 165 + .../Project/metadata/detailviewdefs.php | 123 + .../modules/Project/metadata/editviewdefs.php | 108 + .../Accounts/metadata/detailviewdefs.php | 84 + .../Accounts/metadata/editviewdefs.php | 135 + .../Accounts/metadata/listviewdefs.php | 133 + .../modules/Accounts/metadata/searchdefs.php | 78 + .../Contacts/metadata/detailviewdefs.php | 171 + .../Contacts/metadata/editviewdefs.php | 145 + .../Opportunities/metadata/detailviewdefs.php | 65 + .../Opportunities/metadata/editviewdefs.php | 90 + .../Opportunities/metadata/searchdefs.php | 63 + .../Accounts/metadata/detailviewdefs.php | 428 +++ .../Accounts/metadata/editviewdefs.php | 426 +++ .../Accounts/metadata/listviewdefs.php | 180 + .../modules/Accounts/metadata/searchdefs.php | 209 ++ .../Contacts/metadata/detailviewdefs.php | 331 ++ .../Contacts/metadata/editviewdefs.php | 370 ++ .../Opportunities/metadata/detailviewdefs.php | 391 ++ .../Opportunities/metadata/editviewdefs.php | 402 +++ .../Opportunities/metadata/searchdefs.php | 130 + tests/modules/Users/UserTest.php | 107 + tests/phpuc.xml | 27 + tests/phpunit.bat | 40 + tests/phpunit.php | 56 + tests/phpunit.xml | 11 + tests/service/APIv3Helper.php | 131 + tests/service/Bug39234Test.php | 152 + tests/service/Bug39855Test.php | 139 + tests/service/Bug40250Test.php | 101 + tests/service/Bug42683Test.php | 37 + tests/service/RESTAPI3Test.php | 771 ++++ tests/service/SOAPAPI1Test.php | 157 + tests/service/SOAPAPI2Test.php | 261 ++ tests/service/SOAPAPI3Test.php | 410 +++ tests/service/SOAPTestCase.php | 79 + tests/tests/SugarTestImportUtilitiesTest.php | 81 + tests/tests/SugarTestLangPackCreatorTest.php | 47 + tests/tests/SugarTestThemeUtilitiesTest.php | 61 + tests/tests/SugarTestUserUtilitiesTest.php | 62 + 697 files changed, 97774 insertions(+) create mode 100755 tests/ModuleInstall/Bug41829Test.php create mode 100755 tests/ModuleInstall/ModuleScannerTest.php create mode 100755 tests/ModuleInstall/PackageManager/Bug39980Test.php create mode 100755 tests/PHPUnit/Extensions/Database/AbstractTester.php create mode 100755 tests/PHPUnit/Extensions/Database/Constraint/DataSetIsEqual.php create mode 100755 tests/PHPUnit/Extensions/Database/Constraint/TableIsEqual.php create mode 100755 tests/PHPUnit/Extensions/Database/DB/DataSet.php create mode 100755 tests/PHPUnit/Extensions/Database/DB/DefaultDatabaseConnection.php create mode 100755 tests/PHPUnit/Extensions/Database/DB/FilteredDataSet.php create mode 100755 tests/PHPUnit/Extensions/Database/DB/IDatabaseConnection.php create mode 100755 tests/PHPUnit/Extensions/Database/DB/IMetaData.php create mode 100755 tests/PHPUnit/Extensions/Database/DB/MetaData.php create mode 100755 tests/PHPUnit/Extensions/Database/DB/MetaData/InformationSchema.php create mode 100755 tests/PHPUnit/Extensions/Database/DB/MetaData/MySQL.php create mode 100755 tests/PHPUnit/Extensions/Database/DB/MetaData/Oci.php create mode 100755 tests/PHPUnit/Extensions/Database/DB/MetaData/PgSQL.php create mode 100755 tests/PHPUnit/Extensions/Database/DB/MetaData/Sqlite.php create mode 100755 tests/PHPUnit/Extensions/Database/DB/ResultSetTable.php create mode 100755 tests/PHPUnit/Extensions/Database/DB/Table.php create mode 100755 tests/PHPUnit/Extensions/Database/DB/TableIterator.php create mode 100755 tests/PHPUnit/Extensions/Database/DB/TableMetaData.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/AbstractDataSet.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/AbstractTable.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/AbstractTableMetaData.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/AbstractXmlDataSet.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/CompositeDataSet.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/CsvDataSet.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/DataSetFilter.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/DefaultDataSet.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/DefaultTable.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/DefaultTableIterator.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/IDataSet.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/IPersistable.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/ITable.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/ITableIterator.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/ITableMetaData.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/Persistors/Abstract.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/Persistors/FlatXml.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/Persistors/Xml.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/QueryDataSet.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/QueryTable.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/ReplacementDataSet.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/ReplacementTable.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/ReplacementTableIterator.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/TableFilter.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/TableMetaDataFilter.php create mode 100755 tests/PHPUnit/Extensions/Database/DataSet/XmlDataSet.php create mode 100755 tests/PHPUnit/Extensions/Database/DefaultTester.php create mode 100755 tests/PHPUnit/Extensions/Database/ITester.php create mode 100755 tests/PHPUnit/Extensions/Database/Operation/Composite.php create mode 100755 tests/PHPUnit/Extensions/Database/Operation/Delete.php create mode 100755 tests/PHPUnit/Extensions/Database/Operation/DeleteAll.php create mode 100755 tests/PHPUnit/Extensions/Database/Operation/Exception.php create mode 100755 tests/PHPUnit/Extensions/Database/Operation/Factory.php create mode 100755 tests/PHPUnit/Extensions/Database/Operation/IDatabaseOperation.php create mode 100755 tests/PHPUnit/Extensions/Database/Operation/Insert.php create mode 100755 tests/PHPUnit/Extensions/Database/Operation/Null.php create mode 100755 tests/PHPUnit/Extensions/Database/Operation/Replace.php create mode 100755 tests/PHPUnit/Extensions/Database/Operation/RowBased.php create mode 100755 tests/PHPUnit/Extensions/Database/Operation/Truncate.php create mode 100755 tests/PHPUnit/Extensions/Database/Operation/Update.php create mode 100755 tests/PHPUnit/Extensions/Database/TestCase.php create mode 100755 tests/PHPUnit/Extensions/GroupTestSuite.php create mode 100755 tests/PHPUnit/Extensions/OutputTestCase.php create mode 100755 tests/PHPUnit/Extensions/PerformanceTestCase.php create mode 100755 tests/PHPUnit/Extensions/PhptTestCase.php create mode 100755 tests/PHPUnit/Extensions/PhptTestCase/Logger.php create mode 100755 tests/PHPUnit/Extensions/PhptTestSuite.php create mode 100755 tests/PHPUnit/Extensions/RepeatedTest.php create mode 100755 tests/PHPUnit/Extensions/SeleniumTestCase.php create mode 100755 tests/PHPUnit/Extensions/SeleniumTestCase/Driver.php create mode 100755 tests/PHPUnit/Extensions/SeleniumTestCase/append.php create mode 100755 tests/PHPUnit/Extensions/SeleniumTestCase/phpunit_coverage.php create mode 100755 tests/PHPUnit/Extensions/SeleniumTestCase/prepend.php create mode 100755 tests/PHPUnit/Extensions/Story/Given.php create mode 100755 tests/PHPUnit/Extensions/Story/ResultPrinter.php create mode 100755 tests/PHPUnit/Extensions/Story/ResultPrinter/HTML.php create mode 100755 tests/PHPUnit/Extensions/Story/ResultPrinter/Template/scenario.html.dist create mode 100755 tests/PHPUnit/Extensions/Story/ResultPrinter/Template/scenario_header.html.dist create mode 100755 tests/PHPUnit/Extensions/Story/ResultPrinter/Template/scenarios.html.dist create mode 100755 tests/PHPUnit/Extensions/Story/ResultPrinter/Template/step.html.dist create mode 100755 tests/PHPUnit/Extensions/Story/ResultPrinter/Text.php create mode 100755 tests/PHPUnit/Extensions/Story/Scenario.php create mode 100755 tests/PHPUnit/Extensions/Story/SeleniumTestCase.php create mode 100755 tests/PHPUnit/Extensions/Story/Step.php create mode 100755 tests/PHPUnit/Extensions/Story/TestCase.php create mode 100755 tests/PHPUnit/Extensions/Story/Then.php create mode 100755 tests/PHPUnit/Extensions/Story/When.php create mode 100755 tests/PHPUnit/Extensions/TestDecorator.php create mode 100755 tests/PHPUnit/Framework.php create mode 100755 tests/PHPUnit/Framework/Assert.php create mode 100755 tests/PHPUnit/Framework/AssertionFailedError.php create mode 100755 tests/PHPUnit/Framework/ComparisonFailure.php create mode 100755 tests/PHPUnit/Framework/ComparisonFailure/Array.php create mode 100755 tests/PHPUnit/Framework/ComparisonFailure/Object.php create mode 100755 tests/PHPUnit/Framework/ComparisonFailure/Scalar.php create mode 100755 tests/PHPUnit/Framework/ComparisonFailure/String.php create mode 100755 tests/PHPUnit/Framework/ComparisonFailure/Type.php create mode 100755 tests/PHPUnit/Framework/Constraint.php create mode 100755 tests/PHPUnit/Framework/Constraint/And.php create mode 100755 tests/PHPUnit/Framework/Constraint/ArrayHasKey.php create mode 100755 tests/PHPUnit/Framework/Constraint/Attribute.php create mode 100755 tests/PHPUnit/Framework/Constraint/ClassHasAttribute.php create mode 100755 tests/PHPUnit/Framework/Constraint/ClassHasStaticAttribute.php create mode 100755 tests/PHPUnit/Framework/Constraint/FileExists.php create mode 100755 tests/PHPUnit/Framework/Constraint/GreaterThan.php create mode 100755 tests/PHPUnit/Framework/Constraint/IsAnything.php create mode 100755 tests/PHPUnit/Framework/Constraint/IsEqual.php create mode 100755 tests/PHPUnit/Framework/Constraint/IsFalse.php create mode 100755 tests/PHPUnit/Framework/Constraint/IsIdentical.php create mode 100755 tests/PHPUnit/Framework/Constraint/IsInstanceOf.php create mode 100755 tests/PHPUnit/Framework/Constraint/IsNull.php create mode 100755 tests/PHPUnit/Framework/Constraint/IsTrue.php create mode 100755 tests/PHPUnit/Framework/Constraint/IsType.php create mode 100755 tests/PHPUnit/Framework/Constraint/LessThan.php create mode 100755 tests/PHPUnit/Framework/Constraint/Not.php create mode 100755 tests/PHPUnit/Framework/Constraint/ObjectHasAttribute.php create mode 100755 tests/PHPUnit/Framework/Constraint/Or.php create mode 100755 tests/PHPUnit/Framework/Constraint/PCREMatch.php create mode 100755 tests/PHPUnit/Framework/Constraint/StringContains.php create mode 100755 tests/PHPUnit/Framework/Constraint/TraversableContains.php create mode 100755 tests/PHPUnit/Framework/Constraint/TraversableContainsOnly.php create mode 100755 tests/PHPUnit/Framework/Constraint/Xor.php create mode 100755 tests/PHPUnit/Framework/Error.php create mode 100755 tests/PHPUnit/Framework/Error/Notice.php create mode 100755 tests/PHPUnit/Framework/Error/Warning.php create mode 100755 tests/PHPUnit/Framework/ExpectationFailedException.php create mode 100755 tests/PHPUnit/Framework/IncompleteTest.php create mode 100755 tests/PHPUnit/Framework/IncompleteTestError.php create mode 100755 tests/PHPUnit/Framework/MockObject/Builder/Identity.php create mode 100755 tests/PHPUnit/Framework/MockObject/Builder/InvocationMocker.php create mode 100755 tests/PHPUnit/Framework/MockObject/Builder/Match.php create mode 100755 tests/PHPUnit/Framework/MockObject/Builder/MethodNameMatch.php create mode 100755 tests/PHPUnit/Framework/MockObject/Builder/Namespace.php create mode 100755 tests/PHPUnit/Framework/MockObject/Builder/ParametersMatch.php create mode 100755 tests/PHPUnit/Framework/MockObject/Builder/Stub.php create mode 100755 tests/PHPUnit/Framework/MockObject/Invocation.php create mode 100755 tests/PHPUnit/Framework/MockObject/InvocationMocker.php create mode 100755 tests/PHPUnit/Framework/MockObject/Invokable.php create mode 100755 tests/PHPUnit/Framework/MockObject/Matcher.php create mode 100755 tests/PHPUnit/Framework/MockObject/Matcher/AnyInvokedCount.php create mode 100755 tests/PHPUnit/Framework/MockObject/Matcher/AnyParameters.php create mode 100755 tests/PHPUnit/Framework/MockObject/Matcher/Invocation.php create mode 100755 tests/PHPUnit/Framework/MockObject/Matcher/InvokedAtIndex.php create mode 100755 tests/PHPUnit/Framework/MockObject/Matcher/InvokedAtLeastOnce.php create mode 100755 tests/PHPUnit/Framework/MockObject/Matcher/InvokedCount.php create mode 100755 tests/PHPUnit/Framework/MockObject/Matcher/InvokedRecorder.php create mode 100755 tests/PHPUnit/Framework/MockObject/Matcher/MethodName.php create mode 100755 tests/PHPUnit/Framework/MockObject/Matcher/Parameters.php create mode 100755 tests/PHPUnit/Framework/MockObject/Matcher/StatelessInvocation.php create mode 100755 tests/PHPUnit/Framework/MockObject/Mock.php create mode 100755 tests/PHPUnit/Framework/MockObject/MockObject.php create mode 100755 tests/PHPUnit/Framework/MockObject/Stub.php create mode 100755 tests/PHPUnit/Framework/MockObject/Stub/ConsecutiveCalls.php create mode 100755 tests/PHPUnit/Framework/MockObject/Stub/Exception.php create mode 100755 tests/PHPUnit/Framework/MockObject/Stub/MatcherCollection.php create mode 100755 tests/PHPUnit/Framework/MockObject/Stub/Return.php create mode 100755 tests/PHPUnit/Framework/MockObject/Stub/ReturnArgument.php create mode 100755 tests/PHPUnit/Framework/MockObject/Stub/ReturnCallback.php create mode 100755 tests/PHPUnit/Framework/MockObject/Verifiable.php create mode 100755 tests/PHPUnit/Framework/SelfDescribing.php create mode 100755 tests/PHPUnit/Framework/SkippedTest.php create mode 100755 tests/PHPUnit/Framework/SkippedTestError.php create mode 100755 tests/PHPUnit/Framework/SkippedTestSuiteError.php create mode 100755 tests/PHPUnit/Framework/Test.php create mode 100755 tests/PHPUnit/Framework/TestCase.php create mode 100755 tests/PHPUnit/Framework/TestFailure.php create mode 100755 tests/PHPUnit/Framework/TestListener.php create mode 100755 tests/PHPUnit/Framework/TestResult.php create mode 100755 tests/PHPUnit/Framework/TestSuite.php create mode 100755 tests/PHPUnit/Framework/Warning.php create mode 100755 tests/PHPUnit/Runner/BaseTestRunner.php create mode 100755 tests/PHPUnit/Runner/IncludePathTestCollector.php create mode 100755 tests/PHPUnit/Runner/StandardTestSuiteLoader.php create mode 100755 tests/PHPUnit/Runner/TestCollector.php create mode 100755 tests/PHPUnit/Runner/TestSuiteLoader.php create mode 100755 tests/PHPUnit/Runner/Version.php create mode 100755 tests/PHPUnit/Samples/BankAccount/BankAccount.php create mode 100755 tests/PHPUnit/Samples/BankAccount/BankAccountTest.php create mode 100755 tests/PHPUnit/Samples/BankAccountDB/BankAccount.php create mode 100755 tests/PHPUnit/Samples/BankAccountDB/BankAccountDBTest.php create mode 100755 tests/PHPUnit/Samples/BankAccountDB/BankAccountDBTestMySQL.php create mode 100755 tests/PHPUnit/Samples/BankAccountDB/_files/bank-account-after-deposits.xml create mode 100755 tests/PHPUnit/Samples/BankAccountDB/_files/bank-account-after-new-account.xml create mode 100755 tests/PHPUnit/Samples/BankAccountDB/_files/bank-account-after-withdrawals.xml create mode 100755 tests/PHPUnit/Samples/BankAccountDB/_files/bank-account-seed.xml create mode 100755 tests/PHPUnit/Samples/BowlingGame/BowlingGame.php create mode 100755 tests/PHPUnit/Samples/BowlingGame/BowlingGameSpec.php create mode 100755 tests/PHPUnit/Samples/BowlingGame/BowlingGameTest.php create mode 100755 tests/PHPUnit/Samples/FailureTest.php create mode 100755 tests/PHPUnit/Samples/Money/IMoney.php create mode 100755 tests/PHPUnit/Samples/Money/Money.php create mode 100755 tests/PHPUnit/Samples/Money/MoneyBag.php create mode 100755 tests/PHPUnit/Samples/Money/MoneyTest.php create mode 100755 tests/PHPUnit/Tests/AllTests.php create mode 100755 tests/PHPUnit/Tests/Extensions/AllTests.php create mode 100755 tests/PHPUnit/Tests/Extensions/Database/AllTests.php create mode 100755 tests/PHPUnit/Tests/Extensions/Database/DataSet/AllTests.php create mode 100755 tests/PHPUnit/Tests/Extensions/Database/DataSet/CompositeDataSetTest.php create mode 100755 tests/PHPUnit/Tests/Extensions/Database/DataSet/CsvDataSetTest.php create mode 100755 tests/PHPUnit/Tests/Extensions/Database/DataSet/FilterTest.php create mode 100755 tests/PHPUnit/Tests/Extensions/Database/DataSet/PersistorTest.php create mode 100755 tests/PHPUnit/Tests/Extensions/Database/DataSet/QueryDataSetTest.php create mode 100755 tests/PHPUnit/Tests/Extensions/Database/DataSet/QueryTableTest.php create mode 100755 tests/PHPUnit/Tests/Extensions/Database/DataSet/ReplacementDataSetTest.php create mode 100755 tests/PHPUnit/Tests/Extensions/Database/DataSet/ReplacementTableTest.php create mode 100755 tests/PHPUnit/Tests/Extensions/Database/DataSet/XmlDataSetsTest.php create mode 100755 tests/PHPUnit/Tests/Extensions/Database/Operation/AllTests.php create mode 100755 tests/PHPUnit/Tests/Extensions/Database/Operation/OperationsTest.php create mode 100755 tests/PHPUnit/Tests/Extensions/Database/Operation/RowBasedTest.php create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/CsvDataSets/table1.csv create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/CsvDataSets/table2.csv create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/DatabaseTestUtility.php create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/AllEmptyTableInsertResult.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/AllEmptyTableInsertTest.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/DeleteAllOperationTest.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/DeleteOperationResult.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/DeleteOperationTest.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/EmptyTableInsertResult.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/EmptyTableInsertTest.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/FilteredTestComparison.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/FilteredTestFixture.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/FlatXmlDataSet.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/FlatXmlWriter.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/InsertOperationResult.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/InsertOperationTest.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/OperationsTestFixture.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/QueryDataSetTest.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/ReplaceOperationResult.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/ReplaceOperationTest.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/RowBasedExecute.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/UpdateOperationResult.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/UpdateOperationTest.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/XmlDataSet.xml create mode 100755 tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/XmlWriter.xml create mode 100755 tests/PHPUnit/Tests/Extensions/OutputTestCaseTest.php create mode 100755 tests/PHPUnit/Tests/Extensions/PerformanceTestCaseTest.php create mode 100755 tests/PHPUnit/Tests/Extensions/RepeatedTestTest.php create mode 100755 tests/PHPUnit/Tests/Extensions/SeleniumTestCaseTest.php create mode 100755 tests/PHPUnit/Tests/Framework/AllTests.php create mode 100755 tests/PHPUnit/Tests/Framework/AssertTest.php create mode 100755 tests/PHPUnit/Tests/Framework/ComparisonFailureTest.php create mode 100755 tests/PHPUnit/Tests/Framework/ConstraintTest.php create mode 100755 tests/PHPUnit/Tests/Framework/MockObjectTest.php create mode 100755 tests/PHPUnit/Tests/Framework/SuiteTest.php create mode 100755 tests/PHPUnit/Tests/Framework/TestCaseTest.php create mode 100755 tests/PHPUnit/Tests/Framework/TestFailureTest.php create mode 100755 tests/PHPUnit/Tests/Framework/TestImplementorTest.php create mode 100755 tests/PHPUnit/Tests/Framework/TestListenerTest.php create mode 100755 tests/PHPUnit/Tests/Regression/578.phpt create mode 100755 tests/PHPUnit/Tests/Regression/684.phpt create mode 100755 tests/PHPUnit/Tests/Regression/Issue578Test.php create mode 100755 tests/PHPUnit/Tests/Regression/Issue684Test.php create mode 100755 tests/PHPUnit/Tests/Runner/AllTests.php create mode 100755 tests/PHPUnit/Tests/Runner/BaseTestRunnerTest.php create mode 100755 tests/PHPUnit/Tests/TextUI/abstract-test-class.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/concrete-test-class.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/coverage-clover-class-extended.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/coverage-clover-class.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/coverage-clover-method.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/coverage-clover-not-private.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/coverage-clover-not-protected.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/coverage-clover-not-public.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/coverage-clover-private.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/coverage-clover-protected.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/coverage-clover-public.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/coverage-clover.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/coverage-source.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/dataset-log-xml.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/debug.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/default.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/exclude-group.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/filter-class.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/filter-method.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/group.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/help.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/help2.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/list-groups.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/log-graphviz.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/log-json.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/log-tap.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/log-xml.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/repeat.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/skeleton.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/story.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/tap.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/testdox-html.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/testdox-text.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/testdox.phpt create mode 100755 tests/PHPUnit/Tests/TextUI/verbose.phpt create mode 100755 tests/PHPUnit/Tests/Util/AllTests.php create mode 100755 tests/PHPUnit/Tests/Util/ConfigurationTest.php create mode 100755 tests/PHPUnit/Tests/Util/TestDox/AllTests.php create mode 100755 tests/PHPUnit/Tests/Util/TestDox/NamePrettifierTest.php create mode 100755 tests/PHPUnit/Tests/Util/TestTest.php create mode 100755 tests/PHPUnit/Tests/Util/TimerTest.php create mode 100755 tests/PHPUnit/Tests/Util/XMLTest.php create mode 100755 tests/PHPUnit/Tests/_files/AbstractTest.php create mode 100755 tests/PHPUnit/Tests/_files/AnInterface.php create mode 100755 tests/PHPUnit/Tests/_files/Calculator.php create mode 100755 tests/PHPUnit/Tests/_files/ClassWithNonPublicAttributes.php create mode 100755 tests/PHPUnit/Tests/_files/ConcreteTest.php create mode 100755 tests/PHPUnit/Tests/_files/CoverageClassExtendedTest.php create mode 100755 tests/PHPUnit/Tests/_files/CoverageClassTest.php create mode 100755 tests/PHPUnit/Tests/_files/CoverageMethodTest.php create mode 100755 tests/PHPUnit/Tests/_files/CoverageNotPrivateTest.php create mode 100755 tests/PHPUnit/Tests/_files/CoverageNotProtectedTest.php create mode 100755 tests/PHPUnit/Tests/_files/CoverageNotPublicTest.php create mode 100755 tests/PHPUnit/Tests/_files/CoveragePrivateTest.php create mode 100755 tests/PHPUnit/Tests/_files/CoverageProtectedTest.php create mode 100755 tests/PHPUnit/Tests/_files/CoveragePublicTest.php create mode 100755 tests/PHPUnit/Tests/_files/CoveredClass.php create mode 100755 tests/PHPUnit/Tests/_files/DataSetTest.php create mode 100755 tests/PHPUnit/Tests/_files/DoubleTestCase.php create mode 100755 tests/PHPUnit/Tests/_files/Error.php create mode 100755 tests/PHPUnit/Tests/_files/Failure.php create mode 100755 tests/PHPUnit/Tests/_files/FunctionCallback.php create mode 100755 tests/PHPUnit/Tests/_files/InheritedTestCase.php create mode 100755 tests/PHPUnit/Tests/_files/MethodCallback.php create mode 100755 tests/PHPUnit/Tests/_files/MockRunner.php create mode 100755 tests/PHPUnit/Tests/_files/NoArgTestCaseTest.php create mode 100755 tests/PHPUnit/Tests/_files/NoTestCaseClass.php create mode 100755 tests/PHPUnit/Tests/_files/NoTestCases.php create mode 100755 tests/PHPUnit/Tests/_files/NonStatic.php create mode 100755 tests/PHPUnit/Tests/_files/NotPublicTestCase.php create mode 100755 tests/PHPUnit/Tests/_files/NotVoidTestCase.php create mode 100755 tests/PHPUnit/Tests/_files/OneTestCase.php create mode 100755 tests/PHPUnit/Tests/_files/OutputTestCase.php create mode 100755 tests/PHPUnit/Tests/_files/OverrideTestCase.php create mode 100755 tests/PHPUnit/Tests/_files/PartialMockTestClass.php create mode 100755 tests/PHPUnit/Tests/_files/SampleClass.php create mode 100755 tests/PHPUnit/Tests/_files/SelectorAssertionsFixture.html create mode 100755 tests/PHPUnit/Tests/_files/SetupFailure.php create mode 100755 tests/PHPUnit/Tests/_files/SleepTest.php create mode 100755 tests/PHPUnit/Tests/_files/Struct.php create mode 100755 tests/PHPUnit/Tests/_files/Success.php create mode 100755 tests/PHPUnit/Tests/_files/TearDownFailure.php create mode 100755 tests/PHPUnit/Tests/_files/TestIterator.php create mode 100755 tests/PHPUnit/Tests/_files/ThrowExceptionTestCase.php create mode 100755 tests/PHPUnit/Tests/_files/ThrowNoExceptionTestCase.php create mode 100755 tests/PHPUnit/Tests/_files/TornDown.php create mode 100755 tests/PHPUnit/Tests/_files/TornDown2.php create mode 100755 tests/PHPUnit/Tests/_files/TornDown3.php create mode 100755 tests/PHPUnit/Tests/_files/TornDown4.php create mode 100755 tests/PHPUnit/Tests/_files/TornDown5.php create mode 100755 tests/PHPUnit/Tests/_files/WasRun.php create mode 100755 tests/PHPUnit/Tests/_files/bar.xml create mode 100755 tests/PHPUnit/Tests/_files/configuration.xml create mode 100755 tests/PHPUnit/Tests/_files/foo.xml create mode 100755 tests/PHPUnit/Tests/_files/structureAttributesAreSameButValuesAreNot.xml create mode 100755 tests/PHPUnit/Tests/_files/structureExpected.xml create mode 100755 tests/PHPUnit/Tests/_files/structureIgnoreTextNodes.xml create mode 100755 tests/PHPUnit/Tests/_files/structureIsSameButDataIsNot.xml create mode 100755 tests/PHPUnit/Tests/_files/structureWrongNumberOfAttributes.xml create mode 100755 tests/PHPUnit/Tests/_files/structureWrongNumberOfNodes.xml create mode 100755 tests/PHPUnit/Tests/phpunit.xml.dist create mode 100755 tests/PHPUnit/TextUI/Command.php create mode 100755 tests/PHPUnit/TextUI/ResultPrinter.php create mode 100755 tests/PHPUnit/TextUI/TestRunner.php create mode 100755 tests/PHPUnit/Util/Class.php create mode 100755 tests/PHPUnit/Util/CodeCoverage.php create mode 100755 tests/PHPUnit/Util/Configuration.php create mode 100755 tests/PHPUnit/Util/ErrorHandler.php create mode 100755 tests/PHPUnit/Util/Fileloader.php create mode 100755 tests/PHPUnit/Util/Filesystem.php create mode 100755 tests/PHPUnit/Util/Filter.php create mode 100755 tests/PHPUnit/Util/FilterIterator.php create mode 100755 tests/PHPUnit/Util/Getopt.php create mode 100755 tests/PHPUnit/Util/Log/CPD.php create mode 100755 tests/PHPUnit/Util/Log/CodeCoverage/Database.php create mode 100755 tests/PHPUnit/Util/Log/CodeCoverage/XML/Clover.php create mode 100755 tests/PHPUnit/Util/Log/CodeCoverage/XML/Source.php create mode 100755 tests/PHPUnit/Util/Log/Database.php create mode 100755 tests/PHPUnit/Util/Log/Database/MySQL.sql create mode 100755 tests/PHPUnit/Util/Log/Database/SQLite3.sql create mode 100755 tests/PHPUnit/Util/Log/GraphViz.php create mode 100755 tests/PHPUnit/Util/Log/JSON.php create mode 100755 tests/PHPUnit/Util/Log/Metrics.php create mode 100755 tests/PHPUnit/Util/Log/PEAR.php create mode 100755 tests/PHPUnit/Util/Log/PMD.php create mode 100755 tests/PHPUnit/Util/Log/PMD/Rule.php create mode 100755 tests/PHPUnit/Util/Log/PMD/Rule/Class.php create mode 100755 tests/PHPUnit/Util/Log/PMD/Rule/Class/DepthOfInheritanceTree.php create mode 100755 tests/PHPUnit/Util/Log/PMD/Rule/Class/EfferentCoupling.php create mode 100755 tests/PHPUnit/Util/Log/PMD/Rule/Class/ExcessiveClassLength.php create mode 100755 tests/PHPUnit/Util/Log/PMD/Rule/Class/ExcessivePublicCount.php create mode 100755 tests/PHPUnit/Util/Log/PMD/Rule/Class/TooManyFields.php create mode 100755 tests/PHPUnit/Util/Log/PMD/Rule/File.php create mode 100755 tests/PHPUnit/Util/Log/PMD/Rule/Function.php create mode 100755 tests/PHPUnit/Util/Log/PMD/Rule/Function/CRAP.php create mode 100755 tests/PHPUnit/Util/Log/PMD/Rule/Function/CodeCoverage.php create mode 100755 tests/PHPUnit/Util/Log/PMD/Rule/Function/CyclomaticComplexity.php create mode 100755 tests/PHPUnit/Util/Log/PMD/Rule/Function/ExcessiveMethodLength.php create mode 100755 tests/PHPUnit/Util/Log/PMD/Rule/Function/ExcessiveParameterList.php create mode 100755 tests/PHPUnit/Util/Log/PMD/Rule/Function/NPathComplexity.php create mode 100755 tests/PHPUnit/Util/Log/PMD/Rule/Project.php create mode 100755 tests/PHPUnit/Util/Log/PMD/Rule/Project/CRAP.php create mode 100755 tests/PHPUnit/Util/Log/TAP.php create mode 100755 tests/PHPUnit/Util/Log/XML.php create mode 100755 tests/PHPUnit/Util/Metrics.php create mode 100755 tests/PHPUnit/Util/Metrics/Class.php create mode 100755 tests/PHPUnit/Util/Metrics/File.php create mode 100755 tests/PHPUnit/Util/Metrics/Function.php create mode 100755 tests/PHPUnit/Util/Metrics/Project.php create mode 100755 tests/PHPUnit/Util/PDO.php create mode 100755 tests/PHPUnit/Util/Printer.php create mode 100755 tests/PHPUnit/Util/Report.php create mode 100755 tests/PHPUnit/Util/Report/Node.php create mode 100755 tests/PHPUnit/Util/Report/Node/Directory.php create mode 100755 tests/PHPUnit/Util/Report/Node/File.php create mode 100755 tests/PHPUnit/Util/Report/Template/butter.png create mode 100755 tests/PHPUnit/Util/Report/Template/chameleon.png create mode 100755 tests/PHPUnit/Util/Report/Template/close12_1.gif create mode 100755 tests/PHPUnit/Util/Report/Template/container-min.js create mode 100755 tests/PHPUnit/Util/Report/Template/container.css create mode 100755 tests/PHPUnit/Util/Report/Template/directory.html.dist create mode 100755 tests/PHPUnit/Util/Report/Template/directory_item.html.dist create mode 100755 tests/PHPUnit/Util/Report/Template/file.html.dist create mode 100755 tests/PHPUnit/Util/Report/Template/file_item.html.dist create mode 100755 tests/PHPUnit/Util/Report/Template/file_no_yui.html.dist create mode 100755 tests/PHPUnit/Util/Report/Template/glass.png create mode 100755 tests/PHPUnit/Util/Report/Template/method_item.html.dist create mode 100755 tests/PHPUnit/Util/Report/Template/scarlet_red.png create mode 100755 tests/PHPUnit/Util/Report/Template/snow.png create mode 100755 tests/PHPUnit/Util/Report/Template/style.css create mode 100755 tests/PHPUnit/Util/Report/Template/yahoo-dom-event.js create mode 100755 tests/PHPUnit/Util/Report/Template/yui_item.js create mode 100755 tests/PHPUnit/Util/Skeleton.php create mode 100755 tests/PHPUnit/Util/Skeleton/Class.php create mode 100755 tests/PHPUnit/Util/Skeleton/Template/Class.tpl.dist create mode 100755 tests/PHPUnit/Util/Skeleton/Template/IncompleteTestMethod.tpl.dist create mode 100755 tests/PHPUnit/Util/Skeleton/Template/Method.tpl.dist create mode 100755 tests/PHPUnit/Util/Skeleton/Template/TestClass.tpl.dist create mode 100755 tests/PHPUnit/Util/Skeleton/Template/TestMethod.tpl.dist create mode 100755 tests/PHPUnit/Util/Skeleton/Template/TestMethodBool.tpl.dist create mode 100755 tests/PHPUnit/Util/Skeleton/Template/TestMethodBoolStatic.tpl.dist create mode 100755 tests/PHPUnit/Util/Skeleton/Template/TestMethodException.tpl.dist create mode 100755 tests/PHPUnit/Util/Skeleton/Template/TestMethodExceptionStatic.tpl.dist create mode 100755 tests/PHPUnit/Util/Skeleton/Template/TestMethodStatic.tpl.dist create mode 100755 tests/PHPUnit/Util/Skeleton/Test.php create mode 100755 tests/PHPUnit/Util/Template.php create mode 100755 tests/PHPUnit/Util/Test.php create mode 100755 tests/PHPUnit/Util/TestDox/NamePrettifier.php create mode 100755 tests/PHPUnit/Util/TestDox/ResultPrinter.php create mode 100755 tests/PHPUnit/Util/TestDox/ResultPrinter/HTML.php create mode 100755 tests/PHPUnit/Util/TestDox/ResultPrinter/Text.php create mode 100755 tests/PHPUnit/Util/TestSuiteIterator.php create mode 100755 tests/PHPUnit/Util/Timer.php create mode 100755 tests/PHPUnit/Util/Type.php create mode 100755 tests/PHPUnit/Util/XML.php create mode 100755 tests/SugarTestAccountUtilities.php create mode 100755 tests/SugarTestCampaignUtilities.php create mode 100755 tests/SugarTestContactUtilities.php create mode 100755 tests/SugarTestEmailUtilities.php create mode 100755 tests/SugarTestHelper.php create mode 100755 tests/SugarTestImportUtilities.php create mode 100755 tests/SugarTestLangPackCreator.php create mode 100755 tests/SugarTestLeadUtilities.php create mode 100755 tests/SugarTestMeetingUtilities.php create mode 100755 tests/SugarTestMergeUtilities.php create mode 100755 tests/SugarTestStudioUtilities.php create mode 100755 tests/SugarTestThemeUtilities.php create mode 100755 tests/SugarTestTrackerUtility.php create mode 100755 tests/SugarTestUserUtilities.php create mode 100755 tests/codecoverage.xml create mode 100755 tests/data/Bug39780Test.php create mode 100755 tests/data/Bug40739Test.php create mode 100755 tests/data/fixUpFormatting.php create mode 100755 tests/expressions/expression_engine_eval.php create mode 100755 tests/expressions/expression_engine_test.html create mode 100755 tests/include/Dashlets/Bug41013Test.php create mode 100755 tests/include/Dashlets/DashletLoadLanguageTest.php create mode 100755 tests/include/Expressions/Actions/ActionFactory.php create mode 100755 tests/include/Expressions/Expression/Parser/Parser.php create mode 100755 tests/include/JSONTest.php create mode 100755 tests/include/Localization/LocalizationTest.php create mode 100755 tests/include/MVC/Controller/SugarControllerTest.php create mode 100755 tests/include/MVC/SugarApplicationTest.php create mode 100755 tests/include/MVC/SugarModuleTest.php create mode 100755 tests/include/MVC/View/Bug40019Test.php create mode 100755 tests/include/MVC/View/LoadMenuTest.php create mode 100755 tests/include/MassUpdateTest.php create mode 100755 tests/include/OutboundEmail/Bug23140Test.php create mode 100755 tests/include/OutboundEmail/Bug32487Test.php create mode 100755 tests/include/Popup/Bug36329Test.php create mode 100755 tests/include/SearchForm/SugarSpotTest.php create mode 100755 tests/include/Smarty/plugins/FunctionMultienumToArrayTest.php create mode 100755 tests/include/Smarty/plugins/FunctionSugarHelpTest.php create mode 100755 tests/include/Smarty/plugins/FunctionSugarLinkTest.php create mode 100755 tests/include/Smarty/plugins/FunctionSugarTranslateTest.php create mode 100755 tests/include/SubPanel/Bug40171Test.php create mode 100755 tests/include/SubPanel/Bug41738Test.php create mode 100755 tests/include/SubPanel/GetUnionRelatedTest.php create mode 100755 tests/include/SugarEmailAddress/Bug40068Test.php create mode 100755 tests/include/SugarEmailAddress/SugarEmailAddressRegexTest.php create mode 100755 tests/include/SugarFields/Fields/Enum/SugarFieldEnumTest.php create mode 100755 tests/include/SugarFields/Fields/Relate/SugarFieldRelateTest.php create mode 100755 tests/include/SugarFolders/Bug33404Test.php create mode 100755 tests/include/SugarFolders/Bug33906Test.php create mode 100755 tests/include/SugarFolders/SugarFoldersTest.php create mode 100755 tests/include/SugarLogger/SugarLoggerTest.php create mode 100755 tests/include/SugarObjects/BasicTemplateTest.php create mode 100755 tests/include/SugarObjects/PersonTemplateTest.php create mode 100755 tests/include/SugarObjects/SugarConfigTest.php create mode 100755 tests/include/SugarObjects/SugarRegistryTest.php create mode 100755 tests/include/SugarTheme/SugarThemeRegistryTest.php create mode 100755 tests/include/SugarTheme/SugarThemeTest.php create mode 100755 tests/include/TimeDateTest.php create mode 100755 tests/include/connectors/ConnectorsTestUtility.php create mode 100755 tests/include/database/DBHelperTest.php create mode 100755 tests/include/database/DBManagerFactoryTest.php create mode 100755 tests/include/database/DBManagerTest.php create mode 100755 tests/include/database/FreeTDSManagerTest.php create mode 100755 tests/include/javascript/JSAlertsTest.php create mode 100755 tests/include/javascript/JavascriptTest.php create mode 100755 tests/include/utils/Bug22882Test.php create mode 100755 tests/include/utils/Bug33284_Test.php create mode 100755 tests/include/utils/Bug42427Test.php create mode 100755 tests/include/utils/CheckPhpVersionTest.php create mode 100755 tests/include/utils/CheckPlatformTest.php create mode 100755 tests/include/utils/CreateCacheDirectoryTest.php create mode 100755 tests/include/utils/DbUtilsTest.php create mode 100755 tests/include/utils/DeepArrayDiffTest.php create mode 100755 tests/include/utils/ExternalCacheAPITest.php create mode 100755 tests/include/utils/SugarArrayMergeRecursiveTest.php create mode 100755 tests/include/utils/SugarArrayMergeTest.php create mode 100755 tests/include/utils/SugarArrayTest.php create mode 100755 tests/include/utils/SugarFileUtilsTest.php create mode 100755 tests/include/utils/SugarVersionTest.php create mode 100755 tests/include/utils/XssTest.php create mode 100755 tests/include/vCard/ISO88591SampleFile.vcf create mode 100755 tests/include/vCard/SimpleVCard.vcf create mode 100755 tests/include/vCard/UTF8SampleFile.vcf create mode 100755 tests/include/vCard/vCardBug40629Test.php create mode 100755 tests/include/vCard/vCardTest.php create mode 100755 tests/include/workflow/testfiles/logic_hooks.php create mode 100755 tests/include/workflow/testfiles/workflow/actions_array.php create mode 100755 tests/include/workflow/testfiles/workflow/alerts_array.php create mode 100755 tests/include/workflow/testfiles/workflow/plugins_array.php create mode 100755 tests/include/workflow/testfiles/workflow/triggers_array.php create mode 100755 tests/include/workflow/testfiles/workflow/workflow.php create mode 100755 tests/install/QuotesSeedDataTest.php create mode 100755 tests/modules/Administration/Bug36978Test.php create mode 100755 tests/modules/Administration/UpgradeHistoryTest.php create mode 100755 tests/modules/Calendar/Bug20626Test.php create mode 100755 tests/modules/Calls/Bug39161Test.php create mode 100755 tests/modules/Calls/CallHelperTest.php create mode 100755 tests/modules/CampaignLog/CampaignLogTest.php create mode 100755 tests/modules/CampaignTrackers/CampaignTrackersTest.php create mode 100755 tests/modules/Campaigns/Bug35014Test.php create mode 100755 tests/modules/Campaigns/Bug40233Test.php create mode 100755 tests/modules/Configurator/ConfiguratorTest.php create mode 100755 tests/modules/Contacts/Bug15255Test.php create mode 100755 tests/modules/Contacts/Bug7825Test.php create mode 100755 tests/modules/DynamicFields/Bug24095Test.php create mode 100755 tests/modules/DynamicFields/Bug39766Test.php create mode 100755 tests/modules/DynamicFields/RepairCustomFieldsTest.php create mode 100755 tests/modules/DynamicFields/URLFieldTest.php create mode 100755 tests/modules/EmailAddresses/EmailAddressTest.php create mode 100755 tests/modules/Emails/Bug32489Test.php create mode 100755 tests/modules/Emails/Bug40527Test.php create mode 100755 tests/modules/Emails/ComposePackageTest.php create mode 100755 tests/modules/Emails/EmailTest.php create mode 100755 tests/modules/Emails/EmailUITest.php create mode 100755 tests/modules/Emails/FindEmailFromBeanIdsTest.php create mode 100755 tests/modules/Emails/HandleBodyInHTMLformatTest.php create mode 100755 tests/modules/Home/QuickSearchTests.php create mode 100755 tests/modules/Home/UnifiedSearchAdvancedTest.php create mode 100755 tests/modules/Import/Bug39494ImportFile.txt create mode 100755 tests/modules/Import/ImportCacheFilesTest.php create mode 100755 tests/modules/Import/ImportDuplicateCheckTest.php create mode 100755 tests/modules/Import/ImportFieldSanitizeTest.php create mode 100755 tests/modules/Import/ImportFileSplitterTest.php create mode 100755 tests/modules/Import/ImportFileTest.php create mode 100755 tests/modules/Import/ImportFormsTest.php create mode 100755 tests/modules/Import/ImportMapTest.php create mode 100755 tests/modules/Import/UsersLastImportTest.php create mode 100755 tests/modules/InboundEmail/AutoCreateImportFolderTest.php create mode 100755 tests/modules/InboundEmail/InboundEmailTest.php create mode 100755 tests/modules/Leads/ConvertLeadTests.php create mode 100755 tests/modules/ModuleBuilder/Module/StudioModuleTest.php create mode 100755 tests/modules/ModuleBuilder/parsers/AbstractMetaDataParserTest.php create mode 100755 tests/modules/ModuleBuilder/views/ViewListVIewTest.php create mode 100755 tests/modules/MySettings/StoreQueryTest.php create mode 100755 tests/modules/Notes/NotesTest.php create mode 100755 tests/modules/Tasks/TasksTest.php create mode 100755 tests/modules/Trackers/Bug40019_Test.php create mode 100755 tests/modules/Trackers/TrackerCreateDefaultUserTest.php create mode 100755 tests/modules/Trackers/TrackerManagerTest.php create mode 100755 tests/modules/Trackers/TrackerMetricsTest.php create mode 100755 tests/modules/Trackers/TrackerMonitorTest.php create mode 100755 tests/modules/Trackers/TrackerReportsUsageTest.php create mode 100755 tests/modules/Trackers/TrackerSaveTest.php create mode 100755 tests/modules/Trackers/TrackerTestUtility.php create mode 100755 tests/modules/Trackers/TrackerUpgradeDashletTest.php create mode 100755 tests/modules/UpgradeWizard/Bug30709Test.php create mode 100755 tests/modules/UpgradeWizard/Bug30709_Part_2_Test.php create mode 100755 tests/modules/UpgradeWizard/Bug32003_Test.php create mode 100755 tests/modules/UpgradeWizard/Bug32382Test.php create mode 100755 tests/modules/UpgradeWizard/Bug42643Test.php create mode 100755 tests/modules/UpgradeWizard/SilentUpgradeSessionVarsTest.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/Bug36257Test.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/Bug36481Test.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/Bug37231Test.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/Bug37295Test.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/Bug37461Test.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/Bug37597Test.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/Bug37692Test.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/Bug37704Test.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/Bug37725Test.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/Bug37841Test.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/Bug37850Test.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/Bug37862Test.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/Bug37917Test.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/Bug37921Test.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/Bug39057Test.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/Bug39059Test.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/LeadsMergeTest.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/editviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/listviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/popupdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/quickcreatedefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/searchdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/editviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/listviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/popupdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/quickcreatedefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/searchdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/cit_metadata_files/554/modules/Leads/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/cit_metadata_files/custom/modules/Leads/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/metadata_files/520/modules/Quotes/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/metadata_files/550/modules/Contacts/metadata/editviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Contacts/metadata/editviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Contacts/metadata/searchdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Leads/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Leads/metadata/editviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Notes/metadata/searchdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/Contacts/metadata/editviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/Leads/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/Leads/metadata/editviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/Quotes/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/551/modules/Meetings/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/554/modules/Leads/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/554/modules/Opportunities/metadata/listviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/610/custom/modules/Accounts/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/610/oob/modules/Accounts/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Accounts/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Accounts/metadata/listviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Contacts/metadata/editviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Contacts/metadata/searchdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Leads/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Meetings/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Notes/metadata/searchdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Opportunities/metadata/listviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Project/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Project/metadata/editviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/editviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/listviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/searchdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Contacts/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Contacts/metadata/editviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Opportunities/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Opportunities/metadata/editviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Opportunities/metadata/searchdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Accounts/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Accounts/metadata/editviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Accounts/metadata/listviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Accounts/metadata/searchdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Contacts/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Contacts/metadata/editviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Opportunities/metadata/detailviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Opportunities/metadata/editviewdefs.php create mode 100755 tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Opportunities/metadata/searchdefs.php create mode 100755 tests/modules/Users/UserTest.php create mode 100755 tests/phpuc.xml create mode 100755 tests/phpunit.bat create mode 100755 tests/phpunit.php create mode 100755 tests/phpunit.xml create mode 100755 tests/service/APIv3Helper.php create mode 100755 tests/service/Bug39234Test.php create mode 100755 tests/service/Bug39855Test.php create mode 100755 tests/service/Bug40250Test.php create mode 100755 tests/service/Bug42683Test.php create mode 100755 tests/service/RESTAPI3Test.php create mode 100755 tests/service/SOAPAPI1Test.php create mode 100755 tests/service/SOAPAPI2Test.php create mode 100755 tests/service/SOAPAPI3Test.php create mode 100755 tests/service/SOAPTestCase.php create mode 100755 tests/tests/SugarTestImportUtilitiesTest.php create mode 100755 tests/tests/SugarTestLangPackCreatorTest.php create mode 100755 tests/tests/SugarTestThemeUtilitiesTest.php create mode 100755 tests/tests/SugarTestUserUtilitiesTest.php diff --git a/tests/ModuleInstall/Bug41829Test.php b/tests/ModuleInstall/Bug41829Test.php new file mode 100755 index 00000000..35f5802c --- /dev/null +++ b/tests/ModuleInstall/Bug41829Test.php @@ -0,0 +1,41 @@ +module_installer = new ModuleInstaller(); + $this->module_installer->silent = true; + $this->module_installer->base_dir = ''; + $this->module_installer->id_name = 'Bug41829Test'; + $this->module_installer->installdefs['dcaction'] = array( + array( + 'from' => '/dcaction_file.php', + ), + ); + $this->log = $GLOBALS['log']; + $GLOBALS['log'] = new SugarMockLogger(); + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + $GLOBALS['log'] = $this->log; + } + + public function testWarningOnUninstallDCActions() + { + $this->module_installer->uninstall_dcactions(); + + $this->assertTrue(in_array('DEBUG: Uninstalling DCActions ...' . str_replace('', $this->module_installer->base_dir, $this->module_installer->installdefs['dcaction'][0]['from']), $GLOBALS['log']->messages)); + } + + +} diff --git a/tests/ModuleInstall/ModuleScannerTest.php b/tests/ModuleInstall/ModuleScannerTest.php new file mode 100755 index 00000000..4191436f --- /dev/null +++ b/tests/ModuleInstall/ModuleScannerTest.php @@ -0,0 +1,80 @@ +fileLoc = "cache/moduleScannerTemp.php"; + } + + public function tearDown() + { + if (is_file($this->fileLoc)) + unlink($this->fileLoc); + } + + public function testFileTemplatePass() + { + + $fileModContents = <<file = new File(); + \$file = "file"; + } +} +?> +EOQ; + file_put_contents($this->fileLoc, $fileModContents); + $ms = new ModuleScanner(); + $errors = $ms->scanFile($this->fileLoc); + $this->assertTrue(empty($errors)); + } + + public function testFileFunctionFail() + { + + $fileModContents = <<file = new File(); + \$file = file('test.php'); + + } +} +?> +EOQ; + file_put_contents($this->fileLoc, $fileModContents); + $ms = new ModuleScanner(); + $errors = $ms->scanFile($this->fileLoc); + $this->assertTrue(!empty($errors)); + } + + public function testCallUserFunctionFail() + { + + $fileModContents = << +EOQ; + file_put_contents($this->fileLoc, $fileModContents); + $ms = new ModuleScanner(); + $errors = $ms->scanFile($this->fileLoc); + $this->assertTrue(!empty($errors)); + } + + + +} diff --git a/tests/ModuleInstall/PackageManager/Bug39980Test.php b/tests/ModuleInstall/PackageManager/Bug39980Test.php new file mode 100755 index 00000000..62d63db9 --- /dev/null +++ b/tests/ModuleInstall/PackageManager/Bug39980Test.php @@ -0,0 +1,101 @@ +extractManifest(0, 0); + $packs = $pm->getinstalledPackages(); + //Its confusing, but "UNINSTALLABLE" in file_install means the package is NOT uninstallable + $this->assertEquals("UNINSTALLABLE", $packs[0]['file_install']); + } + +} + +class Bug39980PackageManger extends PackageManager { + static $manifest_location = "cache/Bug39980manifest.php"; + + public function __construct() { + parent::__construct(); + $this->manifest_content = << + array ( + '6.1.0' + ), + 'acceptable_sugar_flavors' => + array( + 'ENT' + ), + 'readme'=>'', + 'key'=>'tf1', + 'author' => '', + 'description' => '', + 'icon' => '', + 'is_uninstallable' => false, + 'name' => 'test_file_1', + 'published_date' => '2010-10-20 22:10:01', + 'type' => 'module', + 'version' => '1287612601', + 'remove_tables' => 'prompt', + ); +\$installdefs = array ( + 'id' => 'asdfqq', + 'copy' => + array ( + 0 => array ( + 'from' => '/Extension/modules/Cases/Ext/Vardefs/dummy_extension2.php', + 'to' => 'custom/Extension/modules/Cases/Ext/Vardefs/dummy_extension2.php', + ), + ), +); + +EOQ; + } + + public function getInstalled($types) + { + include($this->extractManifest(0,0)); + $sm = array( + 'manifest' => (isset($manifest) ? $manifest : ''), + 'installdefs' => (isset($installdefs) ? $installdefs : ''), + 'upgrade_manifest' => (isset($upgrade_manifest) ? $upgrade_manifest : '') + ); + return array ( + (object) array( + 'filename' => Bug39980PackageManger::$manifest_location, + 'manifest' => base64_encode(serialize($sm)), + 'date_entered' => '1/1/2010', + 'new_schema' => '1', + 'module_dir' => 'Administration' , + 'id' => 'b4d22740-4e96-65b3-b712-4ca230d95987' , + 'md5sum' => 'fe221d731d8c624f15712878300aa907' , + 'type' => 'module' , + 'version' => '1285697780' , + 'status' => 'installed' , + 'name' => 'test_file_1' , + 'description' => '' , + 'id_name' => 'tf1' , + 'enabled' => true , + ) + ); + } + + public function extractManifest($filename, $base_tmp_upgrade_dir) + { + if (!is_file(Bug39980PackageManger::$manifest_location)) + file_put_contents(Bug39980PackageManger::$manifest_location, $this->manifest_content); + + return Bug39980PackageManger::$manifest_location; + } +} \ No newline at end of file diff --git a/tests/PHPUnit/Extensions/Database/AbstractTester.php b/tests/PHPUnit/Extensions/Database/AbstractTester.php new file mode 100755 index 00000000..96a1fd0c --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/AbstractTester.php @@ -0,0 +1,206 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/ITester.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Can be used as a foundation for new DatabaseTesters. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +abstract class PHPUnit_Extensions_Database_AbstractTester implements PHPUnit_Extensions_Database_ITester +{ + + /** + * @var PHPUnit_Extensions_Database_Operation_IDatabaseOperation + */ + protected $setUpOperation; + + /** + * @var PHPUnit_Extensions_Database_Operation_IDatabaseOperation + */ + protected $tearDownOperation; + + /** + * @var PHPUnit_Extensions_Database_DataSet_IDataSet + */ + protected $dataSet; + + /** + * @var string + */ + protected $schema; + + /** + * Creates a new database tester. + * + * @param PHPUnit_Extensions_Database_DB_IDatabaseConnection $databaseConnection + */ + public function __construct() + { + $this->setUpOperation = PHPUnit_Extensions_Database_Operation_Factory::CLEAN_INSERT(); + $this->tearDownOperation = PHPUnit_Extensions_Database_Operation_Factory::NONE(); + } + + /** + * Closes the specified connection. + * + * @param PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection + */ + public function closeConnection(PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection) + { + $connection->close(); + } + + /** + * Returns the test dataset. + * + * @return PHPUnit_Extensions_Database_DataSet_IDataSet + */ + public function getDataSet() + { + return $this->dataSet; + } + + /** + * TestCases must call this method inside setUp(). + */ + public function onSetUp() + { + $this->getSetUpOperation()->execute($this->getConnection(), $this->getDataSet()); + } + + /** + * TestCases must call this method inside tearDown(). + */ + public function onTearDown() + { + $this->getTearDownOperation()->execute($this->getConnection(), $this->getDataSet()); + } + + /** + * Sets the test dataset to use. + * + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet + */ + public function setDataSet(PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet) + { + $this->dataSet = $dataSet; + } + + /** + * Sets the schema value. + * + * @param string $schema + */ + public function setSchema($schema) + { + $this->schema = $schema; + } + + /** + * Sets the DatabaseOperation to call when starting the test. + * + * @param PHPUnit_Extensions_Database_Operation_DatabaseOperation $setUpOperation + */ + public function setSetUpOperation(PHPUnit_Extensions_Database_Operation_IDatabaseOperation $setUpOperation) + { + $this->setUpOperation = $setUpOperation; + } + + /** + * Sets the DatabaseOperation to call when ending the test. + * + * @param PHPUnit_Extensions_Database_Operation_DatabaseOperation $tearDownOperation + */ + public function setTearDownOperation(PHPUnit_Extensions_Database_Operation_IDatabaseOperation $tearDownOperation) + { + $this->tearDownOperation = $tearDownOperation; + } + + /** + * Returns the schema value + * + * @return string + */ + protected function getSchema() + { + return $this->schema; + } + + /** + * Returns the database operation that will be called when starting the test. + * + * @return PHPUnit_Extensions_Database_Operation_DatabaseOperation + */ + protected function getSetUpOperation() + { + return $this->setUpOperation; + } + + /** + * Returns the database operation that will be called when ending the test. + * + * @return PHPUnit_Extensions_Database_Operation_DatabaseOperation + */ + protected function getTearDownOperation() + { + return $this->tearDownOperation; + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/Constraint/DataSetIsEqual.php b/tests/PHPUnit/Extensions/Database/Constraint/DataSetIsEqual.php new file mode 100755 index 00000000..f10f8453 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/Constraint/DataSetIsEqual.php @@ -0,0 +1,132 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/Constraint.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Asserts whether or not two dbunit datasets are equal. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_Constraint_DataSetIsEqual extends PHPUnit_Framework_Constraint +{ + + /** + * @var PHPUnit_Extensions_Database_DataSet_IDataSet + */ + protected $value; + + /** + * @var string + */ + protected $failure_reason; + + /** + * Creates a new constraint. + * + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $value + */ + public function __construct(PHPUnit_Extensions_Database_DataSet_IDataSet $value) + { + $this->value = $value; + } + + /** + * Determines whether or not the given dataset matches the dataset used to + * create this constraint. + * + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $other + * @return bool + */ + public function evaluate($other) + { + if ($other instanceof PHPUnit_Extensions_Database_DataSet_IDataSet) { + try { + $this->value->assertEquals($other); + return TRUE; + } catch (Exception $e) { + $this->failure_reason = $e->getMessage(); + return FALSE; + } + } else { + throw new InvalidArgumentException("PHPUnit_Extensions_Database_DataSet_IDataSet expected"); + } + } + + protected function customFailureDescription($other, $description, $not) + { + return sprintf( + 'Failed asserting that actual %s %s Reason: %s', + + $other->__toString(), + $this->toString(), + $this->failure_reason + ); + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + return sprintf('is equal to expected %s', + $this->value->__toString()); + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/Constraint/TableIsEqual.php b/tests/PHPUnit/Extensions/Database/Constraint/TableIsEqual.php new file mode 100755 index 00000000..a06a65ba --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/Constraint/TableIsEqual.php @@ -0,0 +1,133 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/Constraint.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Asserts whether or not two dbunit tables are equal. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_Constraint_TableIsEqual extends PHPUnit_Framework_Constraint +{ + + /** + * @var PHPUnit_Extensions_Database_DataSet_ITable + */ + protected $value; + + /** + * @var string + */ + protected $failure_reason; + + /** + * Creates a new constraint. + * + * @param PHPUnit_Extensions_Database_DataSet_ITable $value + */ + public function __construct(PHPUnit_Extensions_Database_DataSet_ITable $value) + { + $this->value = $value; + } + + /** + * Determines whether or not the given table matches the table used to + * create this constraint. + * + * @param PHPUnit_Extensions_Database_DataSet_ITable $other + * @return bool + */ + public function evaluate($other) + { + if ($other instanceof PHPUnit_Extensions_Database_DataSet_ITable) { + try { + $this->value->assertEquals($other); + return TRUE; + } catch (Exception $e) { + $this->failure_reason = $e->getMessage(); + return FALSE; + } + } else { + throw new InvalidArgumentException("PHPUnit_Extensions_Database_DataSet_ITable expected"); + } + } + + protected function customFailureDescription($other, $description, $not) + { + return sprintf( + 'Failed asserting that actual %s %s Reason: %s', + + $other->__toString(), + $this->toString(), + $this->failure_reason + ); + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + return sprintf('is equal to expected %s', + + PHPUnit_Util_Type::toString($this->value)); + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DB/DataSet.php b/tests/PHPUnit/Extensions/Database/DB/DataSet.php new file mode 100755 index 00000000..669fad06 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DB/DataSet.php @@ -0,0 +1,174 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/AbstractDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php'; +require_once 'PHPUnit/Extensions/Database/DB/TableIterator.php'; +require_once 'PHPUnit/Extensions/Database/DB/Table.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides access to a database instance as a data set. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DB_DataSet extends PHPUnit_Extensions_Database_DataSet_AbstractDataSet +{ + + /** + * An array of ITable objects. + * + * @var array + */ + protected $tables = array(); + + /** + * The database connection this dataset is using. + * + * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection + */ + protected $databaseConnection; + + /** + * Creates a new dataset using the given database connection. + * + * @param PHPUnit_Extensions_Database_DB_IDatabaseConnection $databaseConnection + */ + public function __construct(PHPUnit_Extensions_Database_DB_IDatabaseConnection $databaseConnection) + { + $this->databaseConnection = $databaseConnection; + } + + /** + * Creates the query necessary to pull all of the data from a table. + * + * @param PHPUnit_Extensions_Database_DataSet_ITableMetaData $tableMetaData + * @return unknown + */ + public static function buildTableSelect(PHPUnit_Extensions_Database_DataSet_ITableMetaData $tableMetaData) + { + if ($tableMetaData->getTableName() == '') { + $e = new Exception("Empty Table Name"); + echo $e->getTraceAsString(); + throw $e; + } + + $columnList = implode(', ', $tableMetaData->getColumns()); + + $primaryKeys = $tableMetaData->getPrimaryKeys(); + if (count($primaryKeys)) { + $orderBy = 'ORDER BY ' . implode(' ASC, ', $primaryKeys) . ' ASC'; + } else { + $orderBy = ''; + } + + return "SELECT {$columnList} FROM {$tableMetaData->getTableName()} {$orderBy}"; + } + + /** + * Creates an iterator over the tables in the data set. If $reverse is + * true a reverse iterator will be returned. + * + * @param bool $reverse + * @return PHPUnit_Extensions_Database_DB_TableIterator + */ + protected function createIterator($reverse = FALSE) + { + return new PHPUnit_Extensions_Database_DB_TableIterator($this->getTableNames(), $this, $reverse); + } + + /** + * Returns a table object for the given table. + * + * @param string $tableName + * @return PHPUnit_Extensions_Database_DB_Table + */ + public function getTable($tableName) + { + if (!in_array($tableName, $this->getTableNames())) { + throw new InvalidArgumentException("$tableName is not a table in the current database."); + } + + if (empty($this->tables[$tableName])) { + $this->tables[$tableName] = new PHPUnit_Extensions_Database_DB_Table($this->getTableMetaData($tableName), $this->databaseConnection); + } + + return $this->tables[$tableName]; + } + + /** + * Returns a table meta data object for the given table. + * + * @param string $tableName + * @return PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData + */ + public function getTableMetaData($tableName) + { + return new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData($tableName, $this->databaseConnection->getMetaData()->getTableColumns($tableName), $this->databaseConnection->getMetaData()->getTablePrimaryKeys($tableName)); + } + + /** + * Returns a list of table names for the database + * + * @return Array + */ + public function getTableNames() + { + return $this->databaseConnection->getMetaData()->getTableNames(); + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DB/DefaultDatabaseConnection.php b/tests/PHPUnit/Extensions/Database/DB/DefaultDatabaseConnection.php new file mode 100755 index 00000000..05e569f7 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DB/DefaultDatabaseConnection.php @@ -0,0 +1,232 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/QueryTable.php'; +require_once 'PHPUnit/Extensions/Database/DB/IDatabaseConnection.php'; +require_once 'PHPUnit/Extensions/Database/DB/MetaData.php'; +require_once 'PHPUnit/Extensions/Database/DB/ResultSetTable.php'; +require_once 'PHPUnit/Extensions/Database/DB/DataSet.php'; +require_once 'PHPUnit/Extensions/Database/DB/FilteredDataSet.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides a basic interface for communicating with a database. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DB_DefaultDatabaseConnection implements PHPUnit_Extensions_Database_DB_IDatabaseConnection +{ + /** + * @var PDO + */ + protected $connection; + + /** + * @var string + */ + protected $schema; + + /** + * The metadata object used to retrieve table meta data from the database. + * + * @var PHPUnit_Extensions_Database_DB_IMetaData + */ + protected $metaData; + + /** + * Creates a new database connection + * + * @param PDO $connection + * @param string $schema - The name of the database schema you will be testing against. + */ + public function __construct(PDO $connection, $schema) + { + $this->connection = $connection; + $this->metaData = PHPUnit_Extensions_Database_DB_MetaData::createMetaData($connection, $schema); + $this->schema = $schema; + + $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + } + + /** + * Close this connection. + */ + public function close() + { + unset($this->connection); + } + + /** + * Returns a database metadata object that can be used to retrieve table + * meta data from the database. + * + * @return PHPUnit_Extensions_Database_DB_IMetaData + */ + public function getMetaData() + { + return $this->metaData; + } + + /** + * Returns the schema for the connection. + * + * @return string + */ + public function getSchema() + { + return $this->schema; + } + + /** + * Creates a dataset containing the specified table names. If no table + * names are specified then it will created a dataset over the entire + * database. + * + * @param array $tableNames + * @return PHPUnit_Extensions_Database_DataSet_IDataSet + * @todo Implement the filtered data set. + */ + public function createDataSet(Array $tableNames = NULL) + { + if (empty($tableNames)) { + return new PHPUnit_Extensions_Database_DB_DataSet($this); + } else { + return new PHPUnit_Extensions_Database_DB_FilteredDataSet($this, $tableNames); + } + } + + /** + * Creates a table with the result of the specified SQL statement. + * + * @param string $resultName + * @param string $sql + * @return PHPUnit_Extensions_Database_DB_Table + */ + public function createQueryTable($resultName, $sql) + { + return new PHPUnit_Extensions_Database_DataSet_QueryTable($resultName, $sql, $this); + } + + /** + * Returns this connection database configuration + * + * @return PHPUnit_Extensions_Database_Database_DatabaseConfig + */ + public function getConfig() + { + + } + + /** + * Returns a PDO Connection + * + * @return PDO + */ + public function getConnection() + { + return $this->connection; + } + + /** + * Returns the number of rows in the given table. You can specify an + * optional where clause to return a subset of the table. + * + * @param string $tableName + * @param string $whereClause + * @param int + */ + public function getRowCount($tableName, $whereClause = NULL) + { + $query = "SELECT COUNT(*) FROM {$tableName}"; + + if (isset($whereClause)) { + $query .= " WHERE {$whereClause}"; + } + } + + /** + * Returns a quoted schema object. (table name, column name, etc) + * + * @param string $object + * @return string + */ + public function quoteSchemaObject($object) + { + return $this->getMetaData()->quoteSchemaObject($object); + } + + /** + * Returns the command used to truncate a table. + * + * @return string + */ + public function getTruncateCommand() + { + return $this->getMetaData()->getTruncateCommand(); + } + + /** + * Returns true if the connection allows cascading + * + * @return bool + */ + public function allowsCascading() + { + return $this->getMetaData()->allowsCascading(); + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DB/FilteredDataSet.php b/tests/PHPUnit/Extensions/Database/DB/FilteredDataSet.php new file mode 100755 index 00000000..9e489433 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DB/FilteredDataSet.php @@ -0,0 +1,95 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DB/DataSet.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides access to a database instance as a data set. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DB_FilteredDataSet extends PHPUnit_Extensions_Database_DB_DataSet +{ + + /** + * @var Array + */ + protected $tableNames; + + /** + * Creates a new dataset using the given database connection. + * + * @param PHPUnit_Extensions_Database_DB_IDatabaseConnection $databaseConnection + */ + public function __construct(PHPUnit_Extensions_Database_DB_IDatabaseConnection $databaseConnection, Array $tableNames) + { + parent::__construct($databaseConnection); + $this->tableNames = $tableNames; + } + + /** + * Returns a list of table names for the database + * + * @return Array + */ + public function getTableNames() + { + return $this->tableNames; + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DB/IDatabaseConnection.php b/tests/PHPUnit/Extensions/Database/DB/IDatabaseConnection.php new file mode 100755 index 00000000..276f7ef5 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DB/IDatabaseConnection.php @@ -0,0 +1,145 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides a basic interface for communicating with a database. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +interface PHPUnit_Extensions_Database_DB_IDatabaseConnection +{ + + /** + * Close this connection. + */ + public function close(); + + /** + * Creates a dataset containing the specified table names. If no table + * names are specified then it will created a dataset over the entire + * database. + * + * @param array $tableNames + * @return PHPUnit_Extensions_Database_DataSet_IDataSet + */ + public function createDataSet(Array $tableNames = NULL); + + /** + * Creates a table with the result of the specified SQL statement. + * + * @param string $resultName + * @param string $sql + * @return PHPUnit_Extensions_Database_DataSet_ITable + */ + public function createQueryTable($resultName, $sql); + + /** + * Returns a PDO Connection + * + * @return PDO + */ + public function getConnection(); + + /** + * Returns a database metadata object that can be used to retrieve table + * meta data from the database. + * + * @return PHPUnit_Extensions_Database_DB_IMetaData + */ + public function getMetaData(); + + /** + * Returns the number of rows in the given table. You can specify an + * optional where clause to return a subset of the table. + * + * @param string $tableName + * @param string $whereClause + * @param int + */ + public function getRowCount($tableName, $whereClause = NULL); + + /** + * Returns the schema for the connection. + * + * @return string + */ + public function getSchema(); + + /** + * Returns a quoted schema object. (table name, column name, etc) + * + * @param string $object + * @return string + */ + public function quoteSchemaObject($object); + + /** + * Returns the command used to truncate a table. + * + * @return string + */ + public function getTruncateCommand(); + + /** + * Returns true if the connection allows cascading + * + * @return bool + */ + public function allowsCascading(); +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DB/IMetaData.php b/tests/PHPUnit/Extensions/Database/DB/IMetaData.php new file mode 100755 index 00000000..bff394f4 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DB/IMetaData.php @@ -0,0 +1,114 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides a basic interface for retreiving metadata from a database. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +interface PHPUnit_Extensions_Database_DB_IMetaData +{ + + /** + * Returns an array containing the names of all the tables in the database. + * + * @return array + */ + public function getTableNames(); + + /** + * Returns an array containing the names of all the columns in the + * $tableName table, + * + * @param string $tableName + * @return array + */ + public function getTableColumns($tableName); + + /** + * Returns an array containing the names of all the primary key columns in + * the $tableName table. + * + * @param string $tableName + * @return array + */ + public function getTablePrimaryKeys($tableName); + + /** + * Returns the name of the default schema. + * + * @return string + */ + public function getSchema(); + + /** + * Returns a quoted schema object. (table name, column name, etc) + * + * @param string $object + * @return string + */ + public function quoteSchemaObject($object); + + /** + * Returns true if the rdbms allows cascading + * + * @return bool + */ + public function allowsCascading(); +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DB/MetaData.php b/tests/PHPUnit/Extensions/Database/DB/MetaData.php new file mode 100755 index 00000000..d2b3087c --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DB/MetaData.php @@ -0,0 +1,215 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Extensions/Database/DB/IMetaData.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides a basic constructor for all meta data classes and a factory for + * generating the appropriate meta data class. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +abstract class PHPUnit_Extensions_Database_DB_MetaData implements PHPUnit_Extensions_Database_DB_IMetaData +{ + protected static $metaDataClassMap = array( + 'pgsql' => 'PHPUnit_Extensions_Database_DB_MetaData_PgSQL', + 'mysql' => 'PHPUnit_Extensions_Database_DB_MetaData_MySQL', + 'oci' => 'PHPUnit_Extensions_Database_DB_MetaData_Oci', + 'sqlite' => 'PHPUnit_Extensions_Database_DB_MetaData_Sqlite' + ); + + /** + * The PDO connection used to retreive database meta data + * + * @var PDO + */ + protected $pdo; + + /** + * The default schema name for the meta data object. + * + * @var string + */ + protected $schema; + + /** + * The character used to quote schema objects. + */ + protected $schemaObjectQuoteChar = '"'; + + /** + * The command used to perform a TRUNCATE operation. + */ + protected $truncateCommand = 'TRUNCATE'; + + /** + * Creates a new database meta data object using the given pdo connection + * and schema name. + * + * @param PDO $pdo + * @param string $schema + */ + public final function __construct(PDO $pdo, $schema) + { + $this->pdo = $pdo; + $this->schema = $schema; + } + + /** + * Creates a meta data object based on the driver of given $pdo object and + * $schema name. + * + * @param PDO $pdo + * @param string $schema + * @return PHPUnit_Extensions_Database_DB_MetaData + */ + public static function createMetaData(PDO $pdo, $schema) + { + $driverName = $pdo->getAttribute(PDO::ATTR_DRIVER_NAME); + if (isset(self::$metaDataClassMap[$driverName])) { + $className = self::$metaDataClassMap[$driverName]; + + if ($className instanceof ReflectionClass) { + return $className->newInstance($pdo, $schema); + } else { + return self::registerClassWithDriver($className, $driverName)->newInstance($pdo, $schema); + } + } else { + throw new Exception("Could not find a meta data driver for {$driverName} pdo driver."); + } + } + + /** + * Validates and registers the given $className with the given $pdoDriver. + * It should be noted that this function will not attempt to include / + * require the file. The $pdoDriver can be determined by the value of the + * PDO::ATTR_DRIVER_NAME attribute for a pdo object. + * + * A reflection of the $className is returned. + * + * @param string $className + * @param string $pdoDriver + * @return ReflectionClass + */ + public static function registerClassWithDriver($className, $pdoDriver) + { + if (!class_exists($className)) { + throw new Exception("Specified class for {$pdoDriver} driver ({$className}) does not exist."); + } + + $reflection = new ReflectionClass($className); + if ($reflection->isSubclassOf('PHPUnit_Extensions_Database_DB_MetaData')) { + return self::$metaDataClassMap[$pdoDriver] = $reflection; + } else { + throw new Exception("Specified class for {$pdoDriver} driver ({$className}) does not extend PHPUnit_Extensions_Database_DB_MetaData."); + } + } + + /** + * Returns the schema for the connection. + * + * @return string + */ + public function getSchema() + { + return $this->schema; + } + + /** + * Returns a quoted schema object. (table name, column name, etc) + * + * @param string $object + * @return string + */ + public function quoteSchemaObject($object) + { + return $this->schemaObjectQuoteChar. + str_replace($this->schemaObjectQuoteChar, $this->schemaObjectQuoteChar.$this->schemaObjectQuoteChar, $object). + $this->schemaObjectQuoteChar; + } + + /** + * Returns the command for the database to truncate a table. + * + * @return string + */ + public function getTruncateCommand() + { + return $this->truncateCommand; + } + + /** + * Returns true if the rdbms allows cascading + * + * @return bool + */ + public function allowsCascading() + { + return FALSE; + } +} + +/** + * I am not sure why these requires can't go above the class, but when they do + * the classes can't find the PHPUnit_Extensions_Database_DB_MetaData + * class. + */ +require_once 'PHPUnit/Extensions/Database/DB/MetaData/Sqlite.php'; +require_once 'PHPUnit/Extensions/Database/DB/MetaData/InformationSchema.php'; +require_once 'PHPUnit/Extensions/Database/DB/MetaData/MySQL.php'; +require_once 'PHPUnit/Extensions/Database/DB/MetaData/PgSQL.php'; +?> diff --git a/tests/PHPUnit/Extensions/Database/DB/MetaData/InformationSchema.php b/tests/PHPUnit/Extensions/Database/DB/MetaData/InformationSchema.php new file mode 100755 index 00000000..eae0c5c0 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DB/MetaData/InformationSchema.php @@ -0,0 +1,184 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Extensions/Database/DB/MetaData.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides functionality to retrieve meta data from a database with information_schema support. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DB_MetaData_InformationSchema extends PHPUnit_Extensions_Database_DB_MetaData +{ + + protected $columns = array(); + + protected $keys = array(); + + /** + * Returns an array containing the names of all the tables in the database. + * + * @return array + */ + public function getTableNames() + { + $query = " + SELECT DISTINCT + TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE + TABLE_TYPE='BASE TABLE' AND + TABLE_SCHEMA = ? + ORDER BY TABLE_NAME + "; + + $statement = $this->pdo->prepare($query); + $statement->execute(array($this->getSchema())); + + $tableNames = array(); + while ($tableName = $statement->fetchColumn(0)) { + $tableNames[] = $tableName; + } + + return $tableNames; + } + + /** + * Returns an array containing the names of all the columns in the + * $tableName table, + * + * @param string $tableName + * @return array + */ + public function getTableColumns($tableName) + { + if (!isset($this->columns[$tableName])) { + $this->loadColumnInfo($tableName); + } + + return $this->columns[$tableName]; + } + + /** + * Returns an array containing the names of all the primary key columns in + * the $tableName table. + * + * @param string $tableName + * @return array + */ + public function getTablePrimaryKeys($tableName) + { + if (!isset($this->keys[$tableName])) { + $this->loadColumnInfo($tableName); + } + + return $this->keys[$tableName]; + } + + /** + * Loads column info from a sqlite database. + * + * @param string $tableName + */ + protected function loadColumnInfo($tableName) + { + $this->columns[$tableName] = array(); + $this->keys[$tableName] = array(); + + $columnQuery = " + SELECT DISTINCT + COLUMN_NAME + FROM INFORMATION_SCHEMA.COLUMNS + WHERE + TABLE_NAME = ? AND + TABLE_SCHEMA = ? + ORDER BY ORDINAL_POSITION + "; + + $columnStatement = $this->pdo->prepare($columnQuery); + $columnStatement->execute(array($tableName, $this->getSchema())); + + while ($columName = $columnStatement->fetchColumn(0)) { + $this->columns[$tableName][] = $columName; + } + + $keyQuery = " + SELECT + KCU.COLUMN_NAME + FROM + INFORMATION_SCHEMA.TABLE_CONSTRAINTS as TC, + INFORMATION_SCHEMA.KEY_COLUMN_USAGE as KCU + WHERE + TC.CONSTRAINT_NAME = KCU.CONSTRAINT_NAME AND + TC.TABLE_NAME = KCU.TABLE_NAME AND + TC.TABLE_SCHEMA = KCU.TABLE_SCHEMA AND + TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND + TC.TABLE_NAME = ? AND + TC.TABLE_SCHEMA = ? + ORDER BY + KCU.ORDINAL_POSITION ASC + "; + + $keyStatement = $this->pdo->prepare($keyQuery); + $keyStatement->execute(array($tableName, $this->getSchema())); + + while ($columName = $keyStatement->fetchColumn(0)) { + $this->keys[$tableName][] = $columName; + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DB/MetaData/MySQL.php b/tests/PHPUnit/Extensions/Database/DB/MetaData/MySQL.php new file mode 100755 index 00000000..12093ea7 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DB/MetaData/MySQL.php @@ -0,0 +1,137 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Extensions/Database/DB/MetaData/InformationSchema.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides functionality to retrieve meta data from a database with information_schema support. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DB_MetaData_MySQL extends PHPUnit_Extensions_Database_DB_MetaData +{ + protected $schemaObjectQuoteChar = '`'; + + protected $columns = array(); + + protected $keys = array(); + + /** + * Returns an array containing the names of all the tables in the database. + * + * @return array + */ + public function getTableNames() + { + $query = 'SHOW TABLES'; + $statement = $this->pdo->prepare($query); + $statement->execute(); + + $tableNames = array(); + while (($tableName = $statement->fetchColumn(0))) { + $tableNames[] = $tableName; + } + + return $tableNames; + } + + /** + * Returns an array containing the names of all the columns in the + * $tableName table, + * + * @param string $tableName + * @return array + */ + public function getTableColumns($tableName) + { + $query = 'SHOW COLUMNS FROM `' . $tableName . '`'; + $statement = $this->pdo->prepare($query); + $statement->execute(); + + $columnNames = array(); + while (($columnName = $statement->fetchColumn(0))) { + $columnNames[] = $columnName; + } + + return $columnNames; + } + + /** + * Returns an array containing the names of all the primary key columns in + * the $tableName table. + * + * @param string $tableName + * @return array + */ + public function getTablePrimaryKeys($tableName) + { + $query = 'SHOW INDEX FROM `' . $tableName . '`'; + $statement = $this->pdo->prepare($query); + $statement->execute(); + $statement->setFetchMode(PDO::FETCH_ASSOC); + + $columnNames = array(); + while (($column = $statement->fetch())) { + if ($column['Key_name'] == 'PRIMARY') { + $columnNames[] = $column['Column_name']; + } + } + + return $columnNames; + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DB/MetaData/Oci.php b/tests/PHPUnit/Extensions/Database/DB/MetaData/Oci.php new file mode 100755 index 00000000..e239135b --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DB/MetaData/Oci.php @@ -0,0 +1,164 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Trond Hansen + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.3 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Extensions/Database/DB/MetaData.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides functionality to retrieve meta data from an Oracle database. + * + * @category Testing + * @package PHPUnit + * @author Trond Hansen + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.3 + */ +class PHPUnit_Extensions_Database_DB_MetaData_Oci extends PHPUnit_Extensions_Database_DB_MetaData +{ + /** + * No character used to quote schema objects. + */ + protected $schemaObjectQuoteChar = ''; + + protected $columns = array(); + protected $keys = array(); + + /** + * Returns an array containing the names of all the tables in the database. + * + * @return array + */ + public function getTableNames() + { + $tableNames = array(); + + $query = "SELECT table_name + FROM cat + WHERE table_type='TABLE' + ORDER BY table_name"; + + $result = $this->pdo->query($query); + + while ($tableName = $result->fetchColumn(0)) { + $tableNames[] = $tableName; + } + + return $tableNames; + } + + /** + * Returns an array containing the names of all the columns in the + * $tableName table, + * + * @param string $tableName + * @return array + */ + public function getTableColumns($tableName) + { + if (!isset($this->columns[$tableName])) { + $this->loadColumnInfo($tableName); + } + + return $this->columns[$tableName]; + } + + /** + * Returns an array containing the names of all the primary key columns in + * the $tableName table. + * + * @param string $tableName + * @return array + */ + public function getTablePrimaryKeys($tableName) + { + if (!isset($this->keys[$tableName])) { + $this->loadColumnInfo($tableName); + } + + return $this->keys[$tableName]; + } + + /** + * Loads column info from a oracle database. + * + * @param string $tableName + */ + protected function loadColumnInfo($tableName) + { + $this->columns[$tableName] = array(); + $this->keys[$tableName] = array(); + + $query = "SELECT DISTINCT COLUMN_NAME + FROM USER_TAB_COLUMNS + WHERE TABLE_NAME='".$tableName."' + ORDER BY COLUMN_NAME"; + + $result = $this->pdo->query($query); + + while ($columnName = $result->fetchColumn(0)) { + $this->columns[$tableName][] = $columnName; + } + + $keyQuery = "SELECT b.column_name + FROM user_constraints a, user_cons_columns b + WHERE a.constraint_type='P' + AND a.constraint_name=b.constraint_name + AND a.table_name = '".$tableName."' "; + + $result = $this->pdo->query($keyQuery); + + while ($columnName = $result->fetchColumn(0)) { + $this->keys[$tableName][] = $columnName; + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DB/MetaData/PgSQL.php b/tests/PHPUnit/Extensions/Database/DB/MetaData/PgSQL.php new file mode 100755 index 00000000..16a6b0a8 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DB/MetaData/PgSQL.php @@ -0,0 +1,164 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Extensions/Database/DB/MetaData/InformationSchema.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides functionality to retrieve meta data from a postgres database. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DB_MetaData_PgSQL extends PHPUnit_Extensions_Database_DB_MetaData_InformationSchema +{ + + /** + * Returns an array containing the names of all the tables in the database. + * + * @return array + */ + public function getTableNames() + { + $query = " + SELECT DISTINCT + TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE + TABLE_TYPE='BASE TABLE' AND + TABLE_CATALOG = ? AND + TABLE_SCHEMA = 'public' + ORDER BY TABLE_NAME + "; + + $statement = $this->pdo->prepare($query); + $statement->execute(array($this->getSchema())); + + $tableNames = array(); + while ($tableName = $statement->fetchColumn(0)) { + $tableNames[] = $tableName; + } + + return $tableNames; + } + + /** + * Loads column info from a sqlite database. + * + * @param string $tableName + */ + protected function loadColumnInfo($tableName) + { + $this->columns[$tableName] = array(); + $this->keys[$tableName] = array(); + + $columnQuery = " + SELECT DISTINCT + COLUMN_NAME, + ORDINAL_POSITION + FROM INFORMATION_SCHEMA.COLUMNS + WHERE + TABLE_NAME = ? AND + TABLE_SCHEMA = 'public' AND + TABLE_CATALOG = ? + ORDER BY ORDINAL_POSITION + "; + + $columnStatement = $this->pdo->prepare($columnQuery); + $columnStatement->execute(array($tableName, $this->getSchema())); + + while ($columName = $columnStatement->fetchColumn(0)) { + $this->columns[$tableName][] = $columName; + } + + $keyQuery = " + SELECT + KCU.COLUMN_NAME, + KCU.ORDINAL_POSITION + FROM + INFORMATION_SCHEMA.TABLE_CONSTRAINTS as TC, + INFORMATION_SCHEMA.KEY_COLUMN_USAGE as KCU + WHERE + TC.CONSTRAINT_NAME = KCU.CONSTRAINT_NAME AND + TC.TABLE_NAME = KCU.TABLE_NAME AND + TC.TABLE_SCHEMA = KCU.TABLE_SCHEMA AND + TC.TABLE_CATALOG = KCU.TABLE_CATALOG AND + TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND + TC.TABLE_NAME = ? AND + TC.TABLE_SCHEMA = 'public' AND + TC.TABLE_CATALOG = ? + ORDER BY + KCU.ORDINAL_POSITION ASC + "; + + $keyStatement = $this->pdo->prepare($keyQuery); + $keyStatement->execute(array($tableName, $this->getSchema())); + + while ($columName = $keyStatement->fetchColumn(0)) { + $this->keys[$tableName][] = $columName; + } + } + + /** + * Returns true if the rdbms allows cascading + * + * @return bool + */ + public function allowsCascading() + { + return TRUE; + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DB/MetaData/Sqlite.php b/tests/PHPUnit/Extensions/Database/DB/MetaData/Sqlite.php new file mode 100755 index 00000000..e2688c04 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DB/MetaData/Sqlite.php @@ -0,0 +1,152 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Extensions/Database/DB/MetaData.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides functionality to retrieve meta data from a sqlite database. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DB_MetaData_Sqlite extends PHPUnit_Extensions_Database_DB_MetaData +{ + + protected $columns = array(); + + protected $keys = array(); + + protected $truncateCommand = 'DELETE FROM'; + /** + * Returns an array containing the names of all the tables in the database. + * + * @return array + */ + public function getTableNames() + { + $query = " + SELECT name + FROM sqlite_master + WHERE + type='table' AND + name <> 'sqlite_sequence' + ORDER BY name + "; + + $result = $this->pdo->query($query); + + while ($tableName = $result->fetchColumn(0)) { + $tableNames[] = $tableName; + } + + return $tableNames; + } + + /** + * Returns an array containing the names of all the columns in the + * $tableName table, + * + * @param string $tableName + * @return array + */ + public function getTableColumns($tableName) + { + if (!isset($this->columns[$tableName])) { + $this->loadColumnInfo($tableName); + } + + return $this->columns[$tableName]; + } + + /** + * Returns an array containing the names of all the primary key columns in + * the $tableName table. + * + * @param string $tableName + * @return array + */ + public function getTablePrimaryKeys($tableName) + { + if (!isset($this->keys[$tableName])) { + $this->loadColumnInfo($tableName); + } + + return $this->keys[$tableName]; + } + + /** + * Loads column info from a sqlite database. + * + * @param string $tableName + */ + protected function loadColumnInfo($tableName) + { + $query = "PRAGMA table_info('{$tableName}')"; + $statement = $this->pdo->query($query); + + /* @var $statement PDOStatement */ + $this->columns[$tableName] = array(); + $this->keys[$tableName] = array(); + while ($columnData = $statement->fetch(PDO::FETCH_NUM)) { + $this->columns[$tableName][] = $columnData[1]; + + if ($columnData[5] == 1) { + $this->keys[$tableName][] = $columnData[1]; + } + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DB/ResultSetTable.php b/tests/PHPUnit/Extensions/Database/DB/ResultSetTable.php new file mode 100755 index 00000000..d7aa2ac5 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DB/ResultSetTable.php @@ -0,0 +1,92 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +require_once 'PHPUnit/Extensions/Database/DataSet/AbstractTable.php'; + +/** + * Provides the functionality to represent a database result set as a DBUnit + * table. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @deprecated The PHPUnit_Extension_Database_DataSet_QueryTable should be used instead + * @see PHPUnit_Extension_Database_DataSet_QueryTable + * @see PHPUnit_Extension_Database_DataSet_QueryDataSet + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DB_ResultSetTable extends PHPUnit_Extensions_Database_DataSet_AbstractTable +{ + + /** + * Creates a new result set table. + * + * @param string $tableName + * @param PDOStatement $pdoStatement + */ + public function __construct($tableName, PDOStatement $pdoStatement) + { + $this->data = $pdoStatement->fetchAll(PDO::FETCH_ASSOC); + + if (count($this->data)) { + $columns = array_keys($this->data[0]); + } else { + $columns = array(); + } + + $this->setTableMetaData(new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData($tableName, $columns)); + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DB/Table.php b/tests/PHPUnit/Extensions/Database/DB/Table.php new file mode 100755 index 00000000..17946690 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DB/Table.php @@ -0,0 +1,84 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/AbstractTable.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides the functionality to represent a database table. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DB_Table extends PHPUnit_Extensions_Database_DataSet_AbstractTable +{ + + /** + * Creates a new database table object. + * + * @param PHPUnit_Extensions_Database_DataSet_ITableMetaData $tableMetaData + * @param PHPUnit_Extensions_Database_DB_IDatabaseConnection $databaseConnection + */ + public function __construct(PHPUnit_Extensions_Database_DataSet_ITableMetaData $tableMetaData, PHPUnit_Extensions_Database_DB_IDatabaseConnection $databaseConnection) + { + $this->setTableMetaData($tableMetaData); + + $pdoStatement = $databaseConnection->getConnection()->prepare(PHPUnit_Extensions_Database_DB_DataSet::buildTableSelect($tableMetaData)); + $pdoStatement->execute(); + $this->data = $pdoStatement->fetchAll(PDO::FETCH_ASSOC); + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DB/TableIterator.php b/tests/PHPUnit/Extensions/Database/DB/TableIterator.php new file mode 100755 index 00000000..293a2f17 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DB/TableIterator.php @@ -0,0 +1,176 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/ITableIterator.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides iterative access to tables from a database instance. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DB_TableIterator implements PHPUnit_Extensions_Database_DataSet_ITableIterator +{ + + /** + * An array of tablenames. + * + * @var Array + */ + protected $tableNames; + + /** + * If this property is true then the tables will be iterated in reverse + * order. + * + * @var bool + */ + protected $reverse; + + /** + * The database dataset that this iterator iterates over. + * + * @var PHPUnit_Extensions_Database_DB_DataSet + */ + protected $dataSet; + + public function __construct($tableNames, PHPUnit_Extensions_Database_DB_DataSet $dataSet, $reverse = FALSE) + { + $this->tableNames = $tableNames; + $this->dataSet = $dataSet; + $this->reverse = $reverse; + + $this->rewind(); + } + + /** + * Returns the current table. + * + * @return PHPUnit_Extensions_Database_DataSet_ITable + */ + public function getTable() + { + return $this->current(); + } + + /** + * Returns the current table's meta data. + * + * @return PHPUnit_Extensions_Database_DataSet_ITableMetaData + */ + public function getTableMetaData() + { + return $this->current()->getTableMetaData(); + } + + /** + * Returns the current table. + * + * @return PHPUnit_Extensions_Database_DataSet_ITable + */ + public function current() + { + $tableName = current($this->tableNames); + return $this->dataSet->getTable($tableName); + } + + /** + * Returns the name of the current table. + * + * @return string + */ + public function key() + { + return $this->current()->getTableMetaData()->getTableName(); + } + + /** + * advances to the next element. + * + */ + public function next() + { + if ($this->reverse) { + prev($this->tableNames); + } else { + next($this->tableNames); + } + } + + /** + * Rewinds to the first element + */ + public function rewind() + { + if ($this->reverse) { + end($this->tableNames); + } else { + reset($this->tableNames); + } + } + + /** + * Returns true if the current index is valid + * + * @return bool + */ + public function valid() + { + return (current($this->tableNames) !== FALSE); + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DB/TableMetaData.php b/tests/PHPUnit/Extensions/Database/DB/TableMetaData.php new file mode 100755 index 00000000..9b1976bc --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DB/TableMetaData.php @@ -0,0 +1,75 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * This class loads a table metadata object with database metadata. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DB_TableMetaData extends PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData +{ + + public function __construct($tableName, PHPUnit_Extensions_Database_DB_IMetaData $databaseMetaData) + { + $this->tableName = $tableName; + $this->columns = $databaseMetaData->getTableColumns($tableName); + $this->primaryKeys = $databaseMetaData->getTablePrimaryKeys($tableName); + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/AbstractDataSet.php b/tests/PHPUnit/Extensions/Database/DataSet/AbstractDataSet.php new file mode 100755 index 00000000..ef825b88 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/AbstractDataSet.php @@ -0,0 +1,178 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/IDataSet.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Implements the basic functionality of data sets. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +abstract class PHPUnit_Extensions_Database_DataSet_AbstractDataSet implements PHPUnit_Extensions_Database_DataSet_IDataSet +{ + + /** + * Creates an iterator over the tables in the data set. If $reverse is + * true a reverse iterator will be returned. + * + * @param bool $reverse + * @return PHPUnit_Extensions_Database_DataSet_ITableIterator + */ + protected abstract function createIterator($reverse = FALSE); + + /** + * Returns an array of table names contained in the dataset. + * + * @return array + */ + public function getTableNames() + { + $tableNames = array(); + + foreach ($this->getIterator() as $table) { + /* @var $table PHPUnit_Extensions_Database_DataSet_ITable */ + $tableNames[] = $table->getTableMetaData()->getTableName(); + } + + return $tableNames; + } + + /** + * Returns a table meta data object for the given table. + * + * @param string $tableName + * @return PHPUnit_Extensions_Database_DataSet_ITableMetaData + */ + public function getTableMetaData($tableName) + { + return $this->getTable($tableName)->getTableMetaData(); + } + + /** + * Returns a table object for the given table. + * + * @param string $tableName + * @return PHPUnit_Extensions_Database_DataSet_ITable + */ + public function getTable($tableName) + { + foreach ($this->getIterator() as $table) { + /* @var $table PHPUnit_Extensions_Database_DataSet_ITable */ + if ($table->getTableMetaData()->getTableName() == $tableName) { + return $table; + } + } + } + + /** + * Returns an iterator for all table objects in the given dataset. + * + * @return PHPUnit_Extensions_Database_DataSet_ITableIterator + */ + public function getIterator() + { + return $this->createIterator(); + } + + /** + * Returns a reverse iterator for all table objects in the given dataset. + * + * @return PHPUnit_Extensions_Database_DataSet_ITableIterator + */ + public function getReverseIterator() + { + return $this->createIterator(TRUE); + } + + /** + * Asserts that the given data set matches this data set. + * + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $other + */ + public function assertEquals(PHPUnit_Extensions_Database_DataSet_IDataSet $other) + { + $thisTableNames = $this->getTableNames(); + $otherTableNames = $other->getTableNames(); + + sort($thisTableNames); + sort($otherTableNames); + + if ($thisTableNames != $otherTableNames) { + throw new Exception("Expected following tables: " . implode(', ', $thisTableNames) . "; has columns: " . implode(', ', $otherTableNames)); + } + + foreach ($thisTableNames as $tableName) { + $this->getTable($tableName)->assertEquals($other->getTable($tableName)); + } + + return TRUE; + } + + public function __toString() + { + $iterator = $this->getIterator(); + + $dataSetString = ''; + foreach ($iterator as $table) { + $dataSetString .= $table->__toString(); + } + + return $dataSetString; + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/AbstractTable.php b/tests/PHPUnit/Extensions/Database/DataSet/AbstractTable.php new file mode 100755 index 00000000..450deeed --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/AbstractTable.php @@ -0,0 +1,218 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/ITable.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides a basic functionality for dbunit tables + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DataSet_AbstractTable implements PHPUnit_Extensions_Database_DataSet_ITable +{ + + /** + * @var PHPUnit_Extensions_Database_DataSet_ITableMetaData + */ + protected $tableMetaData; + + /** + * A 2-dimensional array containing the data for this table. + * + * @var array + */ + protected $data; + + /** + * Sets the metadata for this table. + * + * @param PHPUnit_Extensions_Database_DataSet_ITableMetaData $tableMetaData + * @deprecated + */ + protected function setTableMetaData(PHPUnit_Extensions_Database_DataSet_ITableMetaData $tableMetaData) + { + $this->tableMetaData = $tableMetaData; + } + + /** + * Returns the table's meta data. + * + * @return PHPUnit_Extensions_Database_DataSet_ITableMetaData + */ + public function getTableMetaData() + { + return $this->tableMetaData; + } + + /** + * Returns the number of rows in this table. + * + * @return int + */ + public function getRowCount() + { + return count($this->data); + } + + /** + * Returns the value for the given column on the given row. + * + * @param int $row + * @param int $column + * @todo reorganize this function to throw the exception first. + */ + public function getValue($row, $column) + { + if (isset($this->data[$row][$column])) { + return (string)$this->data[$row][$column]; + } else { + if (!in_array($column, $this->getTableMetaData()->getColumns()) || $this->getRowCount() <= $row) { + throw new InvalidArgumentException("The given row ({$row}) and column ({$column}) do not exist in table {$this->getTableMetaData()->getTableName()}"); + } else { + return NULL; + } + } + } + + /** + * Returns the an associative array keyed by columns for the given row. + * + * @param int $row + * @return array + */ + public function getRow($row) + { + if (isset($this->data[$row])) { + return $this->data[$row]; + } else { + if ($this->getRowCount() <= $row) { + throw new InvalidArgumentException("The given row ({$row}) does not exist in table {$this->getTableMetaData()->getTableName()}"); + } else { + return NULL; + } + } + } + + /** + * Asserts that the given table matches this table. + * + * @param PHPUnit_Extensions_Database_DataSet_ITable $other + */ + public function assertEquals(PHPUnit_Extensions_Database_DataSet_ITable $other) + { + $thisMetaData = $this->getTableMetaData(); + $otherMetaData = $other->getTableMetaData(); + + $thisMetaData->assertEquals($otherMetaData); + + if ($this->getRowCount() != $other->getRowCount()) { + throw new Exception("Expected row count of {$this->getRowCount()}, has a row count of {$other->getRowCount()}"); + } + + $columns = $thisMetaData->getColumns(); + for ($i = 0; $i < $this->getRowCount(); $i++) { + foreach ($columns as $columnName) { + if ($this->getValue($i, $columnName) != $other->getValue($i, $columnName)) { + throw new Exception("Expected value of {$this->getValue($i, $columnName)} for row {$i} column {$columnName}, has a value of {$other->getValue($i, $columnName)}"); + } + } + } + + return TRUE; + } + + public function __toString() + { + $columns = $this->getTableMetaData()->getColumns(); + + $lineSeperator = str_repeat('+----------------------', count($columns)) . "+\n"; + $lineLength = strlen($lineSeperator) - 1; + + $tableString = $lineSeperator; + $tableString .= '| ' . str_pad($this->getTableMetaData()->getTableName(), $lineLength - 4, ' ', STR_PAD_RIGHT) . " |\n"; + $tableString .= $lineSeperator; + $tableString .= $this->rowToString($columns); + $tableString .= $lineSeperator; + + for ($i = 0; $i < $this->getRowCount(); $i++) { + $values = array(); + foreach ($columns as $columnName) { + $values[] = $this->getValue($i, $columnName); + } + + $tableString .= $this->rowToString($values); + $tableString .= $lineSeperator; + } + + return "\n" . $tableString . "\n"; + } + + protected function rowToString(Array $row) + { + $rowString = ''; + foreach ($row as $value) { + if (is_null($value)) { + $value = 'NULL'; + } + $rowString .= '| ' . str_pad(substr($value, 0, 20), 20, ' ', STR_PAD_BOTH) . ' '; + } + + return $rowString . "|\n"; + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/AbstractTableMetaData.php b/tests/PHPUnit/Extensions/Database/DataSet/AbstractTableMetaData.php new file mode 100755 index 00000000..4ab612ed --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/AbstractTableMetaData.php @@ -0,0 +1,136 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/ITableMetaData.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides basic functionality for table meta data. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +abstract class PHPUnit_Extensions_Database_DataSet_AbstractTableMetaData implements PHPUnit_Extensions_Database_DataSet_ITableMetaData +{ + + /** + * The names of all columns in the table. + * + * @var Array + */ + protected $columns; + + /** + * The names of all the primary keys in the table. + * + * @var Array + */ + protected $primaryKeys; + + /** + * @var string + */ + protected $tableName; + + /** + * Returns the names of the columns in the table. + * + * @return array + */ + public function getColumns() + { + return $this->columns; + } + + /** + * Returns the names of the primary key columns in the table. + * + * @return array + */ + public function getPrimaryKeys() + { + return $this->primaryKeys; + } + + /** + * Returns the name of the table. + * + * @return string + */ + public function getTableName() + { + return $this->tableName; + } + + /** + * Asserts that the given tableMetaData matches this tableMetaData. + * + * @param PHPUnit_Extensions_Database_DataSet_ITableMetaData $other + */ + public function assertEquals(PHPUnit_Extensions_Database_DataSet_ITableMetaData $other) + { + if ($this->getTableName() != $other->getTableName()) { + throw new Exception("Expected table name of {$this->getTableName()}, has a name of {$other->getTableName()}"); + } + + if ($this->getColumns() != $other->getColumns()) { + throw new Exception("Expected following columns: " . implode(', ', $this->getColumns()) . "; has columns: " . implode(', ', $other->getColumns())); + } + + return TRUE; + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/AbstractXmlDataSet.php b/tests/PHPUnit/Extensions/Database/DataSet/AbstractXmlDataSet.php new file mode 100755 index 00000000..6528380a --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/AbstractXmlDataSet.php @@ -0,0 +1,150 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/AbstractDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableIterator.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTable.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * The default implementation of a data set. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +abstract class PHPUnit_Extensions_Database_DataSet_AbstractXmlDataSet extends PHPUnit_Extensions_Database_DataSet_AbstractDataSet +{ + + /** + * @var array + */ + protected $tables; + + /** + * @var SimpleXmlElement + */ + protected $xmlFileContents; + + /** + * Creates a new dataset using the given tables. + * + * @param array $tables + */ + public function __construct($xmlFile) + { + if (!is_file($xmlFile)) { + throw new InvalidArgumentException("Could not find xml file: {$xmlFile}"); + } + $this->xmlFileContents = @simplexml_load_file($xmlFile); + + if ($this->xmlFileContents === FALSE) { + throw new InvalidArgumentException("File is not valid xml: {$xmlFile}"); + } + + $tableColumns = array(); + $tableValues = array(); + + $this->getTableInfo($tableColumns, $tableValues); + $this->createTables($tableColumns, $tableValues); + } + + /** + * Reads the simple xml object and creates the appropriate tables and meta + * data for this dataset. + */ + protected abstract function getTableInfo(Array &$tableColumns, Array &$tableValues); + + protected function createTables(Array &$tableColumns, Array &$tableValues) + { + foreach ($tableValues as $tableName => $values) { + $table = $this->getOrCreateTable($tableName, $tableColumns[$tableName]); + foreach ($values as $value) { + $table->addRow($value); + } + } + } + + /** + * Returns the table with the matching name. If the table does not exist + * an empty one is created. + * + * @param string $tableName + * @return PHPUnit_Extensions_Database_DataSet_ITable + */ + protected function getOrCreateTable($tableName, $tableColumns) + { + if (empty($this->tables[$tableName])) { + $tableMetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData($tableName, $tableColumns); + $this->tables[$tableName] = new PHPUnit_Extensions_Database_DataSet_DefaultTable($tableMetaData); + } + + return $this->tables[$tableName]; + } + + /** + * Creates an iterator over the tables in the data set. If $reverse is + * true a reverse iterator will be returned. + * + * @param bool $reverse + * @return PHPUnit_Extensions_Database_DataSet_ITableIterator + */ + protected function createIterator($reverse = FALSE) + { + return new PHPUnit_Extensions_Database_DataSet_DefaultTableIterator($this->tables, $reverse); + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/CompositeDataSet.php b/tests/PHPUnit/Extensions/Database/DataSet/CompositeDataSet.php new file mode 100755 index 00000000..b99e04b3 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/CompositeDataSet.php @@ -0,0 +1,130 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/AbstractDataSet.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Creates Composite Datasets + * + * Allows for creating datasets from multiple sources (csv, query, xml, etc.) + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class PHPUnit_Extensions_Database_DataSet_CompositeDataSet extends PHPUnit_Extensions_Database_DataSet_AbstractDataSet +{ + protected $dataSets = array(); + + /** + * Creates a new Composite dataset + * + * You can pass in any data set that implements PHPUnit_Extensions_Database_DataSet_IDataSet + * + * @param string $delimiter + * @param string $enclosure + * @param string $escape + */ + public function __construct(Array $dataSets) + { + foreach ($dataSets as $dataSet) + { + $this->addDataSet($dataSet); + } + } + + /** + * Adds a new data set to the composite. + * + * The dataset may not define tables that already exist in the composite. + * + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet + */ + public function addDataSet(PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet) + { + foreach ($dataSet->getTableNames() as $tableName) + { + if (in_array($tableName, $this->getTableNames())) + { + throw new InvalidArgumentException("DataSet contains a table that already exists: {$tableName}"); + } + } + + $this->dataSets[] = $dataSet; + } + + /** + * Creates an iterator over the tables in the data set. If $reverse is + * true a reverse iterator will be returned. + * + * @param bool $reverse + * @return PHPUnit_Extensions_Database_DataSet_ITableIterator + */ + protected function createIterator($reverse = FALSE) + { + $iterator = new AppendIterator(); + + $dataSets = $reverse ? array_reverse($this->dataSets) : $this->dataSets; + + foreach ($dataSets as $dataSet) + { + /* @var $dataSet PHPUnit_Extensions_Database_DataSet_IDataSet */ + $dataSetIterator = $reverse ? $dataSet->getReverseIterator() : $dataSet->getIterator(); + $iterator->append($dataSetIterator); + } + return $iterator; + } +} +?> \ No newline at end of file diff --git a/tests/PHPUnit/Extensions/Database/DataSet/CsvDataSet.php b/tests/PHPUnit/Extensions/Database/DataSet/CsvDataSet.php new file mode 100755 index 00000000..424b49bd --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/CsvDataSet.php @@ -0,0 +1,158 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/AbstractDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableIterator.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTable.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Creates CsvDataSets. + * + * You can incrementally add CSV files as tables to your datasets + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class PHPUnit_Extensions_Database_DataSet_CsvDataSet extends PHPUnit_Extensions_Database_DataSet_AbstractDataSet +{ + protected $tables = array(); + protected $delimiter = ','; + protected $enclosure = '"'; + protected $escape = '"'; + + /** + * Creates a new CSV dataset + * + * You can pass in the parameters for how csv files will be read. + * + * @param string $delimiter + * @param string $enclosure + * @param string $escape + */ + public function __construct($delimiter = ',', $enclosure = '"', $escape = '"') + { + $this->delimiter = $delimiter; + $this->enclosure = $enclosure; + $this->escape = $escape; + } + + /** + * Adds a table to the dataset + * + * The table will be given the passed name. $csvFile should be a path to + * a valid csv file (based on the arguments passed to the constructor.) + * + * @param string $tableName + * @param string $csvFile + */ + public function addTable($tableName, $csvFile) + { + if (!is_file($csvFile)) { + throw new InvalidArgumentException("Could not find csv file: {$csvFile}"); + } + + if (!is_readable($csvFile)) { + throw new InvalidArgumentException("Could not read csv file: {$csvFile}"); + } + + $fh = fopen($csvFile, 'r'); + $columns = $this->getCsvRow($fh); + + if ($columns === FALSE) + { + throw new InvalidArgumentException("Could not determine the headers from the given file {$csvFile}"); + } + + $metaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData($tableName, $columns); + $table = new PHPUnit_Extensions_Database_DataSet_DefaultTable($metaData); + + while (($row = $this->getCsvRow($fh)) !== FALSE) + { + $table->addRow(array_combine($columns, $row)); + } + + $this->tables[$tableName] = $table; + } + + /** + * Creates an iterator over the tables in the data set. If $reverse is + * true a reverse iterator will be returned. + * + * @param bool $reverse + * @return PHPUnit_Extensions_Database_DataSet_ITableIterator + */ + protected function createIterator($reverse = FALSE) + { + return new PHPUnit_Extensions_Database_DataSet_DefaultTableIterator($this->tables, $reverse); + } + + /** + * Returns a row from the csv file in an indexed array. + * + * @param resource $fh + * @return array + */ + protected function getCsvRow($fh) + { + if (version_compare(PHP_VERSION, '5.3.0', '>')) { + return fgetcsv($fh, NULL, $this->delimiter, $this->enclosure, $this->escape); + } else { + return fgetcsv($fh, NULL, $this->delimiter, $this->enclosure); + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/DataSetFilter.php b/tests/PHPUnit/Extensions/Database/DataSet/DataSetFilter.php new file mode 100755 index 00000000..5bd64b72 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/DataSetFilter.php @@ -0,0 +1,144 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/AbstractDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/TableFilter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * A dataset decorator that allows filtering out tables and table columns from + * results. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DataSet_DataSetFilter extends PHPUnit_Extensions_Database_DataSet_AbstractDataSet +{ + + /** + * The dataset being decorated. + * @var PHPUnit_Extensions_Database_DataSet_IDataSet + */ + protected $originalDataSet; + + /** + * The tables to exclude from the data set. + * @var Array + */ + protected $excludeTables; + + /** + * The columns to exclude from the data set. + * @var Array + */ + protected $excludeColumns; + + /** + * Creates a new filtered data set. + * + * The $exclude tables should be an associative array using table names as + * the key and an array of column names to exclude for the value. If you + * would like to exclude a full table set the value of the table's entry + * to the special string '*'. + * + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $originalDataSet + * @param Array $excludeTables + */ + public function __construct(PHPUnit_Extensions_Database_DataSet_IDataSet $originalDataSet, Array $excludeTables) + { + $this->originalDataSet = $originalDataSet; + $this->excludeTables = $excludeTables; + + foreach ($this->excludeTables as $tableName => $values) { + if (is_array($values)) { + $this->excludeColumns[$tableName] = $values; + } elseif ($values == '*') { + $this->excludeTables[] = $tableName; + } else { + $this->excludeColumns[$tableName] = (array)$values; + } + } + } + + /** + * Creates an iterator over the tables in the data set. If $reverse is + * true a reverse iterator will be returned. + * + * @param bool $reverse + * @return PHPUnit_Extensions_Database_DataSet_ITableIterator + */ + protected function createIterator($reverse = FALSE) + { + $original_tables = $this->originalDataSet->getIterator($reverse); + $new_tables = array(); + + foreach ($original_tables as $table) { + /* @var $table PHPUnit_Extensions_Database_DataSet_ITable */ + $tableName = $table->getTableMetaData()->getTableName(); + + if (in_array($tableName, $this->excludeTables)) { + continue; + } elseif (array_key_exists($tableName, $this->excludeColumns)) { + $new_tables[] = new PHPUnit_Extensions_Database_DataSet_TableFilter($table, $this->excludeColumns[$tableName]); + } else { + $new_tables[] = $table; + } + } + + return new PHPUnit_Extensions_Database_DataSet_DefaultTableIterator($new_tables); + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/DefaultDataSet.php b/tests/PHPUnit/Extensions/Database/DataSet/DefaultDataSet.php new file mode 100755 index 00000000..6535fe95 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/DefaultDataSet.php @@ -0,0 +1,109 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/AbstractDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableIterator.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * The default implementation of a data set. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DataSet_DefaultDataSet extends PHPUnit_Extensions_Database_DataSet_AbstractDataSet +{ + + /** + * An array of ITable objects. + * + * @var array + */ + protected $tables; + + /** + * Creates a new dataset using the given tables. + * + * @param array $tables + */ + public function __construct(Array $tables = array()) + { + $this->tables = $tables; + } + + /** + * Adds a table to the dataset. + * + * @param PHPUnit_Extensions_Database_DataSet_ITable $table + */ + public function addTable(PHPUnit_Extensions_Database_DataSet_ITable $table) + { + $this->tables[] = $table; + } + + /** + * Creates an iterator over the tables in the data set. If $reverse is + * true a reverse iterator will be returned. + * + * @param bool $reverse + * @return PHPUnit_Extensions_Database_DataSet_ITableIterator + */ + protected function createIterator($reverse = FALSE) + { + return new PHPUnit_Extensions_Database_DataSet_DefaultTableIterator($this->tables, $reverse); + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/DefaultTable.php b/tests/PHPUnit/Extensions/Database/DataSet/DefaultTable.php new file mode 100755 index 00000000..fe6b3a01 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/DefaultTable.php @@ -0,0 +1,124 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/AbstractTable.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides default table functionality. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DataSet_DefaultTable extends PHPUnit_Extensions_Database_DataSet_AbstractTable +{ + + /** + * Creates a new table object using the given $tableMetaData + * + * @param PHPUnit_Extensions_Database_DataSet_ITableMetaData $tableMetaData + */ + public function __construct(PHPUnit_Extensions_Database_DataSet_ITableMetaData $tableMetaData) + { + $this->setTableMetaData($tableMetaData); + $this->data = array(); + } + + /** + * Adds a row to the table with optional values. + * + * @param array $values + */ + public function addRow($values = array()) + { + $columnNames = $this->getTableMetaData()->getColumns(); + $this->data[] = array_merge(array_fill_keys($columnNames, NULL), $values); + } + + /** + * Adds the rows in the passed table to the current table. + * + * @param PHPUnit_Extensions_Database_DataSet_ITable $table + */ + public function addTableRows(PHPUnit_Extensions_Database_DataSet_ITable $table) + { + $tableColumns = $this->getTableMetaData()->getColumns(); + for ($i = 0; $i < $table->getRowCount(); $i++) { + $newRow = array(); + foreach ($tableColumns as $columnName) { + $newRow[$columnName] = $table->getValue($i, $columnName); + } + $this->addRow($newRow); + } + } + + /** + * Sets the specified column of the specied row to the specified value. + * + * @param int $row + * @param string $column + * @param mixed $value + */ + public function setValue($row, $column, $value) + { + if (isset($this->data[$row])) { + $this->data[$row][$column] = $value; + } else { + throw new InvalidArgumentException("The row given does not exist."); + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/DefaultTableIterator.php b/tests/PHPUnit/Extensions/Database/DataSet/DefaultTableIterator.php new file mode 100755 index 00000000..682d4502 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/DefaultTableIterator.php @@ -0,0 +1,173 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/ITableIterator.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * The default table iterator + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DataSet_DefaultTableIterator implements PHPUnit_Extensions_Database_DataSet_ITableIterator +{ + + /** + * An array of tables in the iterator. + * + * @var Array + */ + protected $tables; + + /** + * If this property is true then the tables will be iterated in reverse + * order. + * + * @var bool + */ + protected $reverse; + + /** + * Creates a new default table iterator object. + * + * @param array $tables + * @param bool $reverse + */ + public function __construct(Array $tables, $reverse = FALSE) + { + $this->tables = $tables; + $this->reverse = $reverse; + + $this->rewind(); + } + + /** + * Returns the current table. + * + * @return PHPUnit_Extensions_Database_DataSet_ITable + */ + public function getTable() + { + $this->current(); + } + + /** + * Returns the current table's meta data. + * + * @return PHPUnit_Extensions_Database_DataSet_ITableMetaData + */ + public function getTableMetaData() + { + $this->current()->getTableMetaData(); + } + + /** + * Returns the current table. + * + * @return PHPUnit_Extensions_Database_DataSet_ITable + */ + public function current() + { + return current($this->tables); + } + + /** + * Returns the name of the current table. + * + * @return string + */ + public function key() + { + return $this->current()->getTableMetaData()->getTableName(); + } + + /** + * advances to the next element. + * + */ + public function next() + { + if ($this->reverse) { + prev($this->tables); + } else { + next($this->tables); + } + } + + /** + * Rewinds to the first element + */ + public function rewind() + { + if ($this->reverse) { + end($this->tables); + } else { + reset($this->tables); + } + } + + /** + * Returns true if the current index is valid + * + * @return bool + */ + public function valid() + { + return ($this->current() !== FALSE); + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php b/tests/PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php new file mode 100755 index 00000000..0c531c30 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php @@ -0,0 +1,91 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/AbstractTableMetaData.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * The default implementation of table meta data + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData extends PHPUnit_Extensions_Database_DataSet_AbstractTableMetaData +{ + + /** + * Creates a new default table meta data object. + * + * @param string $tableName + * @param array $columns + * @param array $primaryKeys + */ + public function __construct($tableName, Array $columns, Array $primaryKeys = array()) + { + $this->tableName = $tableName; + $this->columns = $columns; + $this->primaryKeys = array(); + + foreach ($primaryKeys as $columnName) { + if (!in_array($columnName, $this->columns)) { + throw new InvalidArgumentException("Primary key column passed that is not in the column list."); + } else { + $this->primaryKeys[] = $columnName; + } + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php b/tests/PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php new file mode 100755 index 00000000..c6e52006 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php @@ -0,0 +1,111 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/AbstractXmlDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/Persistors/FlatXml.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * The default implementation of a data set. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet extends PHPUnit_Extensions_Database_DataSet_AbstractXmlDataSet +{ + + protected function getTableInfo(Array &$tableColumns, Array &$tableValues) + { + if ($this->xmlFileContents->getName() != 'dataset') { + throw new Exception("The root element of a flat xml data set file must be called "); + } + + foreach ($this->xmlFileContents->children() as $row) { + $tableName = $row->getName(); + + if (!isset($tableColumns[$tableName])) { + $tableColumns[$tableName] = array(); + $tableValues[$tableName] = array(); + } + + $values = array(); + foreach ($row->attributes() as $name => $value) { + if (!in_array($name, $tableColumns[$tableName])) { + $tableColumns[$tableName][] = $name; + } + + $values[$name] = $value; + } + + if (count($values)) { + $tableValues[$tableName][] = $values; + } + } + } + + public static function write(PHPUnit_Extensions_Database_DataSet_IDataSet $dataset, $filename) + { + $pers = new PHPUnit_Extensions_Database_DataSet_Persistors_FlatXml(); + $pers->setFileName($filename); + + try { + $pers->write($dataset); + } catch (RuntimeException $e) { + throw new RuntimeException(__METHOD__ . ' called with an unwritable file.'); + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/IDataSet.php b/tests/PHPUnit/Extensions/Database/DataSet/IDataSet.php new file mode 100755 index 00000000..3835b4a2 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/IDataSet.php @@ -0,0 +1,104 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides a basic interface for creating and reading data from data sets. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +interface PHPUnit_Extensions_Database_DataSet_IDataSet extends IteratorAggregate +{ + + /** + * Returns an array of table names contained in the dataset. + * + * @return array + */ + public function getTableNames(); + + /** + * Returns a table meta data object for the given table. + * + * @param string $tableName + * @return PHPUnit_Extensions_Database_DataSet_ITableMetaData + */ + public function getTableMetaData($tableName); + + /** + * Returns a table object for the given table. + * + * @param string $tableName + * @return PHPUnit_Extensions_Database_DataSet_ITable + */ + public function getTable($tableName); + + /** + * Returns a reverse iterator for all table objects in the given dataset. + * + * @return PHPUnit_Extensions_Database_DataSet_ITableIterator + */ + public function getReverseIterator(); + + /** + * Asserts that the given data set matches this data set. + * + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $other + */ + public function assertEquals(PHPUnit_Extensions_Database_DataSet_IDataSet $other); +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/IPersistable.php b/tests/PHPUnit/Extensions/Database/DataSet/IPersistable.php new file mode 100755 index 00000000..885140c3 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/IPersistable.php @@ -0,0 +1,77 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/IDataSet.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * An interface for persisting datasets + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +interface PHPUnit_Extensions_Database_DataSet_IPersistable +{ + /** + * Writes the given dataset + * + * The previous dataset will be overwritten. + * + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataset + */ + public function write(PHPUnit_Extensions_Database_DataSet_IDataSet $dataset); +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/ITable.php b/tests/PHPUnit/Extensions/Database/DataSet/ITable.php new file mode 100755 index 00000000..334f292d --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/ITable.php @@ -0,0 +1,104 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides a basic interface for creating and reading data from data sets. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +interface PHPUnit_Extensions_Database_DataSet_ITable +{ + + /** + * Returns the table's meta data. + * + * @return PHPUnit_Extensions_Database_DataSet_ITableMetaData + */ + public function getTableMetaData(); + + /** + * Returns the number of rows in this table. + * + * @return int + */ + public function getRowCount(); + + /** + * Returns the value for the given column on the given row. + * + * @param int $row + * @param int $column + */ + public function getValue($row, $column); + + /** + * Returns the an associative array keyed by columns for the given row. + * + * @param int $row + * @return array + */ + public function getRow($row); + + /** + * Asserts that the given table matches this table. + * + * @param PHPUnit_Extensions_Database_DataSet_ITable $other + */ + public function assertEquals(PHPUnit_Extensions_Database_DataSet_ITable $other); +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/ITableIterator.php b/tests/PHPUnit/Extensions/Database/DataSet/ITableIterator.php new file mode 100755 index 00000000..d2ee54ab --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/ITableIterator.php @@ -0,0 +1,81 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides a basic interface for creating and reading data from data sets. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +interface PHPUnit_Extensions_Database_DataSet_ITableIterator extends Iterator +{ + + /** + * Returns the current table. + * + * @return PHPUnit_Extensions_Database_DataSet_ITable + */ + public function getTable(); + + /** + * Returns the current table's meta data. + * + * @return PHPUnit_Extensions_Database_DataSet_ITableMetaData + */ + public function getTableMetaData(); +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/ITableMetaData.php b/tests/PHPUnit/Extensions/Database/DataSet/ITableMetaData.php new file mode 100755 index 00000000..f713a539 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/ITableMetaData.php @@ -0,0 +1,95 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides a basic interface for returning table meta data. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +interface PHPUnit_Extensions_Database_DataSet_ITableMetaData +{ + + /** + * Returns the names of the columns in the table. + * + * @return array + */ + public function getColumns(); + + /** + * Returns the names of the primary key columns in the table. + * + * @return array + */ + public function getPrimaryKeys(); + + /** + * Returns the name of the table. + * + * @return string + */ + public function getTableName(); + + /** + * Asserts that the given tableMetaData matches this tableMetaData. + * + * @param PHPUnit_Extensions_Database_DataSet_ITableMetaData $other + */ + public function assertEquals(PHPUnit_Extensions_Database_DataSet_ITableMetaData $other); +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/Persistors/Abstract.php b/tests/PHPUnit/Extensions/Database/DataSet/Persistors/Abstract.php new file mode 100755 index 00000000..101d8baa --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/Persistors/Abstract.php @@ -0,0 +1,137 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/IPersistable.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + + +/** + * An abstract implementation of a dataset persistor. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +abstract class PHPUnit_Extensions_Database_DataSet_Persistors_Abstract implements PHPUnit_Extensions_Database_DataSet_IPersistable +{ + public function write(PHPUnit_Extensions_Database_DataSet_IDataSet $dataset) + { + $this->saveDataSet($dataset); + } + + /** + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataset + */ + protected function saveDataSet(PHPUnit_Extensions_Database_DataSet_IDataSet $dataset) + { + $this->startDataSet($dataset); + foreach ($dataset as $table) + { + $this->saveTable($table); + } + $this->endDataSet($dataset); + } + + /** + * @param PHPUnit_Extensions_Database_DataSet_ITable $table + */ + protected function saveTable(PHPUnit_Extensions_Database_DataSet_ITable $table) + { + $this->startTable($table); + for ($i = 0; $i < $table->getRowCount(); $i++) + { + $this->row($table->getRow($i), $table); + } + $this->endTable($table); + } + + /** + * Override to save the start of a dataset. + * + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataset + */ + abstract protected function startDataSet(PHPUnit_Extensions_Database_DataSet_IDataSet $dataset); + + /** + * Override to save the end of a dataset. + * + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataset + */ + abstract protected function endDataSet(PHPUnit_Extensions_Database_DataSet_IDataSet $dataset); + + /** + * Override to save the start of a table. + * + * @param PHPUnit_Extensions_Database_DataSet_ITable $table + */ + abstract protected function startTable(PHPUnit_Extensions_Database_DataSet_ITable $table); + + /** + * Override to save the end of a table. + * + * @param PHPUnit_Extensions_Database_DataSet_ITable $table + */ + abstract protected function endTable(PHPUnit_Extensions_Database_DataSet_ITable $table); + + /** + * Override to save a table row. + * + * @param array $row + * @param PHPUnit_Extensions_Database_DataSet_ITable $table + */ + abstract protected function row(Array $row, PHPUnit_Extensions_Database_DataSet_ITable $table); +} + +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/Persistors/FlatXml.php b/tests/PHPUnit/Extensions/Database/DataSet/Persistors/FlatXml.php new file mode 100755 index 00000000..916ad488 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/Persistors/FlatXml.php @@ -0,0 +1,157 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/Persistors/Abstract.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * A Flat XML dataset persistor. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DataSet_Persistors_FlatXml extends PHPUnit_Extensions_Database_DataSet_Persistors_Abstract +{ + /** + * @var string + */ + protected $filename; + + /** + * @var resource + */ + protected $fh; + + /** + * Sets the filename that this persistor will save to. + * + * @param string $filename + */ + public function setFileName($filename) + { + $this->filename = $filename; + } + + /** + * Override to save the start of a dataset. + * + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataset + */ + protected function startDataSet(PHPUnit_Extensions_Database_DataSet_IDataSet $dataset) + { + $this->fh = fopen($this->filename, 'w'); + + if ($this->fh === FALSE) { + throw new RuntimeException("Could not open {$this->filename} for writing see " . __CLASS__ . "::setFileName()"); + } + + fwrite($this->fh, "\n"); + fwrite($this->fh, "\n"); + } + + /** + * Override to save the end of a dataset. + * + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataset + */ + protected function endDataSet(PHPUnit_Extensions_Database_DataSet_IDataSet $dataset) + { + fwrite($this->fh, "\n"); + } + + /** + * Override to save the start of a table. + * + * @param PHPUnit_Extensions_Database_DataSet_ITable $table + */ + protected function startTable(PHPUnit_Extensions_Database_DataSet_ITable $table) + { + if ($table->getRowCount() == 0) { + fwrite($this->fh, "\t<{$table->getTableMetaData()->getTableName()} />\n"); + } + } + + /** + * Override to save the end of a table. + * + * @param PHPUnit_Extensions_Database_DataSet_ITable $table + */ + protected function endTable(PHPUnit_Extensions_Database_DataSet_ITable $table) + { + //do nothing + } + + /** + * Override to save a table row. + * + * @param array $row + * @param PHPUnit_Extensions_Database_DataSet_ITable $table + */ + protected function row(Array $row, PHPUnit_Extensions_Database_DataSet_ITable $table) + { + fwrite($this->fh, "\t<{$table->getTableMetaData()->getTableName()}\n"); + + foreach ($table->getTableMetaData()->getColumns() as $columnName) { + if (isset($row[$columnName])) { + fwrite($this->fh, "\t\t{$columnName}=\"". htmlspecialchars($row[$columnName]) . "\"\n"); + } + } + + fwrite($this->fh, "\t/>\n"); + } +} + +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/Persistors/Xml.php b/tests/PHPUnit/Extensions/Database/DataSet/Persistors/Xml.php new file mode 100755 index 00000000..5694567a --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/Persistors/Xml.php @@ -0,0 +1,161 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/Persistors/Abstract.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * A XML dataset persistor. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DataSet_Persistors_Xml extends PHPUnit_Extensions_Database_DataSet_Persistors_Abstract +{ + /** + * @var string + */ + protected $filename; + + /** + * @var resource + */ + protected $fh; + + /** + * Sets the filename that this persistor will save to. + * + * @param string $filename + */ + public function setFileName($filename) + { + $this->filename = $filename; + } + + /** + * Override to save the start of a dataset. + * + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataset + */ + protected function startDataSet(PHPUnit_Extensions_Database_DataSet_IDataSet $dataset) + { + $this->fh = fopen($this->filename, 'w'); + + if ($this->fh === FALSE) { + throw new RuntimeException("Could not open {$this->filename} for writing see " . __CLASS__ . "::setFileName()"); + } + + fwrite($this->fh, "\n"); + fwrite($this->fh, "\n"); + } + + /** + * Override to save the end of a dataset. + * + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataset + */ + protected function endDataSet(PHPUnit_Extensions_Database_DataSet_IDataSet $dataset) + { + fwrite($this->fh, "\n"); + } + + /** + * Override to save the start of a table. + * + * @param PHPUnit_Extensions_Database_DataSet_ITable $table + */ + protected function startTable(PHPUnit_Extensions_Database_DataSet_ITable $table) + { + fwrite($this->fh, "\tgetTableMetaData()->getTableName()}\">\n"); + + foreach ($table->getTableMetaData()->getColumns() as $columnName) { + fwrite($this->fh, "\t\t{$columnName}\n"); + } + } + + /** + * Override to save the end of a table. + * + * @param PHPUnit_Extensions_Database_DataSet_ITable $table + */ + protected function endTable(PHPUnit_Extensions_Database_DataSet_ITable $table) + { + fwrite($this->fh, "\t
\n"); + } + + /** + * Override to save a table row. + * + * @param array $row + * @param PHPUnit_Extensions_Database_DataSet_ITable $table + */ + protected function row(Array $row, PHPUnit_Extensions_Database_DataSet_ITable $table) + { + fwrite($this->fh, "\t\t\n"); + + foreach ($table->getTableMetaData()->getColumns() as $columnName) { + if (isset($row[$columnName])) { + fwrite($this->fh, "\t\t\t" . htmlspecialchars($row[$columnName]) . "\n"); + } else { + fwrite($this->fh, "\t\t\t\n"); + } + } + + fwrite($this->fh, "\t\t\n"); + } +} + +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/QueryDataSet.php b/tests/PHPUnit/Extensions/Database/DataSet/QueryDataSet.php new file mode 100755 index 00000000..07fdd3da --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/QueryDataSet.php @@ -0,0 +1,142 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/AbstractDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/QueryTable.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableIterator.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides access to a database instance as a data set. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DataSet_QueryDataSet extends PHPUnit_Extensions_Database_DataSet_AbstractDataSet +{ + + /** + * An array of ITable objects. + * + * @var array + */ + protected $tables = array(); + + /** + * The database connection this dataset is using. + * + * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection + */ + protected $databaseConnection; + + /** + * Creates a new dataset using the given database connection. + * + * @param PHPUnit_Extensions_Database_DB_IDatabaseConnection $databaseConnection + */ + public function __construct(PHPUnit_Extensions_Database_DB_IDatabaseConnection $databaseConnection) + { + $this->databaseConnection = $databaseConnection; + } + + public function addTable($tableName, $query = NULL) + { + if ($query === NULL) { + $query = 'SELECT * FROM ' . $tableName; + } + + $this->tables[$tableName] = new PHPUnit_Extensions_Database_DataSet_QueryTable($tableName, $query, $this->databaseConnection); + } + + /** + * Creates an iterator over the tables in the data set. If $reverse is + * true a reverse iterator will be returned. + * + * @param bool $reverse + * @return PHPUnit_Extensions_Database_DB_TableIterator + */ + protected function createIterator($reverse = FALSE) + { + return new PHPUnit_Extensions_Database_DataSet_DefaultTableIterator($this->tables, $reverse); + } + + /** + * Returns a table object for the given table. + * + * @param string $tableName + * @return PHPUnit_Extensions_Database_DB_Table + */ + public function getTable($tableName) + { + if (!isset($this->tables[$tableName])) { + throw new InvalidArgumentException("$tableName is not a table in the current database."); + } + + return $this->tables[$tableName]; + } + + /** + * Returns a list of table names for the database + * + * @return Array + */ + public function getTableNames() + { + return array_keys($this->tables); + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/QueryTable.php b/tests/PHPUnit/Extensions/Database/DataSet/QueryTable.php new file mode 100755 index 00000000..84872096 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/QueryTable.php @@ -0,0 +1,172 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/AbstractTable.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides the functionality to represent a database table. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DataSet_QueryTable extends PHPUnit_Extensions_Database_DataSet_AbstractTable +{ + /** + * @var string + */ + protected $query; + + /** + * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection + */ + protected $databaseConnection; + + /** + * @var string + */ + protected $tableName; + + /** + * Creates a new database query table object. + * + * @param string $table_name + * @param string $query + * @param PHPUnit_Extensions_Database_DB_IDatabaseConnection $databaseConnection + */ + public function __construct($tableName, $query, PHPUnit_Extensions_Database_DB_IDatabaseConnection $databaseConnection) + { + $this->query = $query; + $this->databaseConnection = $databaseConnection; + $this->tableName = $tableName; + } + + /** + * Returns the table's meta data. + * + * @return PHPUnit_Extensions_Database_DataSet_ITableMetaData + */ + public function getTableMetaData() + { + $this->createTableMetaData(); + return parent::getTableMetaData(); + } + + /** + * Returns the number of rows in this table. + * + * @return int + */ + public function getRowCount() + { + $this->loadData(); + return parent::getRowCount(); + } + + /** + * Returns the value for the given column on the given row. + * + * @param int $row + * @param int $column + */ + public function getValue($row, $column) + { + $this->loadData(); + return parent::getValue($row, $column); + } + + /** + * Returns the an associative array keyed by columns for the given row. + * + * @param int $row + * @return array + */ + public function getRow($row) + { + $this->loadData(); + return parent::getRow($row); + } + + /** + * Asserts that the given table matches this table. + * + * @param PHPUnit_Extensions_Database_DataSet_ITable $other + */ + public function assertEquals(PHPUnit_Extensions_Database_DataSet_ITable $other) + { + $this->loadData(); + return parent::assertEquals($other); + } + + protected function loadData() + { + if ($this->data === NULL) { + $pdoStatement = $this->databaseConnection->getConnection()->query($this->query); + $this->data = $pdoStatement->fetchAll(PDO::FETCH_ASSOC); + } + } + + protected function createTableMetaData() + { + if ($this->tableMetaData === NULL) + { + $this->loadData(); + $this->tableMetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData($this->tableName, array_keys($this->data[0])); + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/ReplacementDataSet.php b/tests/PHPUnit/Extensions/Database/DataSet/ReplacementDataSet.php new file mode 100755 index 00000000..6f9ccbfc --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/ReplacementDataSet.php @@ -0,0 +1,140 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/AbstractDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/ReplacementTableIterator.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Allows for replacing arbitrary values or portions of values with new data. + * + * A usage for this is replacing all values == '[NULL'] with a true NULL value + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class PHPUnit_Extensions_Database_DataSet_ReplacementDataSet extends PHPUnit_Extensions_Database_DataSet_AbstractDataSet +{ + /** + * @var PHPUnit_Extensions_Database_DataSet_IDataSet + */ + protected $dataSet; + + /** + * @var array + */ + protected $fullReplacements; + + /** + * @var array + */ + protected $subStrReplacements; + + /** + * Creates a new replacement dataset + * + * You can pass in any data set that implements PHPUnit_Extensions_Database_DataSet_IDataSet + * + * @param string $delimiter + * @param string $enclosure + * @param string $escape + */ + public function __construct(PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet, Array $fullReplacements = array(), Array $subStrReplacements = array()) + { + $this->dataSet = $dataSet; + $this->fullReplacements = $fullReplacements; + $this->subStrReplacements = $subStrReplacements; + } + + /** + * Adds a new full replacement + * + * Full replacements will only replace values if the FULL value is a match + * + * @param string $value + * @param string $replacement + */ + public function addFullReplacement($value, $replacement) + { + $this->fullReplacements[$value] = $replacement; + } + + /** + * Adds a new substr replacement + * + * Substr replacements will replace all occurances of the substr in every column + * + * @param string $value + * @param string $replacement + */ + public function addSubStrReplacement($value, $replacement) + { + $this->subStrReplacements[$value] = $replacement; + } + + /** + * Creates an iterator over the tables in the data set. If $reverse is + * true a reverse iterator will be returned. + * + * @param bool $reverse + * @return PHPUnit_Extensions_Database_DataSet_ITableIterator + */ + protected function createIterator($reverse = FALSE) + { + $innerIterator = $reverse ? $this->dataSet->getReverseIterator() : $this->dataSet->getIterator(); + return new PHPUnit_Extensions_Database_DataSet_ReplacementTableIterator($innerIterator, $this->fullReplacements, $this->subStrReplacements); + } +} +?> \ No newline at end of file diff --git a/tests/PHPUnit/Extensions/Database/DataSet/ReplacementTable.php b/tests/PHPUnit/Extensions/Database/DataSet/ReplacementTable.php new file mode 100755 index 00000000..14645c3d --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/ReplacementTable.php @@ -0,0 +1,250 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/ITable.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Allows for replacing arbitrary strings in your data sets with other values. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + * @todo When setTableMetaData() is taken out of the AbstractTable this class should extend AbstractTable. + */ +class PHPUnit_Extensions_Database_DataSet_ReplacementTable implements PHPUnit_Extensions_Database_DataSet_ITable +{ + /** + * @var PHPUnit_Extensions_Database_DataSet_ITable + */ + protected $table; + + /** + * @var array + */ + protected $fullReplacements; + + /** + * @var array + */ + protected $subStrReplacements; + + /** + * Creates a new replacement table + * + * @param PHPUnit_Extensions_Database_DataSet_ITable $table + * @param array $fullReplacements + * @param array $subStrReplacements + */ + public function __construct(PHPUnit_Extensions_Database_DataSet_ITable $table, Array $fullReplacements = array(), Array $subStrReplacements = array()) + { + $this->table = $table; + $this->fullReplacements = $fullReplacements; + $this->subStrReplacements = $subStrReplacements; + } + + /** + * Adds a new full replacement + * + * Full replacements will only replace values if the FULL value is a match + * + * @param string $value + * @param string $replacement + */ + public function addFullReplacement($value, $replacement) + { + $this->fullReplacements[$value] = $replacement; + } + + /** + * Adds a new substr replacement + * + * Substr replacements will replace all occurances of the substr in every column + * + * @param string $value + * @param string $replacement + */ + public function addSubStrReplacement($value, $replacement) + { + $this->subStrReplacements[$value] = $replacement; + } + + /** + * Returns the table's meta data. + * + * @return PHPUnit_Extensions_Database_DataSet_ITableMetaData + */ + public function getTableMetaData() + { + return $this->table->getTableMetaData(); + } + + /** + * Returns the number of rows in this table. + * + * @return int + */ + public function getRowCount() + { + return $this->table->getRowCount(); + } + + /** + * Returns the value for the given column on the given row. + * + * @param int $row + * @param int $column + */ + public function getValue($row, $column) + { + return $this->getReplacedValue($this->table->getValue($row, $column)); + } + + /** + * Returns the an associative array keyed by columns for the given row. + * + * @param int $row + * @return array + */ + public function getRow($row) + { + $row = $this->table->getRow($row); + + return array_map(array($this, 'getReplacedValue'), $row); + } + + /** + * Asserts that the given table matches this table. + * + * @param PHPUnit_Extensions_Database_DataSet_ITable $other + */ + public function assertEquals(PHPUnit_Extensions_Database_DataSet_ITable $other) + { + $thisMetaData = $this->getTableMetaData(); + $otherMetaData = $other->getTableMetaData(); + + $thisMetaData->assertEquals($otherMetaData); + + if ($this->getRowCount() != $other->getRowCount()) { + throw new Exception("Expected row count of {$this->getRowCount()}, has a row count of {$other->getRowCount()}"); + } + + $columns = $thisMetaData->getColumns(); + for ($i = 0; $i < $this->getRowCount(); $i++) { + foreach ($columns as $columnName) { + if ($this->getValue($i, $columnName) != $other->getValue($i, $columnName)) { + throw new Exception("Expected value of {$this->getValue($i, $columnName)} for row {$i} column {$columnName}, has a value of {$other->getValue($i, $columnName)}"); + } + } + } + + return TRUE; + } + + public function __toString() + { + $columns = $this->getTableMetaData()->getColumns(); + + $lineSeperator = str_repeat('+----------------------', count($columns)) . "+\n"; + $lineLength = strlen($lineSeperator) - 1; + + $tableString = $lineSeperator; + $tableString .= '| ' . str_pad($this->getTableMetaData()->getTableName(), $lineLength - 4, ' ', STR_PAD_RIGHT) . " |\n"; + $tableString .= $lineSeperator; + $tableString .= $this->rowToString($columns); + $tableString .= $lineSeperator; + + for ($i = 0; $i < $this->getRowCount(); $i++) { + $values = array(); + foreach ($columns as $columnName) { + $values[] = $this->getValue($i, $columnName); + } + + $tableString .= $this->rowToString($values); + $tableString .= $lineSeperator; + } + + return "\n" . $tableString . "\n"; + } + + protected function rowToString(Array $row) + { + $rowString = ''; + foreach ($row as $value) { + if (is_null($value)) { + $value = 'NULL'; + } + $rowString .= '| ' . str_pad(substr($value, 0, 20), 20, ' ', STR_PAD_BOTH) . ' '; + } + + return $rowString . "|\n"; + } + + protected function getReplacedValue($value) + { + if (is_scalar($value) && array_key_exists((string)$value, $this->fullReplacements)) + { + return $this->fullReplacements[$value]; + } + elseif (count($this->subStrReplacements)) + { + return str_replace(array_keys($this->subStrReplacements), array_values($this->subStrReplacements), $value); + } + else + { + return $value; + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/ReplacementTableIterator.php b/tests/PHPUnit/Extensions/Database/DataSet/ReplacementTableIterator.php new file mode 100755 index 00000000..7690e7ac --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/ReplacementTableIterator.php @@ -0,0 +1,197 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/ITableIterator.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/ReplacementTable.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * The default table iterator + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DataSet_ReplacementTableIterator implements OuterIterator, PHPUnit_Extensions_Database_DataSet_ITableIterator +{ + + /** + * @var PHPUnit_Extensions_Database_DataSet_ITableIterator + */ + protected $innerIterator; + + /** + * @var array + */ + protected $fullReplacements; + + /** + * @var array + */ + protected $subStrReplacements; + + /** + * Creates a new replacement table iterator object. + * + * @param PHPUnit_Extensions_Database_DataSet_ITableIterator $innerIterator + * @param array $fullReplacements + * @param array $subStrReplacements + */ + public function __construct(PHPUnit_Extensions_Database_DataSet_ITableIterator $innerIterator, Array $fullReplacements = array(), Array $subStrReplacements = array()) + { + $this->innerIterator = $innerIterator; + $this->fullReplacements = $fullReplacements; + $this->subStrReplacements = $subStrReplacements; + } + + /** + * Adds a new full replacement + * + * Full replacements will only replace values if the FULL value is a match + * + * @param string $value + * @param string $replacement + */ + public function addFullReplacement($value, $replacement) + { + $this->fullReplacements[$value] = $replacement; + } + + /** + * Adds a new substr replacement + * + * Substr replacements will replace all occurances of the substr in every column + * + * @param string $value + * @param string $replacement + */ + public function addSubStrReplacement($value, $replacement) + { + $this->subStrReplacements[$value] = $replacement; + } + + /** + * Returns the current table. + * + * @return PHPUnit_Extensions_Database_DataSet_ITable + */ + public function getTable() + { + return $this->current(); + } + + /** + * Returns the current table's meta data. + * + * @return PHPUnit_Extensions_Database_DataSet_ITableMetaData + */ + public function getTableMetaData() + { + $this->current()->getTableMetaData(); + } + + /** + * Returns the current table. + * + * @return PHPUnit_Extensions_Database_DataSet_ITable + */ + public function current() + { + return new PHPUnit_Extensions_Database_DataSet_ReplacementTable($this->innerIterator->current(), $this->fullReplacements, $this->subStrReplacements); + } + + /** + * Returns the name of the current table. + * + * @return string + */ + public function key() + { + return $this->current()->getTableMetaData()->getTableName(); + } + + /** + * advances to the next element. + * + */ + public function next() + { + $this->innerIterator->next(); + } + + /** + * Rewinds to the first element + */ + public function rewind() + { + $this->innerIterator->rewind(); + } + + /** + * Returns true if the current index is valid + * + * @return bool + */ + public function valid() + { + return $this->innerIterator->valid(); + } + + public function getInnerIterator() + { + return $this->innerIterator; + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/TableFilter.php b/tests/PHPUnit/Extensions/Database/DataSet/TableFilter.php new file mode 100755 index 00000000..ff2e92d4 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/TableFilter.php @@ -0,0 +1,107 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/AbstractTable.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/TableMetaDataFilter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * A table decorator that allows filtering out table columns from results. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DataSet_TableFilter extends PHPUnit_Extensions_Database_DataSet_AbstractTable +{ + + /** + * The table meta data being decorated. + * @var PHPUnit_Extensions_Database_DataSet_ITable + */ + protected $originalTable; + + public function __construct(PHPUnit_Extensions_Database_DataSet_ITable $originalTable, Array $excludeColumns) + { + $this->originalTable = $originalTable; + $this->setTableMetaData(new PHPUnit_Extensions_Database_DataSet_TableMetaDataFilter($originalTable->getTableMetaData(), $excludeColumns)); + } + + /** + * Returns the number of rows in this table. + * + * @return int + */ + public function getRowCount() + { + return $this->originalTable->getRowCount(); + } + + /** + * Returns the value for the given column on the given row. + * + * @param int $row + * @param int $column + */ + public function getValue($row, $column) + { + if (in_array($column, $this->getTableMetaData()->getColumns())) { + return $this->originalTable->getValue($row, $column); + } else { + throw new InvalidArgumentException("The given row ({$row}) and column ({$column}) do not exist in table {$this->getTableMetaData()->getTableName()}"); + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/TableMetaDataFilter.php b/tests/PHPUnit/Extensions/Database/DataSet/TableMetaDataFilter.php new file mode 100755 index 00000000..6a22135d --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/TableMetaDataFilter.php @@ -0,0 +1,125 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/AbstractTableMetaData.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * A TableMetaData decorator that allows filtering out columns from another + * metaData object. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DataSet_TableMetaDataFilter extends PHPUnit_Extensions_Database_DataSet_AbstractTableMetaData +{ + + /** + * The table meta data being decorated. + * @var PHPUnit_Extensions_Database_DataSet_ITableMetaData + */ + protected $originalMetaData; + + /** + * The columns to exclude from the meta data. + * @var Array + */ + protected $excludeColumns; + + /** + * Creates a new filtered table meta data object filtering out + * $excludeColumns. + * + * @param PHPUnit_Extensions_Database_DataSet_ITableMetaData $originalMetaData + * @param array $excludeColumns + */ + public function __construct(PHPUnit_Extensions_Database_DataSet_ITableMetaData $originalMetaData, Array $excludeColumns) + { + $this->originalMetaData = $originalMetaData; + $this->excludeColumns = $excludeColumns; + } + + /** + * Returns the names of the columns in the table. + * + * @return array + */ + public function getColumns() + { + return array_values(array_diff($this->originalMetaData->getColumns(), $this->excludeColumns)); + } + + /** + * Returns the names of the primary key columns in the table. + * + * @return array + */ + public function getPrimaryKeys() + { + return $this->originalMetaData->getPrimaryKeys(); + } + + /** + * Returns the name of the table. + * + * @return string + */ + public function getTableName() + { + return $this->originalMetaData->getTableName(); + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DataSet/XmlDataSet.php b/tests/PHPUnit/Extensions/Database/DataSet/XmlDataSet.php new file mode 100755 index 00000000..6a38de69 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DataSet/XmlDataSet.php @@ -0,0 +1,141 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DataSet/AbstractXmlDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/Persistors/Xml.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * The default implementation of a data set. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DataSet_XmlDataSet extends PHPUnit_Extensions_Database_DataSet_AbstractXmlDataSet +{ + + protected function getTableInfo(Array &$tableColumns, Array &$tableValues) + { + if ($this->xmlFileContents->getName() != 'dataset') { + throw new Exception("The root element of an xml data set file must be called "); + } + + foreach ($this->xmlFileContents->xpath('/dataset/table') as $tableElement) { + if (empty($tableElement['name'])) { + throw new Exception("Table elements must include a name attribute specifying the table name."); + } + + $tableName = (string)$tableElement['name']; + + if (!isset($tableColumns[$tableName])) { + $tableColumns[$tableName] = array(); + } + + if (!isset($tableValues[$tableName])) { + $tableValues[$tableName] = array(); + } + + $tableInstanceColumns = array(); + + foreach ($tableElement->xpath('./column') as $columnElement) { + $columnName = (string)$columnElement; + if (empty($columnName)) { + throw new Exception("column elements cannot be empty"); + } + + if (!in_array($columnName, $tableColumns[$tableName])) { + $tableColumns[$tableName][] = $columnName; + } + + $tableInstanceColumns[] = $columnName; + } + + foreach ($tableElement->xpath('./row') as $rowElement) { + $rowValues = array(); + $index = 0; + foreach ($rowElement->children() as $columnValue) { + switch ($columnValue->getName()) { + case 'value': + $rowValues[$tableInstanceColumns[$index]] = (string)$columnValue; + $index++; + break; + case 'null': + $rowValues[$tableInstanceColumns[$index]] = NULL; + $index++; + break; + default: + throw new Exception("Unknown child in the a row element."); + } + } + + $tableValues[$tableName][] = $rowValues; + } + } + } + + public static function write(PHPUnit_Extensions_Database_DataSet_IDataSet $dataset, $filename) + { + $pers = new PHPUnit_Extensions_Database_DataSet_Persistors_Xml(); + $pers->setFileName($filename); + + try { + $pers->write($dataset); + } catch (RuntimeException $e) { + throw new RuntimeException(__METHOD__ . ' called with an unwritable file.'); + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/DefaultTester.php b/tests/PHPUnit/Extensions/Database/DefaultTester.php new file mode 100755 index 00000000..2f95852e --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/DefaultTester.php @@ -0,0 +1,95 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/AbstractTester.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * This is the default implementation of the database tester. It receives its + * connection object from the constructor. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_DefaultTester extends PHPUnit_Extensions_Database_AbstractTester +{ + + /** + * @var PHPUnit_Extensions_Database_DB_IDatabaseConnection + */ + protected $connection; + + /** + * Creates a new default database tester using the given connection. + * + * @param PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection + */ + public function __construct(PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection) + { + $this->connection = $connection; + } + + /** + * Returns the test database connection. + * + * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection + */ + public function getConnection() + { + return $this->connection; + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/ITester.php b/tests/PHPUnit/Extensions/Database/ITester.php new file mode 100755 index 00000000..021547f0 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/ITester.php @@ -0,0 +1,128 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * This is the interface for DatabaseTester objects. These objects are used to + * add database testing to existing test cases using composition instead of + * extension. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +interface PHPUnit_Extensions_Database_ITester +{ + + /** + * Closes the specified connection. + * + * @param PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection + */ + public function closeConnection(PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection); + + /** + * Returns the test database connection. + * + * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection + */ + public function getConnection(); + + /** + * Returns the test dataset. + * + * @return PHPUnit_Extensions_Database_DataSet_IDataSet + */ + public function getDataSet(); + + /** + * TestCases must call this method inside setUp(). + */ + public function onSetUp(); + + /** + * TestCases must call this method inside teadDown(). + */ + public function onTearDown(); + + /** + * Sets the test dataset to use. + * + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet + */ + public function setDataSet(PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet); + + /** + * Sets the schema value. + * + * @param string $schema + */ + public function setSchema($schema); + + /** + * Sets the DatabaseOperation to call when starting the test. + * + * @param PHPUnit_Extensions_Database_Operation_DatabaseOperation $setUpOperation + */ + public function setSetUpOperation(PHPUnit_Extensions_Database_Operation_IDatabaseOperation $setUpOperation); + + /** + * Sets the DatabaseOperation to call when starting the test. + * + * @param PHPUnit_Extensions_Database_Operation_DatabaseOperation $tearDownOperation + */ + public function setTearDownOperation(PHPUnit_Extensions_Database_Operation_IDatabaseOperation $tearDownOperation); +} +?> diff --git a/tests/PHPUnit/Extensions/Database/Operation/Composite.php b/tests/PHPUnit/Extensions/Database/Operation/Composite.php new file mode 100755 index 00000000..d2fdcc33 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/Operation/Composite.php @@ -0,0 +1,106 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/Operation/IDatabaseOperation.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Exception.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * This class facilitates combining database operations. To create a composite + * operation pass an array of classes that implement + * PHPUnit_Extensions_Database_Operation_IDatabaseOperation and they will be + * executed in that order against all data sets. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_Operation_Composite implements PHPUnit_Extensions_Database_Operation_IDatabaseOperation +{ + + /** + * @var array + */ + protected $operations = array(); + + /** + * Creates a composite operation. + * + * @param array $operations + */ + public function __construct(Array $operations) + { + foreach ($operations as $operation) { + if ($operation instanceof PHPUnit_Extensions_Database_Operation_IDatabaseOperation) { + $this->operations[] = $operation; + } else { + throw new InvalidArgumentException("Only database operation instances can be passed to a composite database operation."); + } + } + } + + public function execute(PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection, PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet) + { + try { + foreach ($this->operations as $operation) { + /* @var $operation PHPUnit_Extensions_Database_Operation_IDatabaseOperation */ + $operation->execute($connection, $dataSet); + } + } catch (PHPUnit_Extensions_Database_Operation_Exception $e) { + throw new PHPUnit_Extensions_Database_Operation_Exception("COMPOSITE[{$e->getOperation()}]", $e->getQuery(), $e->getArgs(), $e->getTable(), $e->getError()); + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/Operation/Delete.php b/tests/PHPUnit/Extensions/Database/Operation/Delete.php new file mode 100755 index 00000000..d3e586cb --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/Operation/Delete.php @@ -0,0 +1,98 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/Operation/RowBased.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Exception.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Deletes the rows in a given dataset using primary key columns. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_Operation_Delete extends PHPUnit_Extensions_Database_Operation_RowBased +{ + + protected $operationName = 'DELETE'; + + protected $iteratorDirection = self::ITERATOR_TYPE_REVERSE; + + protected function buildOperationQuery(PHPUnit_Extensions_Database_DataSet_ITableMetaData $databaseTableMetaData, PHPUnit_Extensions_Database_DataSet_ITable $table, PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection) + { + $keys = $databaseTableMetaData->getPrimaryKeys(); + + $whereStatement = 'WHERE ' . implode(' AND ', $this->buildPreparedColumnArray($keys, $connection)); + + $query = " + DELETE FROM {$connection->quoteSchemaObject($table->getTableMetaData()->getTableName())} + {$whereStatement} + "; + + return $query; + } + + protected function buildOperationArguments(PHPUnit_Extensions_Database_DataSet_ITableMetaData $databaseTableMetaData, PHPUnit_Extensions_Database_DataSet_ITable $table, $row) + { + $args = array(); + foreach ($databaseTableMetaData->getPrimaryKeys() as $columnName) { + $args[] = $table->getValue($row, $columnName); + } + + return $args; + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/Operation/DeleteAll.php b/tests/PHPUnit/Extensions/Database/Operation/DeleteAll.php new file mode 100755 index 00000000..ceaf107f --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/Operation/DeleteAll.php @@ -0,0 +1,87 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/Operation/IDatabaseOperation.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Exception.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Deletes all rows from all tables in a dataset. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_Operation_DeleteAll implements PHPUnit_Extensions_Database_Operation_IDatabaseOperation +{ + + public function execute(PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection, PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet) + { + foreach ($dataSet->getReverseIterator() as $table) { + /* @var $table PHPUnit_Extensions_Database_DataSet_ITable */ + + $query = " + DELETE FROM {$connection->quoteSchemaObject($table->getTableMetaData()->getTableName())} + "; + + try { + $connection->getConnection()->query($query); + } catch (PDOException $e) { + throw new PHPUnit_Extensions_Database_Operation_Exception('DELETE_ALL', $query, array(), $table, $e->getMessage()); + } + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/Operation/Exception.php b/tests/PHPUnit/Extensions/Database/Operation/Exception.php new file mode 100755 index 00000000..3d23ca32 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/Operation/Exception.php @@ -0,0 +1,137 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Thrown for exceptions encountered with database operations. Provides + * information regarding which operations failed and the query (if any) it + * failed on. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_Operation_Exception extends RuntimeException +{ + + /** + * @var string + */ + protected $operation; + + /** + * @var string + */ + protected $preparedQuery; + + /** + * @var array + */ + protected $preparedArgs; + + /** + * @var PHPUnit_Extensions_Database_DataSet_ITable + */ + protected $table; + + /** + * @var string + */ + protected $error; + + /** + * Creates a new dbunit operation exception + * + * @param string $operation + * @param string $current_query + * @param PHPUnit_Extensions_Database_DataSet_ITable $current_table + * @param string $error + */ + public function __construct($operation, $current_query, $current_args, $current_table, $error) + { + parent::__construct("{$operation} operation failed on query: {$current_query} using args: " . print_r($current_args, TRUE) . " [{$error}]"); + $this->operation = $operation; + $this->preparedQuery = $current_query; + $this->preparedArgs = $current_args; + $this->table = $current_table; + $this->error = $error; + } + + public function getOperation() + { + return $this->operation; + } + + public function getQuery() + { + return $this->preparedQuery; + } + + public function getTable() + { + return $this->table; + } + + public function getArgs() + { + return $this->preparedArgs; + } + + public function getError() + { + return $this->error; + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/Operation/Factory.php b/tests/PHPUnit/Extensions/Database/Operation/Factory.php new file mode 100755 index 00000000..b2cb682e --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/Operation/Factory.php @@ -0,0 +1,157 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/Operation/IDatabaseOperation.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +require_once 'PHPUnit/Extensions/Database/Operation/Composite.php'; +require_once 'PHPUnit/Extensions/Database/Operation/DeleteAll.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Delete.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Insert.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Null.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Update.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Truncate.php'; + +/** + * A class factory to easily return database operations. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_Operation_Factory +{ + + /** + * Returns a null database operation + * + * @return PHPUnit_Extensions_Database_Operation_IDatabaseOperation + */ + public static function NONE() + { + return new PHPUnit_Extensions_Database_Operation_Null(); + } + + /** + * Returns a clean insert database operation. It will remove all contents + * from the table prior to re-inserting rows. + * + * @param bool $cascadeTruncates Set to true to force truncates to cascade on databases that support this. + * @return PHPUnit_Extensions_Database_Operation_IDatabaseOperation + */ + public static function CLEAN_INSERT($cascadeTruncates = FALSE) + { + return new PHPUnit_Extensions_Database_Operation_Composite(array( + self::TRUNCATE($cascadeTruncates), + self::INSERT() + )); + } + + /** + * Returns an insert database operation. + * + * @return PHPUnit_Extensions_Database_Operation_IDatabaseOperation + */ + public static function INSERT() + { + return new PHPUnit_Extensions_Database_Operation_Insert(); + } + + /** + * Returns a truncate database operation. + * + * @param bool $cascadeTruncates Set to true to force truncates to cascade on databases that support this. + * @return PHPUnit_Extensions_Database_Operation_IDatabaseOperation + */ + public static function TRUNCATE($cascadeTruncates = FALSE) + { + $truncate = new PHPUnit_Extensions_Database_Operation_Truncate(); + $truncate->setCascade($cascadeTruncates); + + return $truncate; + } + + /** + * Returns a delete database operation. + * + * @return PHPUnit_Extensions_Database_Operation_IDatabaseOperation + */ + public static function DELETE() + { + return new PHPUnit_Extensions_Database_Operation_Delete(); + } + + /** + * Returns a delete_all database operation. + * + * @return PHPUnit_Extensions_Database_Operation_IDatabaseOperation + */ + public static function DELETE_ALL() + { + return new PHPUnit_Extensions_Database_Operation_DeleteAll(); + } + + /** + * Returns an update database operation. + * + * @return PHPUnit_Extensions_Database_Operation_IDatabaseOperation + */ + public static function UPDATE() + { + return new PHPUnit_Extensions_Database_Operation_Update(); + } + +} +?> diff --git a/tests/PHPUnit/Extensions/Database/Operation/IDatabaseOperation.php b/tests/PHPUnit/Extensions/Database/Operation/IDatabaseOperation.php new file mode 100755 index 00000000..e1e02ee7 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/Operation/IDatabaseOperation.php @@ -0,0 +1,78 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides a basic interface and functionality for executing database + * operations against a connection using a specific dataSet. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +interface PHPUnit_Extensions_Database_Operation_IDatabaseOperation +{ + + /** + * Executes the database operation against the given $connection for the + * given $dataSet. + * + * @param PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet + * @throws PHPUnit_Extensions_Database_Operation_Exception + */ + public function execute(PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection, PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet); +} +?> diff --git a/tests/PHPUnit/Extensions/Database/Operation/Insert.php b/tests/PHPUnit/Extensions/Database/Operation/Insert.php new file mode 100755 index 00000000..eb2ad496 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/Operation/Insert.php @@ -0,0 +1,108 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/Operation/RowBased.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Exception.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * This class provides functionality for inserting rows from a dataset into a database. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_Operation_Insert extends PHPUnit_Extensions_Database_Operation_RowBased +{ + + protected $operationName = 'INSERT'; + + protected function buildOperationQuery(PHPUnit_Extensions_Database_DataSet_ITableMetaData $databaseTableMetaData, PHPUnit_Extensions_Database_DataSet_ITable $table, PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection) + { + $columnCount = count($table->getTableMetaData()->getColumns()); + + if ($columnCount > 0) { + $placeHolders = implode(', ', array_fill(0, $columnCount, '?')); + + $columns = ''; + foreach ($table->getTableMetaData()->getColumns() as $column) { + $columns .= $connection->quoteSchemaObject($column).', '; + } + + $columns = substr($columns, 0, -2); + + $query = " + INSERT INTO {$connection->quoteSchemaObject($table->getTableMetaData()->getTableName())} + ({$columns}) + VALUES + ({$placeHolders}) + "; + + return $query; + } else { + return FALSE; + } + } + + protected function buildOperationArguments(PHPUnit_Extensions_Database_DataSet_ITableMetaData $databaseTableMetaData, PHPUnit_Extensions_Database_DataSet_ITable $table, $row) + { + $args = array(); + foreach ($table->getTableMetaData()->getColumns() as $columnName) { + $args[] = $table->getValue($row, $columnName); + } + return $args; + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/Operation/Null.php b/tests/PHPUnit/Extensions/Database/Operation/Null.php new file mode 100755 index 00000000..3012e67f --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/Operation/Null.php @@ -0,0 +1,74 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/Operation/IDatabaseOperation.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * This class represents a null database operation. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_Operation_Null implements PHPUnit_Extensions_Database_Operation_IDatabaseOperation +{ + + public function execute(PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection, PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet) + { + /* do nothing */ + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/Operation/Replace.php b/tests/PHPUnit/Extensions/Database/Operation/Replace.php new file mode 100755 index 00000000..2760a9a0 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/Operation/Replace.php @@ -0,0 +1,148 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/Operation/RowBased.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Insert.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Update.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Exception.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Updates the rows in a given dataset using primary key columns. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_Operation_Replace extends PHPUnit_Extensions_Database_Operation_RowBased +{ + + protected $operationName = 'REPLACE'; + + protected function buildOperationQuery(PHPUnit_Extensions_Database_DataSet_ITableMetaData $databaseTableMetaData, PHPUnit_Extensions_Database_DataSet_ITable $table, PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection) + { + $keys = $databaseTableMetaData->getPrimaryKeys(); + + $whereStatement = 'WHERE ' . implode(' AND ', $this->buildPreparedColumnArray($keys, $connection)); + + $query = " + SELECT COUNT(*) + FROM {$connection->quoteSchemaObject($table->getTableMetaData()->getTableName())} + {$whereStatement} + "; + + return $query; + } + + protected function buildOperationArguments(PHPUnit_Extensions_Database_DataSet_ITableMetaData $databaseTableMetaData, PHPUnit_Extensions_Database_DataSet_ITable $table, $row) + { + $args = array(); + + foreach ($databaseTableMetaData->getPrimaryKeys() as $columnName) { + $args[] = $table->getValue($row, $columnName); + } + + return $args; + } + + /** + * @param PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet + */ + public function execute(PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection, PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet) + { + $insertOperation = new PHPUnit_Extensions_Database_Operation_Insert(); + $updateOperation = new PHPUnit_Extensions_Database_Operation_Update(); + + $databaseDataSet = $connection->createDataSet(); + + foreach ($dataSet as $table) { + /* @var $table PHPUnit_Extensions_Database_DataSet_ITable */ + $databaseTableMetaData = $databaseDataSet->getTableMetaData($table->getTableMetaData()->getTableName()); + + $insertQuery = $insertOperation->buildOperationQuery($databaseTableMetaData, $table, $connection); + $updateQuery = $updateOperation->buildOperationQuery($databaseTableMetaData, $table, $connection); + $selectQuery = $this->buildOperationQuery($databaseTableMetaData, $table, $connection); + + $insertStatement = $connection->getConnection()->prepare($insertQuery); + $updateStatement = $connection->getConnection()->prepare($updateQuery); + $selectStatement = $connection->getConnection()->prepare($selectQuery); + + for ($i = 0; $i < $table->getRowCount(); $i++) { + $selectArgs = $this->buildOperationArguments($databaseTableMetaData, $table, $i); + $query = $selectQuery; + $args = $selectArgs; + try { + $selectStatement->execute($selectArgs); + + if ($selectStatement->fetchColumn(0) > 0) { + $updateArgs = $updateOperation->buildOperationArguments($databaseTableMetaData, $table, $i); + $query = $updateQuery; + $args = $updateArgs; + $updateStatement->execute($updateArgs); + } else { + $insertArgs = $insertOperation->buildOperationArguments($databaseTableMetaData, $table, $i); + $query = $insertQuery; + $args = $insertArgs; + $insertStatement->execute($insertArgs); + } + } catch (Exception $e) { + throw new PHPUnit_Extensions_Database_Operation_Exception($this->operationName, $query, $args, $table, $e->getMessage()); + } + } + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/Operation/RowBased.php b/tests/PHPUnit/Extensions/Database/Operation/RowBased.php new file mode 100755 index 00000000..fc86e2a0 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/Operation/RowBased.php @@ -0,0 +1,125 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/Operation/IDatabaseOperation.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Exception.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides basic functionality for row based operations. + * + * To create a row based operation you must create two functions. The first + * one, buildOperationQuery(), must return a query that will be used to create + * a prepared statement. The second one, buildOperationArguments(), should + * return an array containing arguments for each row. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +abstract class PHPUnit_Extensions_Database_Operation_RowBased implements PHPUnit_Extensions_Database_Operation_IDatabaseOperation +{ + const ITERATOR_TYPE_FORWARD = 0; + const ITERATOR_TYPE_REVERSE = 1; + + protected $operationName; + + protected $iteratorDirection = self::ITERATOR_TYPE_FORWARD; + + protected abstract function buildOperationQuery(PHPUnit_Extensions_Database_DataSet_ITableMetaData $databaseTableMetaData, PHPUnit_Extensions_Database_DataSet_ITable $table, PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection); + + protected abstract function buildOperationArguments(PHPUnit_Extensions_Database_DataSet_ITableMetaData $databaseTableMetaData, PHPUnit_Extensions_Database_DataSet_ITable $table, $row); + + /** + * @param PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection + * @param PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet + */ + public function execute(PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection, PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet) + { + $databaseDataSet = $connection->createDataSet(); + + $dsIterator = $this->iteratorDirection == self::ITERATOR_TYPE_REVERSE ? $dataSet->getReverseIterator() : $dataSet->getIterator(); + + foreach ($dsIterator as $table) { + /* @var $table PHPUnit_Extensions_Database_DataSet_ITable */ + $databaseTableMetaData = $databaseDataSet->getTableMetaData($table->getTableMetaData()->getTableName()); + $query = $this->buildOperationQuery($databaseTableMetaData, $table, $connection); + + if ($query === FALSE && $table->getRowCount() > 0) { + throw new PHPUnit_Extensions_Database_Operation_Exception($this->operationName, '', array(), $table, "Rows requested for insert, but no columns provided!"); + } + + $statement = $connection->getConnection()->prepare($query); + for ($i = 0; $i < $table->getRowCount(); $i++) { + $args = $this->buildOperationArguments($databaseTableMetaData, $table, $i); + try { + $statement->execute($args); + } catch (Exception $e) { + throw new PHPUnit_Extensions_Database_Operation_Exception($this->operationName, $query, $args, $table, $e->getMessage()); + } + } + } + } + + protected function buildPreparedColumnArray($columns, PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection) + { + $columnArray = array(); + foreach ($columns as $columnName) { + $columnArray[] = "{$connection->quoteSchemaObject($columnName)} = ?"; + } + return $columnArray; + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/Operation/Truncate.php b/tests/PHPUnit/Extensions/Database/Operation/Truncate.php new file mode 100755 index 00000000..a58934b8 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/Operation/Truncate.php @@ -0,0 +1,96 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/Operation/IDatabaseOperation.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Exception.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Executes a truncate against all tables in a dataset. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_Operation_Truncate implements PHPUnit_Extensions_Database_Operation_IDatabaseOperation +{ + protected $useCascade = FALSE; + + public function setCascade($cascade = TRUE) + { + $this->useCascade = $cascade; + } + + public function execute(PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection, PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet) + { + foreach ($dataSet as $table) { + /* @var $table PHPUnit_Extensions_Database_DataSet_ITable */ + $query = " + {$connection->getTruncateCommand()} {$connection->quoteSchemaObject($table->getTableMetaData()->getTableName())} + "; + + if ($this->useCascade && $connection->allowsCascading()) { + $query .= " CASCADE"; + } + + try { + $connection->getConnection()->query($query); + } catch (PDOException $e) { + throw new PHPUnit_Extensions_Database_Operation_Exception('TRUNCATE', $query, array(), $table, $e->getMessage()); + } + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/Operation/Update.php b/tests/PHPUnit/Extensions/Database/Operation/Update.php new file mode 100755 index 00000000..67fa360f --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/Operation/Update.php @@ -0,0 +1,103 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/Operation/RowBased.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Exception.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Updates the rows in a given dataset using primary key columns. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Extensions_Database_Operation_Update extends PHPUnit_Extensions_Database_Operation_RowBased +{ + + protected $operationName = 'UPDATE'; + + protected function buildOperationQuery(PHPUnit_Extensions_Database_DataSet_ITableMetaData $databaseTableMetaData, PHPUnit_Extensions_Database_DataSet_ITable $table, PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection) + { + $keys = $databaseTableMetaData->getPrimaryKeys(); + $columns = $table->getTableMetaData()->getColumns(); + + $whereStatement = 'WHERE ' . implode(' AND ', $this->buildPreparedColumnArray($keys, $connection)); + $setStatement = 'SET ' . implode(', ', $this->buildPreparedColumnArray($columns, $connection)); + + $query = " + UPDATE {$connection->quoteSchemaObject($table->getTableMetaData()->getTableName())} + {$setStatement} + {$whereStatement} + "; + + return $query; + } + + protected function buildOperationArguments(PHPUnit_Extensions_Database_DataSet_ITableMetaData $databaseTableMetaData, PHPUnit_Extensions_Database_DataSet_ITable $table, $row) + { + $args = array(); + foreach ($table->getTableMetaData()->getColumns() as $columnName) { + $args[] = $table->getValue($row, $columnName); + } + + foreach ($databaseTableMetaData->getPrimaryKeys() as $columnName) { + $args[] = $table->getValue($row, $columnName); + } + + return $args; + } +} +?> diff --git a/tests/PHPUnit/Extensions/Database/TestCase.php b/tests/PHPUnit/Extensions/Database/TestCase.php new file mode 100755 index 00000000..46ced682 --- /dev/null +++ b/tests/PHPUnit/Extensions/Database/TestCase.php @@ -0,0 +1,254 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Extensions/Database/DefaultTester.php'; +require_once 'PHPUnit/Extensions/Database/DB/DefaultDatabaseConnection.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Factory.php'; +require_once 'PHPUnit/Extensions/Database/Constraint/TableIsEqual.php'; +require_once 'PHPUnit/Extensions/Database/Constraint/DataSetIsEqual.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * A TestCase extension that provides functionality for testing and asserting + * against a real database. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +abstract class PHPUnit_Extensions_Database_TestCase extends PHPUnit_Framework_TestCase +{ + + /** + * @var PHPUnit_Extensions_Database_ITester + */ + protected $databaseTester; + + /** + * Closes the specified connection. + * + * @param PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection + */ + protected function closeConnection(PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection) + { + $this->getDatabaseTester()->closeConnection($connection); + } + + /** + * Returns the test database connection. + * + * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection + */ + protected abstract function getConnection(); + + /** + * Gets the IDatabaseTester for this testCase. If the IDatabaseTester is + * not set yet, this method calls newDatabaseTester() to obtain a new + * instance. + * + * @return PHPUnit_Extensions_Database_ITester + */ + protected function getDatabaseTester() + { + if (empty($this->databaseTester)) { + $this->databaseTester = $this->newDatabaseTester(); + } + + return $this->databaseTester; + } + + /** + * Returns the test dataset. + * + * @return PHPUnit_Extensions_Database_DataSet_IDataSet + */ + protected abstract function getDataSet(); + + /** + * Returns the database operation executed in test setup. + * + * @return PHPUnit_Extensions_Database_Operation_DatabaseOperation + */ + protected function getSetUpOperation() + { + return PHPUnit_Extensions_Database_Operation_Factory::CLEAN_INSERT(); + } + + /** + * Returns the database operation executed in test cleanup. + * + * @return PHPUnit_Extensions_Database_Operation_DatabaseOperation + */ + protected function getTearDownOperation() + { + return PHPUnit_Extensions_Database_Operation_Factory::NONE(); + } + + /** + * Creates a IDatabaseTester for this testCase. + * + * @return PHPUnit_Extensions_Database_ITester + */ + protected function newDatabaseTester() + { + return new PHPUnit_Extensions_Database_DefaultTester($this->getConnection()); + } + + /** + * Creates a new DefaultDatabaseConnection using the given PDO connection + * and database schema name. + * + * @param PDO $connection + * @param string $schema + * @return PHPUnit_Extensions_Database_DB_DefaultDatabaseConnection + */ + protected function createDefaultDBConnection(PDO $connection, $schema) + { + return new PHPUnit_Extensions_Database_DB_DefaultDatabaseConnection($connection, $schema); + } + + /** + * Creates a new FlatXmlDataSet with the given $xmlFile. (absolute path.) + * + * @param string $xmlFile + * @return PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet + */ + protected function createFlatXMLDataSet($xmlFile) + { + require_once 'PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php'; + return new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet($xmlFile); + } + + /** + * Creates a new XMLDataSet with the given $xmlFile. (absolute path.) + * + * @param string $xmlFile + * @return PHPUnit_Extensions_Database_DataSet_XmlDataSet + */ + protected function createXMLDataSet($xmlFile) + { + require_once 'PHPUnit/Extensions/Database/DataSet/XmlDataSet.php'; + return new PHPUnit_Extensions_Database_DataSet_XmlDataSet($xmlFile); + } + + /** + * Returns an operation factory instance that can be used to instantiate + * new operations. + * + * @return PHPUnit_Extensions_Database_Operation_Factory + */ + protected function getOperations() + { + require_once 'PHPUnit/Extensions/Database/Operation/Factory.php'; + return new PHPUnit_Extensions_Database_Operation_Factory(); + } + + /** + * Performs operation returned by getSetUpOperation(). + */ + protected function setUp() + { + parent::setUp(); + + $this->getDatabaseTester()->setSetUpOperation($this->getSetUpOperation()); + $this->getDatabaseTester()->setDataSet($this->getDataSet()); + $this->getDatabaseTester()->onSetUp(); + } + + /** + * Performs operation returned by getSetUpOperation(). + */ + protected function tearDown() + { + $this->getDatabaseTester()->setTearDownOperation($this->getTearDownOperation()); + $this->getDatabaseTester()->setDataSet($this->getDataSet()); + $this->getDatabaseTester()->onTearDown(); + + /** + * Destroy the tester after the test is run to keep DB connections + * from piling up. + */ + $this->databaseTester = NULL; + } + + /** + * Asserts that two given tables are equal. + * + * @param PHPUnit_Extensions_Database_DataSet_ITable $expected + * @param PHPUnit_Extensions_Database_DataSet_ITable $actual + * @param string $message + */ + public static function assertTablesEqual(PHPUnit_Extensions_Database_DataSet_ITable $expected, PHPUnit_Extensions_Database_DataSet_ITable $actual, $message = '') + { + $constraint = new PHPUnit_Extensions_Database_Constraint_TableIsEqual($expected); + + self::assertThat($actual, $constraint, $message); + } + + /** + * Asserts that two given datasets are equal. + * + * @param PHPUnit_Extensions_Database_DataSet_ITable $expected + * @param PHPUnit_Extensions_Database_DataSet_ITable $actual + * @param string $message + */ + public static function assertDataSetsEqual(PHPUnit_Extensions_Database_DataSet_IDataSet $expected, PHPUnit_Extensions_Database_DataSet_IDataSet $actual, $message = '') + { + $constraint = new PHPUnit_Extensions_Database_Constraint_DataSetIsEqual($expected); + + self::assertThat($actual, $constraint, $message); + } +} +?> diff --git a/tests/PHPUnit/Extensions/GroupTestSuite.php b/tests/PHPUnit/Extensions/GroupTestSuite.php new file mode 100755 index 00000000..b70a16c9 --- /dev/null +++ b/tests/PHPUnit/Extensions/GroupTestSuite.php @@ -0,0 +1,110 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * We have a TestSuite object A. + * In TestSuite object A we have Tests tagged with @group. + * We want a TestSuite object B that contains TestSuite objects C, D, ... + * for the Tests tagged with @group C, @group D, ... + * Running the Tests from TestSuite object B results in Tests tagged with both + * @group C and @group D in TestSuite object A to be run twice . + * + * + * $suite = new PHPUnit_Extensions_GroupTestSuite($A, array('C', 'D')); + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class PHPUnit_Extensions_GroupTestSuite extends PHPUnit_Framework_TestSuite +{ + public function __construct(PHPUnit_Framework_TestSuite $suite, array $groups) + { + $groupSuites = array(); + $name = $suite->getName(); + + foreach ($groups as $group) { + $groupSuites[$group] = new PHPUnit_Framework_TestSuite($name . ' - ' . $group); + $this->addTest($groupSuites[$group]); + } + + $tests = new RecursiveIteratorIterator( + new PHPUnit_Util_TestSuiteIterator($suite), + RecursiveIteratorIterator::LEAVES_ONLY + ); + + foreach ($tests as $test) { + if ($test instanceof PHPUnit_Framework_TestCase) { + $class = new ReflectionClass($test); + $method = $class->getMethod($test->getName(FALSE)); + + $testGroups = PHPUnit_Util_Test::getGroups( + $method->getDocComment(), PHPUnit_Util_Test::getGroups($class) + ); + + foreach ($groups as $group) { + foreach ($testGroups as $testGroup) { + if ($group == $testGroup) { + $groupSuites[$group]->addTest($test); + } + } + } + } + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/OutputTestCase.php b/tests/PHPUnit/Extensions/OutputTestCase.php new file mode 100755 index 00000000..f132aa5f --- /dev/null +++ b/tests/PHPUnit/Extensions/OutputTestCase.php @@ -0,0 +1,195 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * A TestCase that expects a specified output. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +abstract class PHPUnit_Extensions_OutputTestCase extends PHPUnit_Framework_TestCase +{ + /** + * @var string + */ + protected $expectedRegex = NULL; + + /** + * @var string + */ + protected $expectedString = NULL; + + /** + * @var string + */ + protected $output = ''; + + /** + * @var mixed + */ + protected $outputCallback = FALSE; + + /** + * @return bool + */ + public function setOutputCallback($callback) + { + if (is_callable($callback)) { + $this->outputCallback = $callback; + $set = TRUE; + } else { + $set = FALSE; + } + + return $set; + } + + /** + * @return string + */ + public function normalizeOutput($buffer) + { + return str_replace("\r", '', $buffer); + } + + /** + * @return string + */ + public function getActualOutput() + { + return $this->output; + } + + /** + * @return string + */ + public function expectedRegex() + { + return $this->expectedRegex; + } + + /** + * @param string $expectedRegex + */ + public function expectOutputRegex($expectedRegex) + { + if ($this->expectedString !== NULL) { + throw new RuntimeException; + } + + if (is_string($expectedRegex) || is_null($expectedRegex)) { + $this->expectedRegex = $expectedRegex; + } + } + + /** + * @return string + */ + public function expectedString() + { + return $this->expectedOutput; + } + + /** + * @param string $expectedString + */ + public function expectOutputString($expectedString) + { + if ($this->expectedRegex !== NULL) { + throw new RuntimeException; + } + + if (is_string($expectedString) || is_null($expectedString)) { + $this->expectedString = $expectedString; + } + } + + /** + */ + protected function runTest() + { + ob_start(); + + try { + parent::runTest(); + } + + catch (Exception $e) { + ob_end_clean(); + throw $e; + } + + if ($this->outputCallback === FALSE) { + $this->output = ob_get_contents(); + } else { + $this->output = call_user_func_array($this->outputCallback, array(ob_get_contents())); + } + + ob_end_clean(); + + if ($this->expectedRegex !== NULL) { + $this->assertRegExp($this->expectedRegex, $this->output); + $this->expectedRegex = NULL; + } + + else if ($this->expectedString !== NULL) { + $this->assertEquals($this->expectedString, $this->output); + $this->expectedString = NULL; + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/PerformanceTestCase.php b/tests/PHPUnit/Extensions/PerformanceTestCase.php new file mode 100755 index 00000000..d4e9b45c --- /dev/null +++ b/tests/PHPUnit/Extensions/PerformanceTestCase.php @@ -0,0 +1,118 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.1.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Timer.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * A TestCase that expects a TestCase to be executed + * meeting a given time limit. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.1.0 + */ +abstract class PHPUnit_Extensions_PerformanceTestCase extends PHPUnit_Framework_TestCase +{ + /** + * @var integer + */ + protected $maxRunningTime = 0; + + /** + */ + protected function runTest() + { + PHPUnit_Util_Timer::start(); + parent::runTest(); + $time = PHPUnit_Util_Timer::stop(); + + if ($this->maxRunningTime != 0 && + $time > $this->maxRunningTime) { + $this->fail( + sprintf( + 'expected running time: <= %s but was: %s', + + $this->maxRunningTime, + $time + ) + ); + } + } + + /** + * @param integer $maxRunningTime + * @throws InvalidArgumentException + * @since Method available since Release 2.3.0 + */ + public function setMaxRunningTime($maxRunningTime) + { + if (is_integer($maxRunningTime) && + $maxRunningTime >= 0) { + $this->maxRunningTime = $maxRunningTime; + } else { + throw new InvalidArgumentException; + } + } + + /** + * @return integer + * @since Method available since Release 2.3.0 + */ + public function getMaxRunningTime() + { + return $this->maxRunningTime; + } +} +?> diff --git a/tests/PHPUnit/Extensions/PhptTestCase.php b/tests/PHPUnit/Extensions/PhptTestCase.php new file mode 100755 index 00000000..6fdff71e --- /dev/null +++ b/tests/PHPUnit/Extensions/PhptTestCase.php @@ -0,0 +1,271 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.1.4 + */ + +if (PHPUnit_Util_Filesystem::fileExistsInIncludePath('PEAR/RunTest.php')) { + $currentErrorReporting = error_reporting(E_ERROR | E_WARNING | E_PARSE); + PHPUnit_Util_Filesystem::collectStart(); + require_once 'PEAR/RunTest.php'; + error_reporting($currentErrorReporting); + + foreach (PHPUnit_Util_Filesystem::collectEnd() as $blacklistedFile) { + PHPUnit_Util_Filter::addFileToFilter($blacklistedFile, 'PHPUNIT'); + } +} + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Extensions/PhptTestCase/Logger.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Wrapper to run .phpt test cases. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.1.4 + */ +class PHPUnit_Extensions_PhptTestCase implements PHPUnit_Framework_Test, PHPUnit_Framework_SelfDescribing +{ + /** + * The filename of the .phpt file. + * + * @var string + */ + protected $filename; + + /** + * Options for PEAR_RunTest. + * + * @var array + */ + protected $options = array(); + + /** + * Constructs a test case with the given filename. + * + * @param string $filename + * @param array $options + */ + public function __construct($filename, $options = array()) + { + if (!is_string($filename)) { + throw new InvalidArgumentException; + } + + if (!is_file($filename)) { + throw new RuntimeException( + sprintf( + 'File "%s" does not exist.', + $filename + ) + ); + } + + if (!is_array($options)) { + throw new InvalidArgumentException; + } + + $this->filename = $filename; + $this->options = $options; + } + + /** + * Counts the number of test cases executed by run(TestResult result). + * + * @return integer + */ + public function count() + { + return 1; + } + + /** + * Runs a test and collects its result in a TestResult instance. + * + * @param PHPUnit_Framework_TestResult $result + * @param array $options + * @return PHPUnit_Framework_TestResult + */ + public function run(PHPUnit_Framework_TestResult $result = NULL, $options = array()) + { + if (!class_exists('PEAR_RunTest', FALSE)) { + throw new RuntimeException('Class PEAR_RunTest not found.'); + } + + if (isset($GLOBALS['_PEAR_destructor_object_list']) && + is_array($GLOBALS['_PEAR_destructor_object_list']) && + !empty($GLOBALS['_PEAR_destructor_object_list'])) { + $pearDestructorObjectListCount = count($GLOBALS['_PEAR_destructor_object_list']); + } else { + $pearDestructorObjectListCount = 0; + } + + if ($result === NULL) { + $result = new PHPUnit_Framework_TestResult; + } + + if (!is_array($options)) { + throw new InvalidArgumentException; + } + + $coverage = $result->getCollectCodeCoverageInformation(); + $options = array_merge($options, $this->options); + + if (!isset($options['include_path'])) { + $options['include_path'] = get_include_path(); + } + + if ($coverage) { + $options['coverage'] = TRUE; + } else { + $options['coverage'] = FALSE; + } + + $currentErrorReporting = error_reporting(E_ERROR | E_WARNING | E_PARSE); + $runner = new PEAR_RunTest(new PHPUnit_Extensions_PhptTestCase_Logger, $options); + + if ($coverage) { + $runner->xdebug_loaded = TRUE; + } else { + $runner->xdebug_loaded = FALSE; + } + + $result->startTest($this); + + PHPUnit_Util_Timer::start(); + $buffer = $runner->run($this->filename, $options); + $time = PHPUnit_Util_Timer::stop(); + error_reporting($currentErrorReporting); + $base = basename($this->filename); + $path = dirname($this->filename); + $coverageFile = $path . DIRECTORY_SEPARATOR . str_replace('.phpt', '.xdebug', $base); + $diffFile = $path . DIRECTORY_SEPARATOR . str_replace('.phpt', '.diff', $base); + $expFile = $path . DIRECTORY_SEPARATOR . str_replace('.phpt', '.exp', $base); + $logFile = $path . DIRECTORY_SEPARATOR . str_replace('.phpt', '.log', $base); + $outFile = $path . DIRECTORY_SEPARATOR . str_replace('.phpt', '.out', $base); + $phpFile = $path . DIRECTORY_SEPARATOR . str_replace('.phpt', '.php', $base); + + if (is_object($buffer) && $buffer instanceof PEAR_Error) { + $result->addError( + $this, + new RuntimeException($buffer->getMessage()), + $time + ); + } + + else if ($buffer == 'SKIPPED') { + $result->addFailure($this, new PHPUnit_Framework_SkippedTestError, 0); + } + + else if ($buffer != 'PASSED') { + $result->addFailure( + $this, + PHPUnit_Framework_ComparisonFailure::diffEqual( + file_get_contents($expFile), + file_get_contents($outFile) + ), + $time + ); + } + + foreach (array($diffFile, $expFile, $logFile, $phpFile, $outFile) as $file) { + if (file_exists($file)) { + unlink($file); + } + } + + if ($coverage && file_exists($coverageFile)) { + eval('$coverageData = ' . file_get_contents($coverageFile) . ';'); + unset($coverageData[$phpFile]); + + $result->appendCodeCoverageInformation($this, $coverageData); + unlink($coverageFile); + } + + $result->endTest($this, $time); + + // Do not invoke PEAR's destructor mechanism for PHP 4 + // as it raises an E_STRICT. + if ($pearDestructorObjectListCount == 0) { + unset($GLOBALS['_PEAR_destructor_object_list']); + } else { + $count = count($GLOBALS['_PEAR_destructor_object_list']) - $pearDestructorObjectListCount; + + for ($i = 0; $i < $count; $i++) { + array_pop($GLOBALS['_PEAR_destructor_object_list']); + } + } + + return $result; + } + + /** + * Returns the name of the test case. + * + * @return string + */ + public function getName() + { + return $this->toString(); + } + + /** + * Returns a string representation of the test case. + * + * @return string + */ + public function toString() + { + return $this->filename; + } +} +?> diff --git a/tests/PHPUnit/Extensions/PhptTestCase/Logger.php b/tests/PHPUnit/Extensions/PhptTestCase/Logger.php new file mode 100755 index 00000000..ac9a0279 --- /dev/null +++ b/tests/PHPUnit/Extensions/PhptTestCase/Logger.php @@ -0,0 +1,69 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.1.4 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Dummy logger for PEAR_RunTest. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.1.4 + */ +class PHPUnit_Extensions_PhptTestCase_Logger +{ + public function log($level, $msg, $append_crlf = TRUE) + { + } +} +?> diff --git a/tests/PHPUnit/Extensions/PhptTestSuite.php b/tests/PHPUnit/Extensions/PhptTestSuite.php new file mode 100755 index 00000000..c1a0f691 --- /dev/null +++ b/tests/PHPUnit/Extensions/PhptTestSuite.php @@ -0,0 +1,95 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.1.4 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/FilterIterator.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Suite for .phpt test cases. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.1.4 + */ +class PHPUnit_Extensions_PhptTestSuite extends PHPUnit_Framework_TestSuite +{ + /** + * Constructs a new TestSuite for .phpt test cases. + * + * @param string $directory + * @param array $options Array with ini settings for the php instance run, + * key being the name if the setting, value the ini value. + * @throws InvalidArgumentException + */ + public function __construct($directory, $options = array()) + { + if (is_dir($directory)) { + $this->setName($directory); + + $iterator = new PHPUnit_Util_FilterIterator( + new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($directory) + ), + '.phpt' + ); + + foreach ($iterator as $testFile) { + $this->addTestFile($testFile->getPathname(), TRUE, $options); + } + } else { + throw new InvalidArgumentException; + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/RepeatedTest.php b/tests/PHPUnit/Extensions/RepeatedTest.php new file mode 100755 index 00000000..74a6d831 --- /dev/null +++ b/tests/PHPUnit/Extensions/RepeatedTest.php @@ -0,0 +1,153 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Extensions/TestDecorator.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * A Decorator that runs a test repeatedly. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class PHPUnit_Extensions_RepeatedTest extends PHPUnit_Extensions_TestDecorator +{ + /** + * @var mixed + */ + protected $filter = FALSE; + + /** + * @var array + */ + protected $groups = array(); + + /** + * @var array + */ + protected $excludeGroups = array(); + + /** + * @var integer + */ + protected $timesRepeat = 1; + + /** + * Constructor. + * + * @param PHPUnit_Framework_Test $test + * @param integer $timesRepeat + * @param mixed $filter + * @param array $groups + * @param array $excludeGroups + * @throws InvalidArgumentException + */ + public function __construct(PHPUnit_Framework_Test $test, $timesRepeat = 1, $filter = FALSE, array $groups = array(), array $excludeGroups = array()) + { + parent::__construct($test); + + if (is_integer($timesRepeat) && + $timesRepeat >= 0) { + $this->timesRepeat = $timesRepeat; + } else { + throw new InvalidArgumentException( + 'Argument 2 must be a positive integer.' + ); + } + + $this->filter = $filter; + $this->groups = $groups; + $this->excludeGroups = $excludeGroups; + } + + /** + * Counts the number of test cases that + * will be run by this test. + * + * @return integer + */ + public function count() + { + return $this->timesRepeat * count($this->test); + } + + /** + * Runs the decorated test and collects the + * result in a TestResult. + * + * @param PHPUnit_Framework_TestResult $result + * @return PHPUnit_Framework_TestResult + * @throws InvalidArgumentException + */ + public function run(PHPUnit_Framework_TestResult $result = NULL) + { + if ($result === NULL) { + $result = $this->createResult(); + } + + for ($i = 0; $i < $this->timesRepeat && !$result->shouldStop(); $i++) { + if ($this->test instanceof PHPUnit_Framework_TestSuite) { + $this->test->run( + $result, $this->filter, $this->groups, $this->excludeGroups + ); + } else { + $this->test->run($result); + } + } + + return $result; + } +} +?> diff --git a/tests/PHPUnit/Extensions/SeleniumTestCase.php b/tests/PHPUnit/Extensions/SeleniumTestCase.php new file mode 100755 index 00000000..bfcdea9b --- /dev/null +++ b/tests/PHPUnit/Extensions/SeleniumTestCase.php @@ -0,0 +1,1317 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Log/Database.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Test.php'; +require_once 'PHPUnit/Util/XML.php'; +require_once 'PHPUnit/Extensions/SeleniumTestCase/Driver.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * TestCase class that uses Selenium to provide + * the functionality required for web testing. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +abstract class PHPUnit_Extensions_SeleniumTestCase extends PHPUnit_Framework_TestCase +{ + /** + * @var array + */ + public static $browsers = array(); + + /** + * @var boolean + */ + protected $autoStop = TRUE; + + /** + * @var string + */ + protected $browserName; + + /** + * @var boolean + */ + protected $collectCodeCoverageInformation = FALSE; + + /** + * @var string + */ + protected $coverageScriptUrl = ''; + + /** + * @var PHPUnit_Extensions_SeleniumTestCase_Driver[] + */ + protected $drivers = array(); + + /** + * @var boolean + */ + protected $inDefaultAssertions = FALSE; + + /** + * @var string + */ + protected $testId; + + /** + * @var array + * @access protected + */ + protected $verificationErrors = array(); + + /** + * @param string $name + * @param array $data + * @param string $dataName + * @param array $browser + * @throws InvalidArgumentException + */ + public function __construct($name = NULL, array $data = array(), $dataName = '', array $browser = array()) + { + parent::__construct($name, $data, $dataName); + $this->testId = md5(uniqid(rand(), TRUE)); + $this->getDriver($browser); + } + + /** + * @param string $className + * @return PHPUnit_Framework_TestSuite + */ + public static function suite($className) + { + $suite = new PHPUnit_Framework_TestSuite; + $suite->setName($className); + + $class = new ReflectionClass($className); + $classGroups = PHPUnit_Util_Test::getGroups($class->getDocComment()); + $staticProperties = $class->getStaticProperties(); + + // Create tests from Selenese/HTML files. + if (isset($staticProperties['seleneseDirectory']) && + is_dir($staticProperties['seleneseDirectory'])) { + $files = array_merge( + self::getSeleneseFiles($staticProperties['seleneseDirectory'], '.htm'), + self::getSeleneseFiles($staticProperties['seleneseDirectory'], '.html') + ); + + // Create tests from Selenese/HTML files for multiple browsers. + if (!empty($staticProperties['browsers'])) { + foreach ($staticProperties['browsers'] as $browser) { + $browserSuite = new PHPUnit_Framework_TestSuite; + $browserSuite->setName($className . ': ' . $browser['name']); + + foreach ($files as $file) { + $browserSuite->addTest( + new $className($file, array(), '', $browser), + $classGroups + ); + } + + $suite->addTest($browserSuite); + } + } + + // Create tests from Selenese/HTML files for single browser. + else { + foreach ($files as $file) { + $suite->addTest(new $className($file), $classGroups); + } + } + } + + // Create tests from test methods for multiple browsers. + if (!empty($staticProperties['browsers'])) { + foreach ($staticProperties['browsers'] as $browser) { + $browserSuite = new PHPUnit_Framework_TestSuite; + $browserSuite->setName($className . ': ' . $browser['name']); + + foreach ($class->getMethods() as $method) { + if (PHPUnit_Framework_TestSuite::isPublicTestMethod($method)) { + $name = $method->getName(); + $methodDocComment = $method->getDocComment(); + $data = PHPUnit_Util_Test::getProvidedData($className, $name, $methodDocComment); + $groups = PHPUnit_Util_Test::getGroups($methodDocComment, $classGroups); + + // Test method with @dataProvider. + if (is_array($data) || $data instanceof Iterator) { + $dataSuite = new PHPUnit_Framework_TestSuite( + $className . '::' . $name + ); + + foreach ($data as $_dataName => $_data) { + $dataSuite->addTest( + new $className($name, $_data, $_dataName, $browser), + $groups + ); + } + + $browserSuite->addTest($dataSuite); + } + + // Test method without @dataProvider. + else { + $browserSuite->addTest( + new $className($name, array(), '', $browser), $groups + ); + } + } + } + + $suite->addTest($browserSuite); + } + } + + // Create tests from test methods for single browser. + else { + foreach ($class->getMethods() as $method) { + if (PHPUnit_Framework_TestSuite::isPublicTestMethod($method)) { + $name = $method->getName(); + $methodDocComment = $method->getDocComment(); + $data = PHPUnit_Util_Test::getProvidedData($className, $name, $methodDocComment); + $groups = PHPUnit_Util_Test::getGroups($methodDocComment, $classGroups); + + // Test method with @dataProvider. + if (is_array($data) || $data instanceof Iterator) { + $dataSuite = new PHPUnit_Framework_TestSuite( + $className . '::' . $name + ); + + foreach ($data as $_dataName => $_data) { + $dataSuite->addTest( + new $className($name, $_data, $_dataName), + $groups + ); + } + + $suite->addTest($dataSuite); + } + + // Test method without @dataProvider. + else { + $suite->addTest( + new $className($name), $groups + ); + } + } + } + } + + return $suite; + } + + /** + * Runs the test case and collects the results in a TestResult object. + * If no TestResult object is passed a new one will be created. + * + * @param PHPUnit_Framework_TestResult $result + * @return PHPUnit_Framework_TestResult + * @throws InvalidArgumentException + */ + public function run(PHPUnit_Framework_TestResult $result = NULL) + { + if ($result === NULL) { + $result = $this->createResult(); + } + + $this->collectCodeCoverageInformation = $result->getCollectCodeCoverageInformation(); + + foreach ($this->drivers as $driver) { + $driver->setCollectCodeCoverageInformation( + $this->collectCodeCoverageInformation + ); + } + + $result->run($this); + + if ($this->collectCodeCoverageInformation) { + $result->appendCodeCoverageInformation( + $this, $this->getCodeCoverage() + ); + } + + return $result; + } + + /** + * @param array $browser + * @return PHPUnit_Extensions_SeleniumTestCase_Driver + * @since Method available since Release 3.3.0 + */ + protected function getDriver(array $browser) + { + if (isset($browser['name'])) { + if (!is_string($browser['name'])) { + throw new InvalidArgumentException; + } + } else { + $browser['name'] = ''; + } + + if (isset($browser['browser'])) { + if (!is_string($browser['browser'])) { + throw new InvalidArgumentException; + } + } else { + $browser['browser'] = ''; + } + + if (isset($browser['host'])) { + if (!is_string($browser['host'])) { + throw new InvalidArgumentException; + } + } else { + $browser['host'] = 'localhost'; + } + + if (isset($browser['port'])) { + if (!is_int($browser['port'])) { + throw new InvalidArgumentException; + } + } else { + $browser['port'] = 4444; + } + + if (isset($browser['timeout'])) { + if (!is_int($browser['timeout'])) { + throw new InvalidArgumentException; + } + } else { + $browser['timeout'] = 30000; + } + + $driver = new PHPUnit_Extensions_SeleniumTestCase_Driver; + $driver->setName($browser['name']); + $driver->setBrowser($browser['browser']); + $driver->setHost($browser['host']); + $driver->setPort($browser['port']); + $driver->setTimeout($browser['timeout']); + $driver->setTestCase($this); + $driver->setTestId($this->testId); + + $this->drivers[] = $driver; + + return $driver; + } + + /** + */ + protected function runTest() + { + $this->start(); + + if (!is_file($this->name)) { + parent::runTest(); + } else { + $this->runSelenese($this->name); + } + + if ($this->autoStop) { + try { + $this->stop(); + } + + catch (RuntimeException $e) { + } + } + + if (!empty($this->verificationErrors)) { + $this->fail(implode("\n", $this->verificationErrors)); + } + } + + /** + * If you want to override tearDown() make sure to either call stop() or + * parent::tearDown(). Otherwise the Selenium RC session will not be + * closed upon test failure. + * + */ + protected function tearDown() + { + if ($this->autoStop) { + try { + $this->stop(); + } + + catch (RuntimeException $e) { + } + } + } + + /** + * Returns a string representation of the test case. + * + * @return string + */ + public function toString() + { + $buffer = parent::toString(); + + if (!empty($this->browserName)) { + $buffer .= ' with browser ' . $this->browserName; + } + + return $buffer; + } + + /** + * @param boolean $autoStop + * @throws InvalidArgumentException + */ + public function setAutoStop($autoStop) + { + if (!is_bool($autoStop)) { + throw new InvalidArgumentException; + } + + $this->autoStop = $autoStop; + } + + /** + * Runs a test from a Selenese (HTML) specification. + * + * @param string $filename + */ + public function runSelenese($filename) + { + $document = PHPUnit_Util_XML::loadFile($filename, TRUE); + $xpath = new DOMXPath($document); + $rows = $xpath->query('body/table/tbody/tr'); + + foreach ($rows as $row) + { + $action = NULL; + $arguments = array(); + $columns = $xpath->query('td', $row); + + foreach ($columns as $column) + { + if ($action === NULL) { + $action = $column->nodeValue; + } else { + $arguments[] = $column->nodeValue; + } + } + + if (method_exists($this, $action)) { + call_user_func_array(array($this, $action), $arguments); + } else { + $this->__call($action, $arguments); + } + } + } + + /** + * Delegate method calls to the driver. + * + * @param string $command + * @param array $arguments + * @return mixed + * @method unknown addLocationStrategy() + * @method unknown addSelection() + * @method unknown addSelectionAndWait() + * @method unknown allowNativeXpath() + * @method unknown altKeyDown() + * @method unknown altKeyDownAndWait() + * @method unknown altKeyUp() + * @method unknown altKeyUpAndWait() + * @method unknown answerOnNextPrompt() + * @method unknown assignId() + * @method unknown break() + * @method unknown captureEntirePageScreenshot() + * @method unknown captureScreenshot() + * @method unknown check() + * @method unknown chooseCancelOnNextConfirmation() + * @method unknown chooseOkOnNextConfirmation() + * @method unknown click() + * @method unknown clickAndWait() + * @method unknown clickAt() + * @method unknown clickAtAndWait() + * @method unknown close() + * @method unknown contextMenu() + * @method unknown contextMenuAndWait() + * @method unknown contextMenuAt() + * @method unknown contextMenuAtAndWait() + * @method unknown controlKeyDown() + * @method unknown controlKeyDownAndWait() + * @method unknown controlKeyUp() + * @method unknown controlKeyUpAndWait() + * @method unknown createCookie() + * @method unknown createCookieAndWait() + * @method unknown deleteAllVisibleCookies() + * @method unknown deleteAllVisibleCookiesAndWait() + * @method unknown deleteCookie() + * @method unknown deleteCookieAndWait() + * @method unknown doubleClick() + * @method unknown doubleClickAndWait() + * @method unknown doubleClickAt() + * @method unknown doubleClickAtAndWait() + * @method unknown dragAndDrop() + * @method unknown dragAndDropAndWait() + * @method unknown dragAndDropToObject() + * @method unknown dragAndDropToObjectAndWait() + * @method unknown dragDrop() + * @method unknown dragDropAndWait() + * @method unknown echo() + * @method unknown fireEvent() + * @method unknown fireEventAndWait() + * @method unknown focus() + * @method string getAlert() + * @method array getAllButtons() + * @method array getAllFields() + * @method array getAllLinks() + * @method array getAllWindowIds() + * @method array getAllWindowNames() + * @method array getAllWindowTitles() + * @method string getAttribute() + * @method array getAttributeFromAllWindows() + * @method string getBodyText() + * @method string getConfirmation() + * @method string getCookie() + * @method integer getCursorPosition() + * @method integer getElementHeight() + * @method integer getElementIndex() + * @method integer getElementPositionLeft() + * @method integer getElementPositionTop() + * @method integer getElementWidth() + * @method string getEval() + * @method string getExpression() + * @method string getHtmlSource() + * @method string getLocation() + * @method string getLogMessages() + * @method integer getMouseSpeed() + * @method string getPrompt() + * @method array getSelectOptions() + * @method string getSelectedId() + * @method array getSelectedIds() + * @method string getSelectedIndex() + * @method array getSelectedIndexes() + * @method string getSelectedLabel() + * @method array getSelectedLabels() + * @method string getSelectedValue() + * @method array getSelectedValues() + * @method unknown getSpeed() + * @method unknown getSpeedAndWait() + * @method string getTable() + * @method string getText() + * @method string getTitle() + * @method string getValue() + * @method boolean getWhetherThisFrameMatchFrameExpression() + * @method boolean getWhetherThisWindowMatchWindowExpression() + * @method integer getXpathCount() + * @method unknown goBack() + * @method unknown goBackAndWait() + * @method unknown highlight() + * @method unknown highlightAndWait() + * @method unknown ignoreAttributesWithoutValue() + * @method boolean isAlertPresent() + * @method boolean isChecked() + * @method boolean isConfirmationPresent() + * @method boolean isEditable() + * @method boolean isElementPresent() + * @method boolean isOrdered() + * @method boolean isPromptPresent() + * @method boolean isSomethingSelected() + * @method boolean isTextPresent() + * @method boolean isVisible() + * @method unknown keyDown() + * @method unknown keyDownAndWait() + * @method unknown keyPress() + * @method unknown keyPressAndWait() + * @method unknown keyUp() + * @method unknown keyUpAndWait() + * @method unknown metaKeyDown() + * @method unknown metaKeyDownAndWait() + * @method unknown metaKeyUp() + * @method unknown metaKeyUpAndWait() + * @method unknown mouseDown() + * @method unknown mouseDownAndWait() + * @method unknown mouseDownAt() + * @method unknown mouseDownAtAndWait() + * @method unknown mouseMove() + * @method unknown mouseMoveAndWait() + * @method unknown mouseMoveAt() + * @method unknown mouseMoveAtAndWait() + * @method unknown mouseOut() + * @method unknown mouseOutAndWait() + * @method unknown mouseOver() + * @method unknown mouseOverAndWait() + * @method unknown mouseUp() + * @method unknown mouseUpAndWait() + * @method unknown mouseUpAt() + * @method unknown mouseUpAtAndWait() + * @method unknown mouseUpRight() + * @method unknown mouseUpRightAndWait() + * @method unknown mouseUpRightAt() + * @method unknown mouseUpRightAtAndWait() + * @method unknown open() + * @method unknown openWindow() + * @method unknown openWindowAndWait() + * @method unknown pause() + * @method unknown refresh() + * @method unknown refreshAndWait() + * @method unknown removeAllSelections() + * @method unknown removeAllSelectionsAndWait() + * @method unknown removeSelection() + * @method unknown removeSelectionAndWait() + * @method unknown runScript() + * @method unknown select() + * @method unknown selectAndWait() + * @method unknown selectFrame() + * @method unknown selectWindow() + * @method unknown setBrowserLogLevel() + * @method unknown setContext() + * @method unknown setCursorPosition() + * @method unknown setCursorPositionAndWait() + * @method unknown setMouseSpeed() + * @method unknown setMouseSpeedAndWait() + * @method unknown setSpeed() + * @method unknown setSpeedAndWait() + * @method unknown shiftKeyDown() + * @method unknown shiftKeyDownAndWait() + * @method unknown shiftKeyUp() + * @method unknown shiftKeyUpAndWait() + * @method unknown store() + * @method unknown storeAlert() + * @method unknown storeAlertPresent() + * @method unknown storeAllButtons() + * @method unknown storeAllFields() + * @method unknown storeAllLinks() + * @method unknown storeAllWindowIds() + * @method unknown storeAllWindowNames() + * @method unknown storeAllWindowTitle()s + * @method unknown storeAttribute() + * @method unknown storeAttributeFromAllWindows() + * @method unknown storeBodyText() + * @method unknown storeChecked() + * @method unknown storeConfirmation() + * @method unknown storeConfirmationPresent() + * @method unknown storeCookie() + * @method unknown storeCookieByName() + * @method unknown storeCookiePresent() + * @method unknown storeCursorPosition() + * @method unknown storeEditable() + * @method unknown storeElementHeight() + * @method unknown storeElementIndex() + * @method unknown storeElementPositionLeft() + * @method unknown storeElementPositionTop() + * @method unknown storeElementPresent() + * @method unknown storeElementWidth() + * @method unknown storeEval() + * @method unknown storeExpression() + * @method unknown storeHtmlSource() + * @method unknown storeLocation() + * @method unknown storeMouseSpeed() + * @method unknown storeOrdered() + * @method unknown storePrompt() + * @method unknown storePromptPresent() + * @method unknown storeSelectOptions() + * @method unknown storeSelectedId() + * @method unknown storeSelectedIds() + * @method unknown storeSelectedIndex() + * @method unknown storeSelectedIndexes() + * @method unknown storeSelectedLabel() + * @method unknown storeSelectedLabels() + * @method unknown storeSelectedValue() + * @method unknown storeSelectedValues() + * @method unknown storeSomethingSelected() + * @method unknown storeSpeed() + * @method unknown storeTable() + * @method unknown storeText() + * @method unknown storeTextPresent() + * @method unknown storeTitle() + * @method unknown storeValue() + * @method unknown storeVisible() + * @method unknown storeWhetherThisFrameMatchFrameExpression() + * @method unknown storeWhetherThisWindowMatchWindowExpression() + * @method unknown storeXpathCount() + * @method unknown submit() + * @method unknown submitAndWait() + * @method unknown type() + * @method unknown typeAndWait() + * @method unknown typeKeys() + * @method unknown typeKeysAndWait() + * @method unknown uncheck() + * @method unknown uncheckAndWait() + * @method unknown waitForCondition() + * @method unknown waitForPageToLoad() + * @method unknown waitForPopUp() + * @method unknown windowFocus() + * @method unknown windowMaximize() + */ + public function __call($command, $arguments) + { + return call_user_func_array( + array($this->drivers[0], $command), $arguments + ); + } + + /** + * Asserts that an alert is present. + * + * @param string $message + */ + public function assertAlertPresent($message = 'No alert present.') + { + $this->assertTrue($this->isAlertPresent(), $message); + } + + /** + * Asserts that no alert is present. + * + * @param string $message + */ + public function assertNoAlertPresent($message = 'Alert present.') + { + $this->assertFalse($this->isAlertPresent(), $message); + } + + /** + * Asserts that an option is checked. + * + * @param string $locator + * @param string $message + */ + public function assertChecked($locator, $message = '') + { + if ($message == '') { + $message = sprintf( + '"%s" not checked.', + $locator + ); + } + + $this->assertTrue($this->isChecked($locator), $message); + } + + /** + * Asserts that an option is not checked. + * + * @param string $locator + * @param string $message + */ + public function assertNotChecked($locator, $message = '') + { + if ($message == '') { + $message = sprintf( + '"%s" checked.', + $locator + ); + } + + $this->assertFalse($this->isChecked($locator), $message); + } + + /** + * Assert that a confirmation is present. + * + * @param string $message + */ + public function assertConfirmationPresent($message = 'No confirmation present.') + { + $this->assertTrue($this->isConfirmationPresent(), $message); + } + + /** + * Assert that no confirmation is present. + * + * @param string $message + */ + public function assertNoConfirmationPresent($message = 'Confirmation present.') + { + $this->assertFalse($this->isConfirmationPresent(), $message); + } + + /** + * Asserts that an input field is editable. + * + * @param string $locator + * @param string $message + */ + public function assertEditable($locator, $message = '') + { + if ($message == '') { + $message = sprintf( + '"%s" not editable.', + $locator + ); + } + + $this->assertTrue($this->isEditable($locator), $message); + } + + /** + * Asserts that an input field is not editable. + * + * @param string $locator + * @param string $message + */ + public function assertNotEditable($locator, $message = '') + { + if ($message == '') { + $message = sprintf( + '"%s" editable.', + $locator + ); + } + + $this->assertFalse($this->isEditable($locator), $message); + } + + /** + * Asserts that an element's value is equal to a given string. + * + * @param string $locator + * @param string $text + * @param string $message + */ + public function assertElementValueEquals($locator, $text, $message = '') + { + $this->assertEquals($text, $this->getValue($locator), $message); + } + + /** + * Asserts that an element's value is not equal to a given string. + * + * @param string $locator + * @param string $text + * @param string $message + */ + public function assertElementValueNotEquals($locator, $text, $message = '') + { + $this->assertNotEquals($text, $this->getValue($locator), $message); + } + + /** + * Asserts that an element contains a given string. + * + * @param string $locator + * @param string $text + * @param string $message + */ + public function assertElementContainsText($locator, $text, $message = '') + { + $this->assertContains($text, $this->getValue($locator), $message); + } + + /** + * Asserts that an element does not contain a given string. + * + * @param string $locator + * @param string $text + * @param string $message + */ + public function assertElementNotContainsText($locator, $text, $message = '') + { + $this->assertNotContains($text, $this->getValue($locator), $message); + } + + /** + * Asserts than an element is present. + * + * @param string $locator + * @param string $message + */ + public function assertElementPresent($locator, $message = '') + { + if ($message == '') { + $message = sprintf( + 'Element "%s" not present.', + $locator + ); + } + + $this->assertTrue($this->isElementPresent($locator), $message); + } + + /** + * Asserts than an element is not present. + * + * @param string $locator + * @param string $message + */ + public function assertElementNotPresent($locator, $message = '') + { + if ($message == '') { + $message = sprintf( + 'Element "%s" present.', + $locator + ); + } + + $this->assertFalse($this->isElementPresent($locator), $message); + } + + /** + * Asserts that the location is equal to a specified one. + * + * @param string $location + * @param string $message + */ + public function assertLocationEquals($location, $message = '') + { + $this->assertEquals($location, $this->getLocation(), $message); + } + + /** + * Asserts that the location is not equal to a specified one. + * + * @param string $location + * @param string $message + */ + public function assertLocationNotEquals($location, $message = '') + { + $this->assertNotEquals($location, $this->getLocation(), $message); + } + + /** + * Asserts than a prompt is present. + * + * @param string $message + */ + public function assertPromptPresent($message = 'No prompt present.') + { + $this->assertTrue($this->isPromptPresent(), $message); + } + + /** + * Asserts than no prompt is present. + * + * @param string $message + */ + public function assertNoPromptPresent($message = 'Prompt present.') + { + $this->assertFalse($this->isPromptPresent(), $message); + } + + /** + * Asserts that a select element has a specific option. + * + * @param string $selectLocator + * @param string $option + * @param string $message + * @since Method available since Release 3.2.0 + */ + public function assertSelectHasOption($selectLocator, $option, $message = '') + { + $this->assertContains($option, $this->getSelectOptions($selectLocator), $message); + } + + /** + * Asserts that a select element does not have a specific option. + * + * @param string $selectLocator + * @param string $option + * @param string $message + * @since Method available since Release 3.2.0 + */ + public function assertSelectNotHasOption($selectLocator, $option, $message = '') + { + $this->assertNotContains($option, $this->getSelectOptions($selectLocator), $message); + } + + /** + * Asserts that a specific label is selected. + * + * @param string $selectLocator + * @param string $value + * @param string $message + * @since Method available since Release 3.2.0 + */ + public function assertSelected($selectLocator, $option, $message = '') + { + if ($message == '') { + $message = sprintf( + 'Label "%s" not selected in "%s".', + $option, + $selectLocator + ); + } + + $this->assertEquals( + $option, + $this->getSelectedLabel($selectLocator), + $message + ); + } + + /** + * Asserts that a specific label is not selected. + * + * @param string $selectLocator + * @param string $value + * @param string $message + * @since Method available since Release 3.2.0 + */ + public function assertNotSelected($selectLocator, $option, $message = '') + { + if ($message == '') { + $message = sprintf( + 'Label "%s" selected in "%s".', + $option, + $selectLocator + ); + } + + $this->assertNotEquals( + $option, + $this->getSelectedLabel($selectLocator), + $message + ); + } + + /** + * Asserts that a specific value is selected. + * + * @param string $selectLocator + * @param string $value + * @param string $message + */ + public function assertIsSelected($selectLocator, $value, $message = '') + { + if ($message == '') { + $message = sprintf( + 'Value "%s" not selected in "%s".', + $value, + $selectLocator + ); + } + + $this->assertEquals( + $value, $this->getSelectedValue($selectLocator), + $message + ); + } + + /** + * Asserts that a specific value is not selected. + * + * @param string $selectLocator + * @param string $value + * @param string $message + */ + public function assertIsNotSelected($selectLocator, $value, $message = '') + { + if ($message == '') { + $message = sprintf( + 'Value "%s" selected in "%s".', + $value, + $selectLocator + ); + } + + $this->assertNotEquals( + $value, + $this->getSelectedValue($selectLocator), + $message + ); + } + + /** + * Asserts that something is selected. + * + * @param string $selectLocator + * @param string $message + */ + public function assertSomethingSelected($selectLocator, $message = '') + { + if ($message == '') { + $message = sprintf( + 'Nothing selected from "%s".', + $selectLocator + ); + } + + $this->assertTrue($this->isSomethingSelected($selectLocator), $message); + } + + /** + * Asserts that nothing is selected. + * + * @param string $selectLocator + * @param string $message + */ + public function assertNothingSelected($selectLocator, $message = '') + { + if ($message == '') { + $message = sprintf( + 'Something selected from "%s".', + $selectLocator + ); + } + + $this->assertFalse($this->isSomethingSelected($selectLocator), $message); + } + + /** + * Asserts that a given text is present. + * + * @param string $pattern + * @param string $message + */ + public function assertTextPresent($pattern, $message = '') + { + if ($message == '') { + $message = sprintf( + '"%s" not present.', + $pattern + ); + } + + $this->assertTrue($this->isTextPresent($pattern), $message); + } + + /** + * Asserts that a given text is not present. + * + * @param string $pattern + * @param string $message + */ + public function assertTextNotPresent($pattern, $message = '') + { + if ($message == '') { + $message = sprintf( + '"%s" present.', + $pattern + ); + } + + $this->assertFalse($this->isTextPresent($pattern), $message); + } + + /** + * Asserts that the title is equal to a given string. + * + * @param string $title + * @param string $message + */ + public function assertTitleEquals($title, $message = '') + { + $this->assertEquals($title, $this->getTitle(), $message); + } + + /** + * Asserts that the title is not equal to a given string. + * + * @param string $title + * @param string $message + */ + public function assertTitleNotEquals($title, $message = '') + { + $this->assertNotEquals($title, $this->getTitle(), $message); + } + + /** + * Asserts that something is visible. + * + * @param string $locator + * @param string $message + */ + public function assertVisible($locator, $message = '') + { + if ($message == '') { + $message = sprintf( + '"%s" not visible.', + $locator + ); + } + + $this->assertTrue($this->isVisible($locator), $message); + } + + /** + * Asserts that something is not visible. + * + * @param string $locator + * @param string $message + */ + public function assertNotVisible($locator, $message = '') + { + if ($message == '') { + $message = sprintf( + '"%s" visible.', + $locator + ); + } + + $this->assertFalse($this->isVisible($locator), $message); + } + + /** + * Template Method that is called after Selenium actions. + * + * @param string $action + * @since Method available since Release 3.1.0 + */ + protected function defaultAssertions($action) + { + } + + /** + * @return array + * @since Method available since Release 3.2.0 + */ + protected function getCodeCoverage() + { + if (!empty($this->coverageScriptUrl)) { + $url = sprintf( + '%s?PHPUNIT_SELENIUM_TEST_ID=%s', + $this->coverageScriptUrl, + $this->testId + ); + + $buffer = @file_get_contents($url); + + if ($buffer !== FALSE) { + return $this->matchLocalAndRemotePaths(unserialize($buffer)); + } + } + + return array(); + } + + /** + * @param array $coverage + * @return array + * @author Mattis Stordalen Flister + * @since Method available since Release 3.2.9 + */ + protected function matchLocalAndRemotePaths(array $coverage) + { + $coverageWithLocalPaths = array(); + + foreach ($coverage as $originalRemotePath => $data) { + $remotePath = $originalRemotePath; + $separator = $this->findDirectorySeparator($remotePath); + + while (!($localpath = PHPUnit_Util_Filesystem::fileExistsInIncludePath($remotePath)) && + strpos($remotePath, $separator) !== FALSE) { + $remotePath = substr($remotePath, strpos($remotePath, $separator) + 1); + } + + if ($localpath && md5_file($localpath) == $data['md5']) { + $coverageWithLocalPaths[$localpath] = $data['coverage']; + } + } + + return $coverageWithLocalPaths; + } + + /** + * @param string $path + * @return string + * @author Mattis Stordalen Flister + * @since Method available since Release 3.2.9 + */ + protected function findDirectorySeparator($path) + { + if (strpos($path, '/') !== FALSE) { + return '/'; + } + + return '\\'; + } + + /** + * @param string $path + * @return array + * @author Mattis Stordalen Flister + * @since Method available since Release 3.2.9 + */ + protected function explodeDirectories($path) + { + return explode($this->findDirectorySeparator($path), dirname($path)); + } + + /** + * @param string $directory + * @param string $suffix + * @return array + * @since Method available since Release 3.3.0 + */ + protected static function getSeleneseFiles($directory, $suffix) + { + $files = array(); + + $iterator = new PHPUnit_Util_FilterIterator( + new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($directory) + ), + $suffix + ); + + foreach ($iterator as $file) { + $files[] = (string)$file; + } + + return $files; + } + + /** + * @param string $action + * @since Method available since Release 3.2.0 + */ + public function runDefaultAssertions($action) + { + if (!$this->inDefaultAssertions) { + $this->inDefaultAssertions = TRUE; + $this->defaultAssertions($action); + $this->inDefaultAssertions = FALSE; + } + } +} +?> diff --git a/tests/PHPUnit/Extensions/SeleniumTestCase/Driver.php b/tests/PHPUnit/Extensions/SeleniumTestCase/Driver.php new file mode 100755 index 00000000..b2dc4651 --- /dev/null +++ b/tests/PHPUnit/Extensions/SeleniumTestCase/Driver.php @@ -0,0 +1,1048 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Implementation of the Selenium RC client/server protocol. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class PHPUnit_Extensions_SeleniumTestCase_Driver +{ + /** + * @var PHPUnit_Extensions_SeleniumTestCase + */ + protected $testCase; + + /** + * @var string + */ + protected $testId; + + /** + * @var string + */ + protected $name; + + /** + * @var string + */ + protected $browser; + + /** + * @var string + */ + protected $browserUrl; + + /** + * @var boolean + */ + protected $collectCodeCoverageInformation = FALSE; + + /** + * @var string + */ + protected $host = 'localhost'; + + /** + * @var integer + */ + protected $port = 4444; + + /** + * @var integer + */ + protected $timeout = 30000; + + /** + * @var array + */ + protected $sessionId; + + /** + * @var integer + */ + protected $sleep = 0; + + /** + * @var boolean + */ + protected $useWaitForPageToLoad = TRUE; + + /** + * @var boolean + */ + protected $wait = 5; + + /** + * @return string + */ + public function start() + { + if ($this->browserUrl == NULL) { + throw new RuntimeException( + 'setBrowserUrl() needs to be called before start().' + ); + } + + if (!isset($this->sessionId)) { + $this->sessionId = $this->getString( + 'getNewBrowserSession', + array($this->browser, $this->browserUrl) + ); + + $this->doCommand('setTimeout', array($this->timeout)); + } + + return $this->sessionId; + } + + /** + */ + public function stop() + { + if (!isset($this->sessionId)) { + return; + } + + $this->doCommand('testComplete'); + + $this->sessionId = NULL; + } + + /** + * @param boolean $flag + * @throws InvalidArgumentException + */ + public function setCollectCodeCoverageInformation($flag) + { + if (!is_bool($flag)) { + throw new InvalidArgumentException; + } + + $this->collectCodeCoverageInformation = $flag; + } + + /** + * @param PHPUnit_Extensions_SeleniumTestCase $testCase + */ + public function setTestCase(PHPUnit_Extensions_SeleniumTestCase $testCase) + { + $this->testCase = $testCase; + } + + /** + * @param integer $testId + */ + public function setTestId($testId) + { + $this->testId = $testId; + } + + /** + * @param string $name + * @throws InvalidArgumentException + */ + public function setName($name) + { + if (!is_string($name)) { + throw new InvalidArgumentException; + } + + $this->name = $name; + } + + /** + * @param string $browser + * @throws InvalidArgumentException + */ + public function setBrowser($browser) + { + if (!is_string($browser)) { + throw new InvalidArgumentException; + } + + $this->browser = $browser; + } + + /** + * @param string $browserUrl + * @throws InvalidArgumentException + */ + public function setBrowserUrl($browserUrl) + { + if (!is_string($browserUrl)) { + throw new InvalidArgumentException; + } + + $this->browserUrl = $browserUrl; + } + + /** + * @param string $host + * @throws InvalidArgumentException + */ + public function setHost($host) + { + if (!is_string($host)) { + throw new InvalidArgumentException; + } + + $this->host = $host; + } + + /** + * @param integer $port + * @throws InvalidArgumentException + */ + public function setPort($port) + { + if (!is_int($port)) { + throw new InvalidArgumentException; + } + + $this->port = $port; + } + + /** + * @param integer $timeout + * @throws InvalidArgumentException + */ + public function setTimeout($timeout) + { + if (!is_int($timeout)) { + throw new InvalidArgumentException; + } + + $this->timeout = $timeout; + } + + /** + * @param integer $seconds + * @throws InvalidArgumentException + */ + public function setSleep($seconds) + { + if (!is_int($seconds)) { + throw new InvalidArgumentException; + } + + $this->sleep = $seconds; + } + + /** + * Sets the number of seconds to sleep() after *AndWait commands + * when setWaitForPageToLoad(FALSE) is used. + * + * @param integer $seconds + * @throws InvalidArgumentException + */ + public function setWait($seconds) + { + if (!is_int($seconds)) { + throw new InvalidArgumentException; + } + + $this->wait = $seconds; + } + + /** + * Sets whether waitForPageToLoad (TRUE) or sleep() (FALSE) + * is used after *AndWait commands. + * + * @param boolean $flag + * @throws InvalidArgumentException + */ + public function setWaitForPageToLoad($flag) + { + if (!is_bool($flag)) { + throw new InvalidArgumentException; + } + + $this->useWaitForPageToLoad = $flag; + } + + /** + * This method implements the Selenium RC protocol. + * + * @param string $command + * @param array $arguments + * @return mixed + * @method unknown addLocationStrategy() + * @method unknown addSelection() + * @method unknown addSelectionAndWait() + * @method unknown allowNativeXpath() + * @method unknown altKeyDown() + * @method unknown altKeyDownAndWait() + * @method unknown altKeyUp() + * @method unknown altKeyUpAndWait() + * @method unknown answerOnNextPrompt() + * @method unknown assignId() + * @method unknown break() + * @method unknown captureEntirePageScreenshot() + * @method unknown captureScreenshot() + * @method unknown check() + * @method unknown chooseCancelOnNextConfirmation() + * @method unknown chooseOkOnNextConfirmation() + * @method unknown click() + * @method unknown clickAndWait() + * @method unknown clickAt() + * @method unknown clickAtAndWait() + * @method unknown close() + * @method unknown contextMenu() + * @method unknown contextMenuAndWait() + * @method unknown contextMenuAt() + * @method unknown contextMenuAtAndWait() + * @method unknown controlKeyDown() + * @method unknown controlKeyDownAndWait() + * @method unknown controlKeyUp() + * @method unknown controlKeyUpAndWait() + * @method unknown createCookie() + * @method unknown createCookieAndWait() + * @method unknown deleteAllVisibleCookies() + * @method unknown deleteAllVisibleCookiesAndWait() + * @method unknown deleteCookie() + * @method unknown deleteCookieAndWait() + * @method unknown doubleClick() + * @method unknown doubleClickAndWait() + * @method unknown doubleClickAt() + * @method unknown doubleClickAtAndWait() + * @method unknown dragAndDrop() + * @method unknown dragAndDropAndWait() + * @method unknown dragAndDropToObject() + * @method unknown dragAndDropToObjectAndWait() + * @method unknown dragDrop() + * @method unknown dragDropAndWait() + * @method unknown echo() + * @method unknown fireEvent() + * @method unknown fireEventAndWait() + * @method unknown focus() + * @method string getAlert() + * @method array getAllButtons() + * @method array getAllFields() + * @method array getAllLinks() + * @method array getAllWindowIds() + * @method array getAllWindowNames() + * @method array getAllWindowTitles() + * @method string getAttribute() + * @method array getAttributeFromAllWindows() + * @method string getBodyText() + * @method string getConfirmation() + * @method string getCookie() + * @method integer getCursorPosition() + * @method integer getElementHeight() + * @method integer getElementIndex() + * @method integer getElementPositionLeft() + * @method integer getElementPositionTop() + * @method integer getElementWidth() + * @method string getEval() + * @method string getExpression() + * @method string getHtmlSource() + * @method string getLocation() + * @method string getLogMessages() + * @method integer getMouseSpeed() + * @method string getPrompt() + * @method array getSelectOptions() + * @method string getSelectedId() + * @method array getSelectedIds() + * @method string getSelectedIndex() + * @method array getSelectedIndexes() + * @method string getSelectedLabel() + * @method array getSelectedLabels() + * @method string getSelectedValue() + * @method array getSelectedValues() + * @method unknown getSpeed() + * @method unknown getSpeedAndWait() + * @method string getTable() + * @method string getText() + * @method string getTitle() + * @method string getValue() + * @method boolean getWhetherThisFrameMatchFrameExpression() + * @method boolean getWhetherThisWindowMatchWindowExpression() + * @method integer getXpathCount() + * @method unknown goBack() + * @method unknown goBackAndWait() + * @method unknown highlight() + * @method unknown highlightAndWait() + * @method unknown ignoreAttributesWithoutValue() + * @method boolean isAlertPresent() + * @method boolean isChecked() + * @method boolean isConfirmationPresent() + * @method boolean isEditable() + * @method boolean isElementPresent() + * @method boolean isOrdered() + * @method boolean isPromptPresent() + * @method boolean isSomethingSelected() + * @method boolean isTextPresent() + * @method boolean isVisible() + * @method unknown keyDown() + * @method unknown keyDownAndWait() + * @method unknown keyPress() + * @method unknown keyPressAndWait() + * @method unknown keyUp() + * @method unknown keyUpAndWait() + * @method unknown metaKeyDown() + * @method unknown metaKeyDownAndWait() + * @method unknown metaKeyUp() + * @method unknown metaKeyUpAndWait() + * @method unknown mouseDown() + * @method unknown mouseDownAndWait() + * @method unknown mouseDownAt() + * @method unknown mouseDownAtAndWait() + * @method unknown mouseMove() + * @method unknown mouseMoveAndWait() + * @method unknown mouseMoveAt() + * @method unknown mouseMoveAtAndWait() + * @method unknown mouseOut() + * @method unknown mouseOutAndWait() + * @method unknown mouseOver() + * @method unknown mouseOverAndWait() + * @method unknown mouseUp() + * @method unknown mouseUpAndWait() + * @method unknown mouseUpAt() + * @method unknown mouseUpAtAndWait() + * @method unknown mouseUpRight() + * @method unknown mouseUpRightAndWait() + * @method unknown mouseUpRightAt() + * @method unknown mouseUpRightAtAndWait() + * @method unknown open() + * @method unknown openWindow() + * @method unknown openWindowAndWait() + * @method unknown pause() + * @method unknown refresh() + * @method unknown refreshAndWait() + * @method unknown removeAllSelections() + * @method unknown removeAllSelectionsAndWait() + * @method unknown removeSelection() + * @method unknown removeSelectionAndWait() + * @method unknown runScript() + * @method unknown select() + * @method unknown selectAndWait() + * @method unknown selectFrame() + * @method unknown selectWindow() + * @method unknown setBrowserLogLevel() + * @method unknown setContext() + * @method unknown setCursorPosition() + * @method unknown setCursorPositionAndWait() + * @method unknown setMouseSpeed() + * @method unknown setMouseSpeedAndWait() + * @method unknown setSpeed() + * @method unknown setSpeedAndWait() + * @method unknown shiftKeyDown() + * @method unknown shiftKeyDownAndWait() + * @method unknown shiftKeyUp() + * @method unknown shiftKeyUpAndWait() + * @method unknown store() + * @method unknown storeAlert() + * @method unknown storeAlertPresent() + * @method unknown storeAllButtons() + * @method unknown storeAllFields() + * @method unknown storeAllLinks() + * @method unknown storeAllWindowIds() + * @method unknown storeAllWindowNames() + * @method unknown storeAllWindowTitle()s + * @method unknown storeAttribute() + * @method unknown storeAttributeFromAllWindows() + * @method unknown storeBodyText() + * @method unknown storeChecked() + * @method unknown storeConfirmation() + * @method unknown storeConfirmationPresent() + * @method unknown storeCookie() + * @method unknown storeCookieByName() + * @method unknown storeCookiePresent() + * @method unknown storeCursorPosition() + * @method unknown storeEditable() + * @method unknown storeElementHeight() + * @method unknown storeElementIndex() + * @method unknown storeElementPositionLeft() + * @method unknown storeElementPositionTop() + * @method unknown storeElementPresent() + * @method unknown storeElementWidth() + * @method unknown storeEval() + * @method unknown storeExpression() + * @method unknown storeHtmlSource() + * @method unknown storeLocation() + * @method unknown storeMouseSpeed() + * @method unknown storeOrdered() + * @method unknown storePrompt() + * @method unknown storePromptPresent() + * @method unknown storeSelectOptions() + * @method unknown storeSelectedId() + * @method unknown storeSelectedIds() + * @method unknown storeSelectedIndex() + * @method unknown storeSelectedIndexes() + * @method unknown storeSelectedLabel() + * @method unknown storeSelectedLabels() + * @method unknown storeSelectedValue() + * @method unknown storeSelectedValues() + * @method unknown storeSomethingSelected() + * @method unknown storeSpeed() + * @method unknown storeTable() + * @method unknown storeText() + * @method unknown storeTextPresent() + * @method unknown storeTitle() + * @method unknown storeValue() + * @method unknown storeVisible() + * @method unknown storeWhetherThisFrameMatchFrameExpression() + * @method unknown storeWhetherThisWindowMatchWindowExpression() + * @method unknown storeXpathCount() + * @method unknown submit() + * @method unknown submitAndWait() + * @method unknown type() + * @method unknown typeAndWait() + * @method unknown typeKeys() + * @method unknown typeKeysAndWait() + * @method unknown uncheck() + * @method unknown uncheckAndWait() + * @method unknown waitForCondition() + * @method unknown waitForPageToLoad() + * @method unknown waitForPopUp() + * @method unknown windowFocus() + * @method unknown windowMaximize() + */ + public function __call($command, $arguments) + { + $wait = FALSE; + + if (substr($command, -7, 7) == 'AndWait') { + $command = substr($command, 0, -7); + $wait = TRUE; + } + + switch ($command) { + case 'addLocationStrategy': + case 'addSelection': + case 'allowNativeXpath': + case 'altKeyDown': + case 'altKeyUp': + case 'answerOnNextPrompt': + case 'assignId': + case 'break': + case 'captureEntirePageScreenshot': + case 'captureScreenshot': + case 'check': + case 'chooseCancelOnNextConfirmation': + case 'chooseOkOnNextConfirmation': + case 'click': + case 'clickAt': + case 'close': + case 'contextMenu': + case 'contextMenuAt': + case 'controlKeyDown': + case 'controlKeyUp': + case 'createCookie': + case 'deleteAllVisibleCookies': + case 'deleteCookie': + case 'doubleClick': + case 'doubleClickAt': + case 'dragAndDrop': + case 'dragAndDropToObject': + case 'dragDrop': + case 'echo': + case 'fireEvent': + case 'focus': + case 'goBack': + case 'highlight': + case 'ignoreAttributesWithoutValue': + case 'keyDown': + case 'keyPress': + case 'keyUp': + case 'metaKeyDown': + case 'metaKeyUp': + case 'mouseDown': + case 'mouseDownAt': + case 'mouseMove': + case 'mouseMoveAt': + case 'mouseOut': + case 'mouseOver': + case 'mouseUp': + case 'mouseUpAt': + case 'mouseUpRight': + case 'mouseUpRightAt': + case 'open': + case 'openWindow': + case 'pause': + case 'refresh': + case 'removeAllSelections': + case 'removeSelection': + case 'runScript': + case 'select': + case 'selectFrame': + case 'selectWindow': + case 'setBrowserLogLevel': + case 'setContext': + case 'setCursorPosition': + case 'setMouseSpeed': + case 'setSpeed': + case 'shiftKeyDown': + case 'shiftKeyUp': + case 'store': + case 'storeAlert': + case 'storeAlertPresent': + case 'storeAllButtons': + case 'storeAllFields': + case 'storeAllLinks': + case 'storeAllWindowIds': + case 'storeAllWindowNames': + case 'storeAllWindowTitles': + case 'storeAttribute': + case 'storeAttributeFromAllWindows': + case 'storeBodyText': + case 'storeChecked': + case 'storeConfirmation': + case 'storeConfirmationPresent': + case 'storeCookie': + case 'storeCookieByName': + case 'storeCookiePresent': + case 'storeCursorPosition': + case 'storeEditable': + case 'storeElementHeight': + case 'storeElementIndex': + case 'storeElementPositionLeft': + case 'storeElementPositionTop': + case 'storeElementPresent': + case 'storeElementWidth': + case 'storeEval': + case 'storeExpression': + case 'storeHtmlSource': + case 'storeLocation': + case 'storeMouseSpeed': + case 'storeOrdered': + case 'storePrompt': + case 'storePromptPresent': + case 'storeSelectOptions': + case 'storeSelectedId': + case 'storeSelectedIds': + case 'storeSelectedIndex': + case 'storeSelectedIndexes': + case 'storeSelectedLabel': + case 'storeSelectedLabels': + case 'storeSelectedValue': + case 'storeSelectedValues': + case 'storeSomethingSelected': + case 'storeSpeed': + case 'storeTable': + case 'storeText': + case 'storeTextPresent': + case 'storeTitle': + case 'storeValue': + case 'storeVisible': + case 'storeWhetherThisFrameMatchFrameExpression': + case 'storeWhetherThisWindowMatchWindowExpression': + case 'storeXpathCount': + case 'submit': + case 'type': + case 'typeKeys': + case 'uncheck': + case 'windowFocus': + case 'windowMaximize': { + // Pre-Command Actions + switch ($command) { + case 'open': + case 'openWindow': { + if ($this->collectCodeCoverageInformation) { + $this->deleteCookie('PHPUNIT_SELENIUM_TEST_ID', 'path=/'); + + $this->createCookie( + 'PHPUNIT_SELENIUM_TEST_ID=' . $this->testId, + 'path=/' + ); + } + } + break; + } + + $this->doCommand($command, $arguments); + + // Post-Command Actions + switch ($command) { + case 'addLocationStrategy': + case 'allowNativeXpath': + case 'assignId': + case 'captureScreenshot': { + // intentionally empty + } + break; + + default: { + if ($wait) { + if ($this->useWaitForPageToLoad) { + $this->waitForPageToLoad($this->timeout); + } else { + sleep($this->wait); + } + } + + if ($this->sleep > 0) { + sleep($this->sleep); + } + + $this->testCase->runDefaultAssertions($command); + } + } + } + break; + + case 'getWhetherThisFrameMatchFrameExpression': + case 'getWhetherThisWindowMatchWindowExpression': + case 'isAlertPresent': + case 'isChecked': + case 'isConfirmationPresent': + case 'isEditable': + case 'isElementPresent': + case 'isOrdered': + case 'isPromptPresent': + case 'isSomethingSelected': + case 'isTextPresent': + case 'isVisible': { + return $this->getBoolean($command, $arguments); + } + break; + + case 'getCursorPosition': + case 'getElementHeight': + case 'getElementIndex': + case 'getElementPositionLeft': + case 'getElementPositionTop': + case 'getElementWidth': + case 'getMouseSpeed': + case 'getSpeed': + case 'getXpathCount': { + $result = $this->getNumber($command, $arguments); + + if ($wait) { + $this->waitForPageToLoad($this->timeout); + } + + return $result; + } + break; + + case 'getAlert': + case 'getAttribute': + case 'getBodyText': + case 'getConfirmation': + case 'getCookie': + case 'getEval': + case 'getExpression': + case 'getHtmlSource': + case 'getLocation': + case 'getLogMessages': + case 'getPrompt': + case 'getSelectedId': + case 'getSelectedIndex': + case 'getSelectedLabel': + case 'getSelectedValue': + case 'getTable': + case 'getText': + case 'getTitle': + case 'getValue': { + $result = $this->getString($command, $arguments); + + if ($wait) { + $this->waitForPageToLoad($this->timeout); + } + + return $result; + } + break; + + case 'getAllButtons': + case 'getAllFields': + case 'getAllLinks': + case 'getAllWindowIds': + case 'getAllWindowNames': + case 'getAllWindowTitles': + case 'getAttributeFromAllWindows': + case 'getSelectedIds': + case 'getSelectedIndexes': + case 'getSelectedLabels': + case 'getSelectedValues': + case 'getSelectOptions': { + $result = $this->getStringArray($command, $arguments); + + if ($wait) { + $this->waitForPageToLoad($this->timeout); + } + + return $result; + } + break; + + case 'waitForCondition': + case 'waitForFrameToLoad': + case 'waitForPopUp': { + if (count($arguments) == 1) { + $arguments[] = $this->timeout; + } + + $this->doCommand($command, $arguments); + $this->testCase->runDefaultAssertions($command); + } + break; + + case 'waitForPageToLoad': { + if (empty($arguments)) { + $arguments[] = $this->timeout; + } + + $this->doCommand($command, $arguments); + $this->testCase->runDefaultAssertions($command); + } + break; + + default: { + $this->stop(); + + throw new BadMethodCallException( + "Method $command not defined." + ); + } + } + } + + /** + * Send a command to the Selenium RC server. + * + * @param string $command + * @param array $arguments + * @return string + * @author Shin Ohno + * @author Bjoern Schotte + */ + protected function doCommand($command, array $arguments = array()) + { + if (!ini_get('allow_url_fopen')) { + throw new RuntimeException( + 'Could not connect to the Selenium RC server because allow_url_fopen is disabled.' + ); + } + + $url = sprintf( + 'http://%s:%s/selenium-server/driver/?cmd=%s', + $this->host, + $this->port, + urlencode($command) + ); + + $numArguments = count($arguments); + + for ($i = 0; $i < $numArguments; $i++) { + $argNum = strval($i + 1); + $url .= sprintf('&%s=%s', $argNum, urlencode(trim($arguments[$i]))); + } + + if (isset($this->sessionId)) { + $url .= sprintf('&%s=%s', 'sessionId', $this->sessionId); + } + + $handle = @fopen($url, 'r'); + + if (!$handle) { + throw new RuntimeException( + 'Could not connect to the Selenium RC server.' + ); + } + + stream_set_blocking($handle, 1); + stream_set_timeout($handle, 0, $this->timeout); + + $info = stream_get_meta_data($handle); + $response = ''; + + while (!$info['eof'] && !$info['timed_out']) { + $response .= fgets($handle, 4096); + $info = stream_get_meta_data($handle); + } + + fclose($handle); + + if (!preg_match('/^OK/', $response)) { + $this->stop(); + + throw new RuntimeException( + 'The response from the Selenium RC server is invalid: ' . $response + ); + } + + return $response; + } + + /** + * Send a command to the Selenium RC server and treat the result + * as a boolean. + * + * @param string $command + * @param array $arguments + * @return boolean + * @author Shin Ohno + * @author Bjoern Schotte + */ + protected function getBoolean($command, array $arguments) + { + $result = $this->getString($command, $arguments); + + switch ($result) { + case 'true': return TRUE; + + case 'false': return FALSE; + + default: { + $this->stop(); + + throw new RuntimeException( + 'Result is neither "true" nor "false": ' . PHPUnit_Util_Type::toString($result, TRUE) + ); + } + } + } + + /** + * Send a command to the Selenium RC server and treat the result + * as a number. + * + * @param string $command + * @param array $arguments + * @return numeric + * @author Shin Ohno + * @author Bjoern Schotte + */ + protected function getNumber($command, array $arguments) + { + $result = $this->getString($command, $arguments); + + if (!is_numeric($result)) { + $this->stop(); + + throw new RuntimeException( + 'Result is not numeric: ' . PHPUnit_Util_Type::toString($result, TRUE) + ); + } + + return $result; + } + + /** + * Send a command to the Selenium RC server and treat the result + * as a string. + * + * @param string $command + * @param array $arguments + * @return string + * @author Shin Ohno + * @author Bjoern Schotte + */ + protected function getString($command, array $arguments) + { + try { + $result = $this->doCommand($command, $arguments); + } + + catch (RuntimeException $e) { + $this->stop(); + + throw $e; + } + + return (strlen($result) > 3) ? substr($result, 3) : ''; + } + + /** + * Send a command to the Selenium RC server and treat the result + * as an array of strings. + * + * @param string $command + * @param array $arguments + * @return array + * @author Shin Ohno + * @author Bjoern Schotte + */ + protected function getStringArray($command, array $arguments) + { + $csv = $this->getString($command, $arguments); + $token = ''; + $tokens = array(); + $letters = preg_split('//', $csv, -1, PREG_SPLIT_NO_EMPTY); + $count = count($letters); + + for ($i = 0; $i < $count; $i++) { + $letter = $letters[$i]; + + switch($letter) { + case '\\': { + $letter = $letters[++$i]; + $token .= $letter; + } + break; + + case ',': { + $tokens[] = $token; + $token = ''; + } + break; + + default: { + $token .= $letter; + } + } + } + + $tokens[] = $token; + + return $tokens; + } +} +?> diff --git a/tests/PHPUnit/Extensions/SeleniumTestCase/append.php b/tests/PHPUnit/Extensions/SeleniumTestCase/append.php new file mode 100755 index 00000000..19fa05d8 --- /dev/null +++ b/tests/PHPUnit/Extensions/SeleniumTestCase/append.php @@ -0,0 +1,66 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.10 + */ + +if ( isset($_COOKIE['PHPUNIT_SELENIUM_TEST_ID']) && + !isset($_GET['PHPUNIT_SELENIUM_TEST_ID']) && + extension_loaded('xdebug')) { + $GLOBALS['PHPUNIT_FILTERED_FILES'][] = __FILE__; + + $data = xdebug_get_code_coverage(); + xdebug_stop_code_coverage(); + + foreach ($GLOBALS['PHPUNIT_FILTERED_FILES'] as $file) { + unset($data[$file]); + } + + file_put_contents( + $_SERVER['SCRIPT_FILENAME'] . '.' . + md5(uniqid(rand(), TRUE)) . '.' . + $_COOKIE['PHPUNIT_SELENIUM_TEST_ID'], + serialize($data) + ); +} +?> diff --git a/tests/PHPUnit/Extensions/SeleniumTestCase/phpunit_coverage.php b/tests/PHPUnit/Extensions/SeleniumTestCase/phpunit_coverage.php new file mode 100755 index 00000000..0835f28a --- /dev/null +++ b/tests/PHPUnit/Extensions/SeleniumTestCase/phpunit_coverage.php @@ -0,0 +1,86 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.10 + */ + +require_once 'PHPUnit/Util/CodeCoverage.php'; +require_once 'PHPUnit/Util/FilterIterator.php'; + +if (isset($_GET['PHPUNIT_SELENIUM_TEST_ID'])) { + $files = new PHPUnit_Util_FilterIterator( + new RecursiveIteratorIterator( + new RecursiveDirectoryIterator(dirname(__FILE__)) + ), + $_GET['PHPUNIT_SELENIUM_TEST_ID'] + ); + + $coverage = array(); + + foreach ($files as $file) { + $filename = $file->getPathName(); + $data = unserialize(file_get_contents($filename)); + @unlink($filename); + unset($filename); + + foreach ($data as $filename => $lines) { + if (PHPUnit_Util_CodeCoverage::isFile($filename)) { + if (!isset($coverage[$filename])) { + $coverage[$filename] = array( + 'md5' => md5_file($filename), 'coverage' => $lines + ); + } else { + foreach ($lines as $line => $flag) { + if (!isset($coverage[$filename]['coverage'][$line]) || + $flag > $coverage[$filename]['coverage'][$line]) { + $coverage[$filename]['coverage'][$line] = $flag; + } + } + } + } + } + } + + print serialize($coverage); +} +?> diff --git a/tests/PHPUnit/Extensions/SeleniumTestCase/prepend.php b/tests/PHPUnit/Extensions/SeleniumTestCase/prepend.php new file mode 100755 index 00000000..5b956196 --- /dev/null +++ b/tests/PHPUnit/Extensions/SeleniumTestCase/prepend.php @@ -0,0 +1,54 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.10 + */ + +if ( isset($_COOKIE['PHPUNIT_SELENIUM_TEST_ID']) && + !isset($_GET['PHPUNIT_SELENIUM_TEST_ID']) && + extension_loaded('xdebug')) { + $GLOBALS['PHPUNIT_FILTERED_FILES'] = array(__FILE__); + + xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE); +} +?> diff --git a/tests/PHPUnit/Extensions/Story/Given.php b/tests/PHPUnit/Extensions/Story/Given.php new file mode 100755 index 00000000..6e73403b --- /dev/null +++ b/tests/PHPUnit/Extensions/Story/Given.php @@ -0,0 +1,79 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Extensions/Story/Step.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * A "Given" step. + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + * @abstract + */ +class PHPUnit_Extensions_Story_Given extends PHPUnit_Extensions_Story_Step +{ + /** + * Returns this step's name. + * + * @return string + */ + public function getName() + { + return 'Given'; + } +} +?> diff --git a/tests/PHPUnit/Extensions/Story/ResultPrinter.php b/tests/PHPUnit/Extensions/Story/ResultPrinter.php new file mode 100755 index 00000000..7374c66e --- /dev/null +++ b/tests/PHPUnit/Extensions/Story/ResultPrinter.php @@ -0,0 +1,110 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Template.php'; +require_once 'PHPUnit/Util/TestDox/ResultPrinter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Base for Story result printers. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class PHPUnit_Extensions_Story_ResultPrinter extends PHPUnit_Util_TestDox_ResultPrinter +{ + /** + * A test ended. + * + * @param PHPUnit_Framework_Test $test + * @param float $time + */ + public function endTest(PHPUnit_Framework_Test $test, $time) + { + if ($test instanceof PHPUnit_Extensions_Story_TestCase || + $test instanceof PHPUnit_Extensions_Story_SeleniumTestCase) { + if ($this->testStatus == PHPUnit_Runner_BaseTestRunner::STATUS_PASSED) { + $this->successful++; + $success = TRUE; + } else { + $success = FALSE; + } + + $this->onTest( + $this->currentTestMethodPrettified, + $success, + $test->getScenario()->getSteps() + ); + } + } + + /** + */ + protected function doEndClass() + { + $this->endClass($this->testClass); + } + + /** + * Handler for 'on test' event. + * + * @param string $name + * @param boolean $success + * @param array $steps + */ + protected function onTest($name, $success = TRUE, array $steps = array()) + { + } +} +?> diff --git a/tests/PHPUnit/Extensions/Story/ResultPrinter/HTML.php b/tests/PHPUnit/Extensions/Story/ResultPrinter/HTML.php new file mode 100755 index 00000000..8a6d6701 --- /dev/null +++ b/tests/PHPUnit/Extensions/Story/ResultPrinter/HTML.php @@ -0,0 +1,209 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Template.php'; +require_once 'PHPUnit/Extensions/Story/ResultPrinter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Prints stories in HTML format. + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class PHPUnit_Extensions_Story_ResultPrinter_HTML extends PHPUnit_Extensions_Story_ResultPrinter +{ + /** + * @var boolean + */ + protected $printsHTML = TRUE; + + protected $id = 0; + protected $scenarios = ''; + protected $templatePath; + + /** + * Constructor. + * + * @param mixed $out + * @throws InvalidArgumentException + */ + public function __construct($out = NULL) + { + parent::__construct($out); + + $this->templatePath = sprintf( + '%s%sTemplate%s', + + dirname(__FILE__), + DIRECTORY_SEPARATOR, + DIRECTORY_SEPARATOR + ); + } + + /** + * Handler for 'start class' event. + * + * @param string $name + */ + protected function startClass($name) + { + $scenarioHeaderTemplate = new PHPUnit_Util_Template( + $this->templatePath . 'scenario_header.html' + ); + + $scenarioHeaderTemplate->setVar( + array( + 'name' => $this->currentTestClassPrettified + ) + ); + + $this->scenarios .= $scenarioHeaderTemplate->render(); + } + + /** + * Handler for 'on test' event. + * + * @param string $name + * @param boolean $success + * @param array $steps + */ + protected function onTest($name, $success = TRUE, array $steps = array()) + { + if ($this->testStatus == PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE) { + $scenarioStatus = 'scenarioFailed'; + } + + else if ($this->testStatus == PHPUnit_Runner_BaseTestRunner::STATUS_SKIPPED) { + $scenarioStatus = 'scenarioSkipped'; + } + + else if ($this->testStatus == PHPUnit_Runner_BaseTestRunner::STATUS_INCOMPLETE) { + $scenarioStatus = 'scenarioIncomplete'; + } + + else { + $scenarioStatus = 'scenarioSuccess'; + } + + $lastStepName = ''; + $stepsBuffer = ''; + + foreach ($steps as $step) { + $currentStepName = $step->getName(); + + if ($lastStepName == $currentStepName) { + $stepText = 'and'; + } else { + $stepText = $currentStepName; + } + + $lastStepName = $currentStepName; + + $stepTemplate = new PHPUnit_Util_Template( + $this->templatePath . 'step.html' + ); + + $stepTemplate->setVar( + array( + 'text' => $stepText, + 'action' => $step->getAction() . ' ' . $step->getArguments(TRUE), + ) + ); + + $stepsBuffer .= $stepTemplate->render(); + } + + $scenarioTemplate = new PHPUnit_Util_Template( + $this->templatePath . 'scenario.html' + ); + + $scenarioTemplate->setVar( + array( + 'id' => ++$this->id, + 'name' => $name, + 'scenarioStatus' => $scenarioStatus, + 'steps' => $stepsBuffer, + ) + ); + + $this->scenarios .= $scenarioTemplate->render(); + } + + /** + * Handler for 'end run' event. + * + */ + protected function endRun() + { + $scenariosTemplate = new PHPUnit_Util_Template( + $this->templatePath . 'scenarios.html' + ); + + $scenariosTemplate->setVar( + array( + 'scenarios' => $this->scenarios, + 'successfulScenarios' => $this->successful, + 'failedScenarios' => $this->failed, + 'skippedScenarios' => $this->skipped, + 'incompleteScenarios' => $this->incomplete + ) + ); + + $this->write($scenariosTemplate->render()); + } +} +?> diff --git a/tests/PHPUnit/Extensions/Story/ResultPrinter/Template/scenario.html.dist b/tests/PHPUnit/Extensions/Story/ResultPrinter/Template/scenario.html.dist new file mode 100755 index 00000000..caa149aa --- /dev/null +++ b/tests/PHPUnit/Extensions/Story/ResultPrinter/Template/scenario.html.dist @@ -0,0 +1,13 @@ + + +

[+] {name}

+ + + + + +{steps} +
+ + + diff --git a/tests/PHPUnit/Extensions/Story/ResultPrinter/Template/scenario_header.html.dist b/tests/PHPUnit/Extensions/Story/ResultPrinter/Template/scenario_header.html.dist new file mode 100755 index 00000000..7b205d1c --- /dev/null +++ b/tests/PHPUnit/Extensions/Story/ResultPrinter/Template/scenario_header.html.dist @@ -0,0 +1,6 @@ + + +

{name}

+ + + diff --git a/tests/PHPUnit/Extensions/Story/ResultPrinter/Template/scenarios.html.dist b/tests/PHPUnit/Extensions/Story/ResultPrinter/Template/scenarios.html.dist new file mode 100755 index 00000000..21bf38e8 --- /dev/null +++ b/tests/PHPUnit/Extensions/Story/ResultPrinter/Template/scenarios.html.dist @@ -0,0 +1,60 @@ + + + + + + + +{scenarios} + + + +
+

[+] Summary:

+ +
+ + diff --git a/tests/PHPUnit/Extensions/Story/ResultPrinter/Template/step.html.dist b/tests/PHPUnit/Extensions/Story/ResultPrinter/Template/step.html.dist new file mode 100755 index 00000000..bcdce3f4 --- /dev/null +++ b/tests/PHPUnit/Extensions/Story/ResultPrinter/Template/step.html.dist @@ -0,0 +1,6 @@ + + {text} + {action} +   + + diff --git a/tests/PHPUnit/Extensions/Story/ResultPrinter/Text.php b/tests/PHPUnit/Extensions/Story/ResultPrinter/Text.php new file mode 100755 index 00000000..c92f266d --- /dev/null +++ b/tests/PHPUnit/Extensions/Story/ResultPrinter/Text.php @@ -0,0 +1,158 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Template.php'; +require_once 'PHPUnit/Extensions/Story/ResultPrinter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Prints stories in HTML format. + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class PHPUnit_Extensions_Story_ResultPrinter_Text extends PHPUnit_Extensions_Story_ResultPrinter +{ + /** + * Handler for 'start class' event. + * + * @param string $name + */ + protected function startClass($name) + { + $this->write($this->currentTestClassPrettified . "\n"); + } + + /** + * Handler for 'on test' event. + * + * @param string $name + * @param boolean $success + * @param array $steps + */ + protected function onTest($name, $success = TRUE, array $steps = array()) + { + if ($this->testStatus == PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE) { + $scenarioStatus = 'failed'; + } + + else if ($this->testStatus == PHPUnit_Runner_BaseTestRunner::STATUS_SKIPPED) { + $scenarioStatus = 'skipped'; + } + + else if ($this->testStatus == PHPUnit_Runner_BaseTestRunner::STATUS_INCOMPLETE) { + $scenarioStatus = 'incomplete'; + } + + else { + $scenarioStatus = 'successful'; + } + + $this->write( + sprintf( + " [%s] %s\n\n", + $scenarioStatus == 'successful' ? 'x' : ' ', + $name + ) + ); + + $lastStepName = ''; + $stepsBuffer = ''; + + foreach ($steps as $step) { + $currentStepName = $step->getName(); + + if ($lastStepName == $currentStepName) { + $stepText = 'and'; + } else { + $stepText = $currentStepName; + } + + $lastStepName = $currentStepName; + + $this->write( + sprintf( + " %5s %s %s\n", + $stepText, + $step->getAction(), + $step->getArguments(TRUE) + ) + ); + } + + $this->write("\n"); + } + + /** + * Handler for 'end run' event. + * + */ + protected function endRun() + { + $this->write( + sprintf( + "Scenarios: %d, Failed: %d, Skipped: %d, Incomplete: %d.\n", + + $this->successful + $this->failed + + $this->skipped + $this->incomplete, + $this->failed, + $this->skipped, + $this->incomplete + ) + ); + } +} +?> diff --git a/tests/PHPUnit/Extensions/Story/Scenario.php b/tests/PHPUnit/Extensions/Story/Scenario.php new file mode 100755 index 00000000..84cb4b4f --- /dev/null +++ b/tests/PHPUnit/Extensions/Story/Scenario.php @@ -0,0 +1,200 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Extensions/Story/Step.php'; +require_once 'PHPUnit/Extensions/Story/Given.php'; +require_once 'PHPUnit/Extensions/Story/When.php'; +require_once 'PHPUnit/Extensions/Story/Then.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * A scenario. + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + * @abstract + */ +class PHPUnit_Extensions_Story_Scenario +{ + /** + * @var PHPUnit_Extensions_Story_TestCase + */ + protected $test; + + /** + * @var array + */ + protected $steps = array(); + + /** + * @var string + */ + protected $lastCalledMethod; + + /** + * Constructor. + * + * @param PHPUnit_Extensions_Story_TestCase $caller + */ + public function __construct($test) + { + if ($test instanceof PHPUnit_Extensions_Story_TestCase || + $test instanceof PHPUnit_Extensions_Story_SeleniumTestCase) { + $this->test = $test; + } else { + throw new Exception('$test must either be PHPUnit_Extensions_Story_TestCase or PHPUnit_Extensions_Story_SeleniumTestCase'); + } + } + + /** + * Adds a "Given" step to the scenario. + * + * @param array $arguments + * @return PHPUnit_Extensions_Story_TestCase + */ + public function given($arguments) + { + return $this->addStep(new PHPUnit_Extensions_Story_Given($arguments)); + } + + /** + * Adds a "When" step to the scenario. + * + * @param array $arguments + * @return PHPUnit_Extensions_Story_TestCase + */ + public function when($arguments) + { + return $this->addStep(new PHPUnit_Extensions_Story_When($arguments)); + } + + /** + * Adds a "Then" step to the scenario. + * + * @param array $arguments + * @return PHPUnit_Extensions_Story_TestCase + */ + public function then($arguments) + { + return $this->addStep(new PHPUnit_Extensions_Story_Then($arguments)); + } + + /** + * Add another step of the same type as the step that was added before. + * + * @param array $arguments + * @return PHPUnit_Extensions_Story_TestCase + */ + public function _and($arguments) + { + $lastCalledStepClass = get_class($this->steps[count($this->steps)-1]); + + return $this->addStep(new $lastCalledStepClass($arguments)); + } + + /** + * Runs this scenario. + * + * @param array $world + */ + public function run(array &$world) + { + foreach ($this->steps as $step) + { + if ($step instanceof PHPUnit_Extensions_Story_Given) { + $this->test->runGiven( + $world, $step->getAction(), $step->getArguments() + ); + } + + else if ($step instanceof PHPUnit_Extensions_Story_When) { + $this->test->runWhen( + $world, $step->getAction(), $step->getArguments() + ); + } + + else { + $this->test->runThen( + $world, $step->getAction(), $step->getArguments() + ); + } + } + } + + /** + * Adds a step to the scenario. + * + * @param PHPUnit_Extensions_Story_Step $step + * @return PHPUnit_Extensions_Story_TestCase + */ + protected function addStep(PHPUnit_Extensions_Story_Step $step) + { + $this->steps[] = $step; + + return $this->test; + } + + /** + * Returns the steps of this scenario. + * + * @return array + */ + public function getSteps() + { + return $this->steps; + } +} +?> diff --git a/tests/PHPUnit/Extensions/Story/SeleniumTestCase.php b/tests/PHPUnit/Extensions/Story/SeleniumTestCase.php new file mode 100755 index 00000000..143dc6d0 --- /dev/null +++ b/tests/PHPUnit/Extensions/Story/SeleniumTestCase.php @@ -0,0 +1,209 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Extensions/Story/Scenario.php'; +require_once 'PHPUnit/Extensions/SeleniumTestCase.php'; +require_once 'PHPUnit/Extensions/Story/TestCase.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + * @abstract + */ +abstract class PHPUnit_Extensions_Story_SeleniumTestCase extends PHPUnit_Extensions_SeleniumTestCase +{ + protected $scenario; + protected $world = array(); + + public function __construct($name = NULL, array $data = array(), $dataName = '', array $browser = array()) + { + parent::__construct($name, $data, $dataName, $browser); + $this->scenario = new PHPUnit_Extensions_Story_Scenario($this); + } + + /** + * @method PHPUnit_Extensions_Story_Step and($contextOrOutcome) + */ + public function __call($command, $arguments) + { + switch($command) { + case 'and': { + return $this->scenario->_and($arguments); + } + break; + + default: { + return parent::__call($command, $arguments); + } + } + } + + /** + * Returns this test's scenario. + * + * @return PHPUnit_Extensions_Story_Scenario + */ + public function getScenario() + { + return $this->scenario; + } + + /** + * This method is used by __call + * + */ + protected function notImplemented($action) + { + if (strstr($action, ' ')) { + $this->markTestIncomplete("step: $action not implemented."); + } + + throw new BadMethodCallException("Method $action not defined."); + } + + /** + * Adds a "Given" step to the scenario. + * + * @param array $arguments + * @return PHPUnit_Extensions_Story_TestCase + */ + protected function given($context) + { + return $this->scenario->given(func_get_args()); + } + + /** + * Adds a "When" step to the scenario. + * + * @param array $arguments + * @return PHPUnit_Extensions_Story_TestCase + */ + protected function when($event) + { + return $this->scenario->when(func_get_args()); + } + + /** + * Adds a "Then" step to the scenario. + * + * @param array $arguments + * @return PHPUnit_Extensions_Story_TestCase + */ + protected function then($outcome) + { + return $this->scenario->then(func_get_args()); + } + + /** + * Add another step of the same type as the step that was added before. + * + * @param array $arguments + * @return PHPUnit_Extensions_Story_TestCase + */ + protected function _and($contextOrOutcome) + { + return $this->scenario->_and(func_get_args()); + } + + /** + * Run this test's scenario. + * + * @throws RuntimeException + */ + protected function runTest() + { + $autostop = $this->autoStop; + $this->autoStop = FALSE; + + try { + parent::runTest(); + $this->scenario->run($this->world); + $this->autoStop = $autostop; + } + + catch (Exception $e) { + $this->autoStop = $autostop; + throw $e; + } + } + + /** + * Implementation for "Given" steps. + * + * @param array $world + * @param string $action + * @param array $arguments + */ + abstract protected function runGiven(&$world, $action, $arguments); + + /** + * Implementation for "When" steps. + * + * @param array $world + * @param string $action + * @param array $arguments + */ + abstract protected function runWhen(&$world, $action, $arguments); + + /** + * Implementation for "Then" steps. + * + * @param array $world + * @param string $action + * @param array $arguments + */ + abstract protected function runThen(&$world, $action, $arguments); +} diff --git a/tests/PHPUnit/Extensions/Story/Step.php b/tests/PHPUnit/Extensions/Story/Step.php new file mode 100755 index 00000000..17ea8b23 --- /dev/null +++ b/tests/PHPUnit/Extensions/Story/Step.php @@ -0,0 +1,135 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * A step of a scenario. + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + * @abstract + */ +abstract class PHPUnit_Extensions_Story_Step +{ + /** + * @var string + */ + protected $action; + + /** + * @var array + */ + protected $arguments; + + /** + * Constructor. + * + * @param array $arguments + */ + public function __construct(array $arguments) + { + $this->action = array_shift($arguments); + $this->arguments = $arguments; + } + + /** + * Returns this step's action. + * + * @return string + */ + public function getAction() + { + return $this->action; + } + + /** + * Returns this step's arguments. + * + * @param boolean $asString + * @return array|string + */ + public function getArguments($asString = FALSE) + { + if (!$asString) { + return $this->arguments; + } else { + switch (count($this->arguments)) { + case 0: { + return ''; + } + break; + + case 1: { + return $this->arguments[0]; + } + break; + + default: { + return var_export($this->arguments, TRUE); + } + } + } + } + + /** + * Returns this step's name. + * + * @return string + */ + abstract public function getName(); +} +?> diff --git a/tests/PHPUnit/Extensions/Story/TestCase.php b/tests/PHPUnit/Extensions/Story/TestCase.php new file mode 100755 index 00000000..1b3dba7f --- /dev/null +++ b/tests/PHPUnit/Extensions/Story/TestCase.php @@ -0,0 +1,217 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Extensions/Story/Scenario.php'; +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * A story test case. + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + * @abstract + */ +abstract class PHPUnit_Extensions_Story_TestCase extends PHPUnit_Framework_TestCase +{ + /** + * @var PHPUnit_Extensions_Story_Scenario + */ + protected $scenario; + + /** + * @var array + */ + protected $world = array(); + + /** + * Constructs a test case with the given name. + * + * @param string $name + * @param array $data + * @param string $dataName + */ + public function __construct($name = NULL, array $data = array(), $dataName = '') + { + parent::__construct($name, $data, $dataName); + $this->scenario = new PHPUnit_Extensions_Story_Scenario($this); + } + + /** + * @method PHPUnit_Extensions_Story_Step and($contextOrOutcome) + */ + public function __call($command, $arguments) + { + switch ($command) { + case 'and': { + return $this->scenario->_and($arguments); + } + break; + + default: { + throw new BadMethodCallException( + "Method $command not defined." + ); + } + } + } + + /** + * Returns this test's scenario. + * + * @return PHPUnit_Extensions_Story_Scenario + */ + public function getScenario() + { + return $this->scenario; + } + + /** + * + * + */ + protected function notImplemented($action) + { + if (strstr($action, ' ')) { + $this->markTestIncomplete("step: $action not implemented."); + } + + throw new BadMethodCallException("Method $action not defined."); + } + + /** + * Adds a "Given" step to the scenario. + * + * @param array $arguments + * @return PHPUnit_Extensions_Story_TestCase + */ + protected function given($context) + { + return $this->scenario->given(func_get_args()); + } + + /** + * Adds a "When" step to the scenario. + * + * @param array $arguments + * @return PHPUnit_Extensions_Story_TestCase + */ + protected function when($event) + { + return $this->scenario->when(func_get_args()); + } + + /** + * Adds a "Then" step to the scenario. + * + * @param array $arguments + * @return PHPUnit_Extensions_Story_TestCase + */ + protected function then($outcome) + { + return $this->scenario->then(func_get_args()); + } + + /** + * Add another step of the same type as the step that was added before. + * + * @param array $arguments + * @return PHPUnit_Extensions_Story_TestCase + */ + protected function _and($contextOrOutcome) + { + return $this->scenario->_and(func_get_args()); + } + + /** + * Run this test's scenario. + * + * @throws RuntimeException + */ + protected function runTest() + { + parent::runTest(); + $this->scenario->run($this->world); + } + + /** + * Implementation for "Given" steps. + * + * @param array $world + * @param string $action + * @param array $arguments + */ + abstract protected function runGiven(&$world, $action, $arguments); + + /** + * Implementation for "When" steps. + * + * @param array $world + * @param string $action + * @param array $arguments + */ + abstract protected function runWhen(&$world, $action, $arguments); + + /** + * Implementation for "Then" steps. + * + * @param array $world + * @param string $action + * @param array $arguments + */ + abstract protected function runThen(&$world, $action, $arguments); +} +?> diff --git a/tests/PHPUnit/Extensions/Story/Then.php b/tests/PHPUnit/Extensions/Story/Then.php new file mode 100755 index 00000000..4f38032d --- /dev/null +++ b/tests/PHPUnit/Extensions/Story/Then.php @@ -0,0 +1,79 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Extensions/Story/Step.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * A "Then" step. + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + * @abstract + */ +class PHPUnit_Extensions_Story_Then extends PHPUnit_Extensions_Story_Step +{ + /** + * Returns this step's name. + * + * @return string + */ + public function getName() + { + return 'Then'; + } +} +?> diff --git a/tests/PHPUnit/Extensions/Story/When.php b/tests/PHPUnit/Extensions/Story/When.php new file mode 100755 index 00000000..5e1d19ae --- /dev/null +++ b/tests/PHPUnit/Extensions/Story/When.php @@ -0,0 +1,79 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Extensions/Story/Step.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * A "When" step. + * + * @category Testing + * @package PHPUnit + * @author Mattis Stordalen Flister + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + * @abstract + */ +class PHPUnit_Extensions_Story_When extends PHPUnit_Extensions_Story_Step +{ + /** + * Returns this step's name. + * + * @return string + */ + public function getName() + { + return 'When'; + } +} +?> diff --git a/tests/PHPUnit/Extensions/TestDecorator.php b/tests/PHPUnit/Extensions/TestDecorator.php new file mode 100755 index 00000000..f5cee8a6 --- /dev/null +++ b/tests/PHPUnit/Extensions/TestDecorator.php @@ -0,0 +1,158 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * A Decorator for Tests. + * + * Use TestDecorator as the base class for defining new + * test decorators. Test decorator subclasses can be introduced + * to add behaviour before or after a test is run. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class PHPUnit_Extensions_TestDecorator extends PHPUnit_Framework_Assert implements PHPUnit_Framework_Test, PHPUnit_Framework_SelfDescribing +{ + /** + * The Test to be decorated. + * + * @var object + */ + protected $test = NULL; + + /** + * Constructor. + * + * @param PHPUnit_Framework_Test $test + */ + public function __construct(PHPUnit_Framework_Test $test) + { + $this->test = $test; + } + + /** + * Returns a string representation of the test. + * + * @return string + */ + public function toString() + { + return $this->test->toString(); + } + + /** + * Runs the test and collects the + * result in a TestResult. + * + * @param PHPUnit_Framework_TestResult $result + */ + public function basicRun(PHPUnit_Framework_TestResult $result) + { + $this->test->run($result); + } + + /** + * Counts the number of test cases that + * will be run by this test. + * + * @return integer + */ + public function count() + { + return count($this->test); + } + + /** + * Creates a default TestResult object. + * + * @return PHPUnit_Framework_TestResult + */ + protected function createResult() + { + return new PHPUnit_Framework_TestResult; + } + + /** + * Returns the test to be run. + * + * @return PHPUnit_Framework_Test + */ + public function getTest() + { + return $this->test; + } + + /** + * Runs the decorated test and collects the + * result in a TestResult. + * + * @param PHPUnit_Framework_TestResult $result + * @return PHPUnit_Framework_TestResult + * @throws InvalidArgumentException + */ + public function run(PHPUnit_Framework_TestResult $result = NULL) + { + if ($result === NULL) { + $result = $this->createResult(); + } + + $this->basicRun($result); + + return $result; + } +} +?> diff --git a/tests/PHPUnit/Framework.php b/tests/PHPUnit/Framework.php new file mode 100755 index 00000000..2b2629af --- /dev/null +++ b/tests/PHPUnit/Framework.php @@ -0,0 +1,72 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +require 'PHPUnit/Framework/SelfDescribing.php'; +require 'PHPUnit/Framework/AssertionFailedError.php'; +require 'PHPUnit/Framework/Assert.php'; +require 'PHPUnit/Framework/Error.php'; +require 'PHPUnit/Framework/Error/Notice.php'; +require 'PHPUnit/Framework/Error/Warning.php'; +require 'PHPUnit/Framework/IncompleteTest.php'; +require 'PHPUnit/Framework/SkippedTest.php'; +require 'PHPUnit/Framework/Test.php'; +require 'PHPUnit/Framework/TestFailure.php'; +require 'PHPUnit/Framework/TestListener.php'; +require 'PHPUnit/Framework/TestResult.php'; +require 'PHPUnit/Framework/ExpectationFailedException.php'; +require 'PHPUnit/Framework/IncompleteTestError.php'; +require 'PHPUnit/Framework/SkippedTestError.php'; +require 'PHPUnit/Framework/SkippedTestSuiteError.php'; +require 'PHPUnit/Framework/TestCase.php'; +require 'PHPUnit/Framework/TestSuite.php'; +require 'PHPUnit/Framework/Warning.php'; +require 'PHPUnit/Framework/Constraint.php'; +require 'PHPUnit/Framework/ComparisonFailure.php'; +?> diff --git a/tests/PHPUnit/Framework/Assert.php b/tests/PHPUnit/Framework/Assert.php new file mode 100755 index 00000000..50416e7d --- /dev/null +++ b/tests/PHPUnit/Framework/Assert.php @@ -0,0 +1,2084 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; +require_once 'PHPUnit/Util/XML.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!class_exists('PHPUnit_Framework_Assert', FALSE)) { + +/** + * A set of assert methods. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + * @abstract + */ +abstract class PHPUnit_Framework_Assert +{ + /** + * @var integer + */ + private static $count = 0; + + /** + * Asserts that an array has a specified key. + * + * @param mixed $key + * @param array $array + * @param string $message + * @since Method available since Release 3.0.0 + */ + public static function assertArrayHasKey($key, array $array, $message = '') + { + if (!(is_integer($key) || is_string($key))) { + throw new InvalidArgumentException; + } + + $constraint = new PHPUnit_Framework_Constraint_ArrayHasKey($key); + + self::assertThat($array, $constraint, $message); + } + + /** + * Asserts that an array does not have a specified key. + * + * @param mixed $key + * @param array $array + * @param string $message + * @since Method available since Release 3.0.0 + */ + public static function assertArrayNotHasKey($key, array $array, $message = '') + { + if (!(is_integer($key) || is_string($key))) { + throw new InvalidArgumentException; + } + + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_ArrayHasKey($key) + ); + + self::assertThat($array, $constraint, $message); + } + + /** + * Asserts that a haystack contains a needle. + * + * @param mixed $needle + * @param mixed $haystack + * @param string $message + * @since Method available since Release 2.1.0 + */ + public static function assertContains($needle, $haystack, $message = '') + { + if (is_array($haystack) || + is_object($haystack) && $haystack instanceof Iterator) { + $constraint = new PHPUnit_Framework_Constraint_TraversableContains($needle); + } + + else if (is_string($haystack)) { + $constraint = new PHPUnit_Framework_Constraint_StringContains($needle); + } + + else { + throw new InvalidArgumentException; + } + + self::assertThat($haystack, $constraint, $message); + } + + /** + * Asserts that a haystack that is stored in a static attribute of a class + * or an attribute of an object contains a needle. + * + * @param mixed $needle + * @param string $haystackAttributeName + * @param mixed $haystackClassOrObject + * @param string $message + * @since Method available since Release 3.0.0 + */ + public static function assertAttributeContains($needle, $haystackAttributeName, $haystackClassOrObject, $message = '') + { + self::assertContains( + $needle, + self::readAttribute($haystackClassOrObject, $haystackAttributeName), + $message + ); + } + + /** + * Asserts that a haystack does not contain a needle. + * + * @param mixed $needle + * @param mixed $haystack + * @param string $message + * @since Method available since Release 2.1.0 + */ + public static function assertNotContains($needle, $haystack, $message = '') + { + if (is_array($haystack) || + is_object($haystack) && $haystack instanceof Iterator) { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_TraversableContains($needle) + ); + } + + else if (is_string($haystack)) { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_StringContains($needle) + ); + } + + else { + throw new InvalidArgumentException; + } + + self::assertThat($haystack, $constraint, $message); + } + + /** + * Asserts that a haystack that is stored in a static attribute of a class + * or an attribute of an object does not contain a needle. + * + * @param mixed $needle + * @param string $haystackAttributeName + * @param mixed $haystackClassOrObject + * @param string $message + * @since Method available since Release 3.0.0 + */ + public static function assertAttributeNotContains($needle, $haystackAttributeName, $haystackClassOrObject, $message = '') + { + self::assertNotContains( + $needle, + self::readAttribute($haystackClassOrObject, $haystackAttributeName), + $message + ); + } + + /** + * Asserts that a haystack contains only values of a given type. + * + * @param string $type + * @param mixed $haystack + * @param boolean $isNativeType + * @param string $message + * @since Method available since Release 3.1.4 + */ + public static function assertContainsOnly($type, $haystack, $isNativeType = NULL, $message = '') + { + if (!(is_array($haystack) || + is_object($haystack) && $haystack instanceof Iterator)) { + throw new InvalidArgumentException; + } + + if ($isNativeType == NULL) { + $isNativeType = PHPUnit_Util_Type::isType($type); + } + + self::assertThat( + $haystack, + new PHPUnit_Framework_Constraint_TraversableContainsOnly( + $type, $isNativeType + ), + $message + ); + } + + /** + * Asserts that a haystack that is stored in a static attribute of a class + * or an attribute of an object contains only values of a given type. + * + * @param string $type + * @param string $haystackAttributeName + * @param mixed $haystackClassOrObject + * @param boolean $isNativeType + * @param string $message + * @since Method available since Release 3.1.4 + */ + public static function assertAttributeContainsOnly($type, $haystackAttributeName, $haystackClassOrObject, $isNativeType = NULL, $message = '') + { + self::assertContainsOnly( + $type, + self::readAttribute($haystackClassOrObject, $haystackAttributeName), + $isNativeType, + $message + ); + } + + /** + * Asserts that a haystack does not contain only values of a given type. + * + * @param string $type + * @param mixed $haystack + * @param boolean $isNativeType + * @param string $message + * @since Method available since Release 3.1.4 + */ + public static function assertNotContainsOnly($type, $haystack, $isNativeType = NULL, $message = '') + { + if (!(is_array($haystack) || + is_object($haystack) && $haystack instanceof Iterator)) { + throw new InvalidArgumentException; + } + + if ($isNativeType == NULL) { + $isNativeType = PHPUnit_Util_Type::isType($type); + } + + self::assertThat( + $haystack, + new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_TraversableContainsOnly( + $type, $isNativeType + ) + ), + $message + ); + } + + /** + * Asserts that a haystack that is stored in a static attribute of a class + * or an attribute of an object does not contain only values of a given type. + * + * @param string $type + * @param string $haystackAttributeName + * @param mixed $haystackClassOrObject + * @param boolean $isNativeType + * @param string $message + * @since Method available since Release 3.1.4 + */ + public static function assertAttributeNotContainsOnly($type, $haystackAttributeName, $haystackClassOrObject, $isNativeType = NULL, $message = '') + { + self::assertNotContainsOnly( + $type, + self::readAttribute($haystackClassOrObject, $haystackAttributeName), + $isNativeType, + $message + ); + } + + /** + * Asserts that two variables are equal. + * + * @param mixed $expected + * @param mixed $actual + * @param string $message + * @param float $delta + * @param integer $maxDepth + * @param boolean $canonicalizeEol + */ + public static function assertEquals($expected, $actual, $message = '', $delta = 0, $maxDepth = 10, $canonicalizeEol = FALSE) + { + $constraint = new PHPUnit_Framework_Constraint_IsEqual( + $expected, $delta, $maxDepth, $canonicalizeEol + ); + + self::assertThat($actual, $constraint, $message); + } + + /** + * Asserts that a variable is equal to an attribute of an object. + * + * @param mixed $expected + * @param string $actualAttributeName + * @param string $actualClassOrObject + * @param string $message + * @param float $delta + * @param integer $maxDepth + * @param boolean $canonicalizeEol + */ + public static function assertAttributeEquals($expected, $actualAttributeName, $actualClassOrObject, $message = '', $delta = 0, $maxDepth = 10, $canonicalizeEol = FALSE) + { + self::assertEquals( + $expected, + self::readAttribute($actualClassOrObject, $actualAttributeName), + $message, + $delta, + $maxDepth, + $canonicalizeEol + ); + } + + /** + * Asserts that two variables are not equal. + * + * @param mixed $expected + * @param mixed $actual + * @param string $message + * @param float $delta + * @param integer $maxDepth + * @param boolean $canonicalizeEol + * @since Method available since Release 2.3.0 + */ + public static function assertNotEquals($expected, $actual, $message = '', $delta = 0, $maxDepth = 10, $canonicalizeEol = FALSE) + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsEqual( + $expected, $delta, $maxDepth, $canonicalizeEol + ) + ); + + self::assertThat($actual, $constraint, $message); + } + + /** + * Asserts that a variable is not equal to an attribute of an object. + * + * @param mixed $expected + * @param string $actualAttributeName + * @param string $actualClassOrObject + * @param string $message + * @param float $delta + * @param integer $maxDepth + * @param boolean $canonicalizeEol + */ + public static function assertAttributeNotEquals($expected, $actualAttributeName, $actualClassOrObject, $message = '', $delta = 0, $maxDepth = 10, $canonicalizeEol = FALSE) + { + self::assertNotEquals( + $expected, + self::readAttribute($actualClassOrObject, $actualAttributeName), + $message, + $delta, + $maxDepth, + $canonicalizeEol + ); + } + + /** + * Asserts that a value is greater than another value. + * + * @param mixed $expected + * @param mixed $actual + * @param string $message + * @since Method available since Release 3.1.0 + */ + public static function assertGreaterThan($expected, $actual, $message = '') + { + self::assertThat($actual, self::greaterThan($expected), $message); + } + + /** + * Asserts that an attribute is greater than another value. + * + * @param mixed $expected + * @param string $actualAttributeName + * @param string $actualClassOrObject + * @param string $message + * @since Method available since Release 3.1.0 + */ + public static function assertAttributeGreaterThan($expected, $actualAttributeName, $actualClassOrObject, $message = '') + { + self::assertGreaterThan( + $expected, + self::readAttribute($actualClassOrObject, $actualAttributeName), + $message + ); + } + + /** + * Asserts that a value is greater than or equal to another value. + * + * @param mixed $expected + * @param mixed $actual + * @param string $message + * @since Method available since Release 3.1.0 + */ + public static function assertGreaterThanOrEqual($expected, $actual, $message = '') + { + self::assertThat($actual, self::greaterThanOrEqual($expected), $message); + } + + /** + * Asserts that an attribute is greater than or equal to another value. + * + * @param mixed $expected + * @param string $actualAttributeName + * @param string $actualClassOrObject + * @param string $message + * @since Method available since Release 3.1.0 + */ + public static function assertAttributeGreaterThanOrEqual($expected, $actualAttributeName, $actualClassOrObject, $message = '') + { + self::assertGreaterThanOrEqual( + $expected, + self::readAttribute($actualClassOrObject, $actualAttributeName), + $message + ); + } + + /** + * Asserts that a value is smaller than another value. + * + * @param mixed $expected + * @param mixed $actual + * @param string $message + * @since Method available since Release 3.1.0 + */ + public static function assertLessThan($expected, $actual, $message = '') + { + self::assertThat($actual, self::lessThan($expected), $message); + } + + /** + * Asserts that an attribute is smaller than another value. + * + * @param mixed $expected + * @param string $actualAttributeName + * @param string $actualClassOrObject + * @param string $message + * @since Method available since Release 3.1.0 + */ + public static function assertAttributeLessThan($expected, $actualAttributeName, $actualClassOrObject, $message = '') + { + self::assertLessThan( + $expected, + self::readAttribute($actualClassOrObject, $actualAttributeName), + $message + ); + } + + /** + * Asserts that a value is smaller than or equal to another value. + * + * @param mixed $expected + * @param mixed $actual + * @param string $message + * @since Method available since Release 3.1.0 + */ + public static function assertLessThanOrEqual($expected, $actual, $message = '') + { + self::assertThat($actual, self::lessThanOrEqual($expected), $message); + } + + /** + * Asserts that an attribute is smaller than or equal to another value. + * + * @param mixed $expected + * @param string $actualAttributeName + * @param string $actualClassOrObject + * @param string $message + * @since Method available since Release 3.1.0 + */ + public static function assertAttributeLessThanOrEqual($expected, $actualAttributeName, $actualClassOrObject, $message = '') + { + self::assertLessThanOrEqual( + $expected, + self::readAttribute($actualClassOrObject, $actualAttributeName), + $message + ); + } + + /** + * Asserts that the contents of one file is equal to the contents of another + * file. + * + * @param string $expected + * @param string $actual + * @param string $message + * @param boolean $canonicalizeEol + * @since Method available since Release 3.2.14 + */ + public static function assertFileEquals($expected, $actual, $message = '', $canonicalizeEol = FALSE) + { + self::assertFileExists($expected, $message); + self::assertFileExists($actual, $message); + + self::assertEquals( + file_get_contents($expected), + file_get_contents($actual), + $message, + 0, + 10, + $canonicalizeEol + ); + } + + /** + * Asserts that the contents of one file is not equal to the contents of + * another file. + * + * @param string $expected + * @param string $actual + * @param string $message + * @param boolean $canonicalizeEol + * @since Method available since Release 3.2.14 + */ + public static function assertFileNotEquals($expected, $actual, $message = '', $canonicalizeEol = FALSE) + { + self::assertFileExists($expected, $message); + self::assertFileExists($actual, $message); + + self::assertNotEquals( + file_get_contents($expected), + file_get_contents($actual), + $message, + 0, + 10, + $canonicalizeEol + ); + } + + /** + * Asserts that the contents of a string is equal + * to the contents of a file. + * + * @param string $expectedFile + * @param string $actualString + * @param string $message + * @param boolean $canonicalizeEol + * @since Method available since Release 3.3.0 + */ + public static function assertStringEqualsFile($expectedFile, $actualString, $message = '', $canonicalizeEol = FALSE) + { + self::assertFileExists($expectedFile, $message); + + self::assertEquals( + file_get_contents($expectedFile), + $actualString, + $message, + 0, + 10, + $canonicalizeEol + ); + } + + /** + * Asserts that the contents of a string is not equal + * to the contents of a file. + * + * @param string $expectedFile + * @param string $actualString + * @param string $message + * @param boolean $canonicalizeEol + * @since Method available since Release 3.3.0 + */ + public static function assertStringNotEqualsFile($expectedFile, $actualString, $message = '', $canonicalizeEol = FALSE) + { + self::assertFileExists($expectedFile, $message); + + self::assertNotEquals( + file_get_contents($expectedFile), + $actualString, + $message, + 0, + 10, + $canonicalizeEol + ); + } + + /** + * Asserts that a file exists. + * + * @param string $filename + * @param string $message + * @since Method available since Release 3.0.0 + */ + public static function assertFileExists($filename, $message = '') + { + if (!is_string($filename)) { + throw new InvalidArgumentException; + } + + $constraint = new PHPUnit_Framework_Constraint_FileExists; + + self::assertThat($filename, $constraint, $message); + } + + /** + * Asserts that a file does not exist. + * + * @param string $filename + * @param string $message + * @since Method available since Release 3.0.0 + */ + public static function assertFileNotExists($filename, $message = '') + { + if (!is_string($filename)) { + throw new InvalidArgumentException; + } + + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_FileExists + ); + + self::assertThat($filename, $constraint, $message); + } + + /** + * Asserts that a condition is true. + * + * @param boolean $condition + * @param string $message + * @throws PHPUnit_Framework_AssertionFailedError + */ + public static function assertTrue($condition, $message = '') + { + self::assertThat($condition, self::isTrue(), $message); + } + + /** + * Asserts that a condition is false. + * + * @param boolean $condition + * @param string $message + * @throws PHPUnit_Framework_AssertionFailedError + */ + public static function assertFalse($condition, $message = '') + { + self::assertThat($condition, self::isFalse(), $message); + } + + /** + * Asserts that a variable is not NULL. + * + * @param mixed $actual + * @param string $message + */ + public static function assertNotNull($actual, $message = '') + { + self::assertThat($actual, self::logicalNot(self::isNull()), $message); + } + + /** + * Asserts that a variable is NULL. + * + * @param mixed $actual + * @param string $message + */ + public static function assertNull($actual, $message = '') + { + self::assertThat($actual, self::isNull(), $message); + } + + /** + * Asserts that a class has a specified attribute. + * + * @param string $attributeName + * @param string $className + * @param string $message + * @since Method available since Release 3.1.0 + */ + public static function assertClassHasAttribute($attributeName, $className, $message = '') + { + if (!is_string($attributeName) || !is_string($className) || !class_exists($className, FALSE)) { + throw new InvalidArgumentException; + } + + $constraint = new PHPUnit_Framework_Constraint_ClassHasAttribute($attributeName); + + self::assertThat($className, $constraint, $message); + } + + /** + * Asserts that a class does not have a specified attribute. + * + * @param string $attributeName + * @param string $className + * @param string $message + * @since Method available since Release 3.1.0 + */ + public static function assertClassNotHasAttribute($attributeName, $className, $message = '') + { + if (!is_string($attributeName) || !is_string($className) || !class_exists($className)) { + throw new InvalidArgumentException; + } + + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_ClassHasAttribute($attributeName) + ); + + self::assertThat($className, $constraint, $message); + } + + /** + * Asserts that a class has a specified static attribute. + * + * @param string $attributeName + * @param string $className + * @param string $message + * @since Method available since Release 3.1.0 + */ + public static function assertClassHasStaticAttribute($attributeName, $className, $message = '') + { + if (!is_string($attributeName) || !is_string($className) || !class_exists($className)) { + throw new InvalidArgumentException; + } + + $constraint = new PHPUnit_Framework_Constraint_ClassHasStaticAttribute($attributeName); + + self::assertThat($className, $constraint, $message); + } + + /** + * Asserts that a class does not have a specified static attribute. + * + * @param string $attributeName + * @param string $className + * @param string $message + * @since Method available since Release 3.1.0 + */ + public static function assertClassNotHasStaticAttribute($attributeName, $className, $message = '') + { + if (!is_string($attributeName) || !is_string($className) || !class_exists($className)) { + throw new InvalidArgumentException; + } + + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_ClassHasStaticAttribute($attributeName) + ); + + self::assertThat($className, $constraint, $message); + } + + /** + * Asserts that an object has a specified attribute. + * + * @param string $attributeName + * @param object $object + * @param string $message + * @since Method available since Release 3.0.0 + */ + public static function assertObjectHasAttribute($attributeName, $object, $message = '') + { + if (!is_string($attributeName) || !is_object($object)) { + throw new InvalidArgumentException; + } + + $constraint = new PHPUnit_Framework_Constraint_ObjectHasAttribute($attributeName); + + self::assertThat($object, $constraint, $message); + } + + /** + * Asserts that an object does not have a specified attribute. + * + * @param string $attributeName + * @param object $object + * @param string $message + * @since Method available since Release 3.0.0 + */ + public static function assertObjectNotHasAttribute($attributeName, $object, $message = '') + { + if (!is_string($attributeName) || !is_object($object)) { + throw new InvalidArgumentException; + } + + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_ObjectHasAttribute($attributeName) + ); + + self::assertThat($object, $constraint, $message); + } + + /** + * Asserts that two variables have the same type and value. + * Used on objects, it asserts that two variables reference + * the same object. + * + * @param mixed $expected + * @param mixed $actual + * @param string $message + */ + public static function assertSame($expected, $actual, $message = '') + { + if (is_bool($expected) && is_bool($actual)) { + self::assertEquals($expected, $actual, $message); + } else { + $constraint = new PHPUnit_Framework_Constraint_IsIdentical($expected); + + self::assertThat($actual, $constraint, $message); + } + } + + /** + * Asserts that a variable and an attribute of an object have the same type + * and value. + * + * @param mixed $expected + * @param string $actualAttributeName + * @param object $actualClassOrObject + * @param string $message + */ + public static function assertAttributeSame($expected, $actualAttributeName, $actualClassOrObject, $message = '') + { + self::assertSame( + $expected, + self::readAttribute($actualClassOrObject, $actualAttributeName), + $message + ); + } + + /** + * Asserts that two variables do not have the same type and value. + * Used on objects, it asserts that two variables do not reference + * the same object. + * + * @param mixed $expected + * @param mixed $actual + * @param string $message + */ + public static function assertNotSame($expected, $actual, $message = '') + { + if (is_bool($expected) && is_bool($actual)) { + self::assertNotEquals($expected, $actual, $message); + } else { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsIdentical($expected) + ); + + self::assertThat($actual, $constraint, $message); + } + } + + /** + * Asserts that a variable and an attribute of an object do not have the + * same type and value. + * + * @param mixed $expected + * @param string $actualAttributeName + * @param object $actualClassOrObject + * @param string $message + */ + public static function assertAttributeNotSame($expected, $actualAttributeName, $actualClassOrObject, $message = '') + { + self::assertNotSame( + $expected, + self::readAttribute($actualClassOrObject, $actualAttributeName), + $message + ); + } + + /** + * Asserts that a variable is of a given type. + * + * @param string $expected + * @param mixed $actual + * @param string $message + */ + public static function assertType($expected, $actual, $message = '') + { + if (is_string($expected)) { + if (PHPUnit_Util_Type::isType($expected)) { + $constraint = new PHPUnit_Framework_Constraint_IsType($expected); + } + + else if (class_exists($expected) || interface_exists($expected)) { + $constraint = new PHPUnit_Framework_Constraint_IsInstanceOf( + $expected + ); + } + + else { + throw new InvalidArgumentException; + } + } else { + throw new InvalidArgumentException; + } + + self::assertThat($actual, $constraint, $message); + } + + /** + * Asserts that a variable is not of a given type. + * + * @param string $expected + * @param mixed $actual + * @param string $message + * @since Method available since Release 2.2.0 + */ + public static function assertNotType($expected, $actual, $message = '') + { + if (is_string($expected)) { + if (PHPUnit_Util_Type::isType($expected)) { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsType($expected) + ); + } + + else if (class_exists($expected) || interface_exists($expected)) { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsInstanceOf($expected) + ); + } + + else { + throw new InvalidArgumentException; + } + } else { + throw new InvalidArgumentException; + } + + self::assertThat($actual, $constraint, $message); + } + + /** + * Asserts that a string matches a given regular expression. + * + * @param string $pattern + * @param string $string + * @param string $message + */ + public static function assertRegExp($pattern, $string, $message = '') + { + if (!is_string($pattern) || !is_string($string)) { + throw new InvalidArgumentException; + } + + $constraint = new PHPUnit_Framework_Constraint_PCREMatch($pattern); + + self::assertThat($string, $constraint, $message); + } + + /** + * Asserts that a string does not match a given regular expression. + * + * @param string $pattern + * @param string $string + * @param string $message + * @since Method available since Release 2.1.0 + */ + public static function assertNotRegExp($pattern, $string, $message = '') + { + if (!is_string($pattern) || !is_string($string)) { + throw new InvalidArgumentException; + } + + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_PCREMatch($pattern) + ); + + self::assertThat($string, $constraint, $message); + } + + /** + * Asserts that two XML files are equal. + * + * @param string $expectedFile + * @param string $actualFile + * @param string $message + * @since Method available since Release 3.1.0 + */ + public static function assertXmlFileEqualsXmlFile($expectedFile, $actualFile, $message = '') + { + self::assertFileExists($expectedFile); + self::assertFileExists($actualFile); + + $expected = new DOMDocument; + $expected->preserveWhiteSpace = FALSE; + $expected->load($expectedFile); + + $actual = new DOMDocument; + $actual->preserveWhiteSpace = FALSE; + $actual->load($actualFile); + + self::assertEquals($expected, $actual, $message); + } + + /** + * Asserts that two XML files are not equal. + * + * @param string $expectedFile + * @param string $actualFile + * @param string $message + * @since Method available since Release 3.1.0 + */ + public static function assertXmlFileNotEqualsXmlFile($expectedFile, $actualFile, $message = '') + { + self::assertFileExists($expectedFile); + self::assertFileExists($actualFile); + + $expected = new DOMDocument; + $expected->preserveWhiteSpace = FALSE; + $expected->load($expectedFile); + + $actual = new DOMDocument; + $actual->preserveWhiteSpace = FALSE; + $actual->load($actualFile); + + self::assertNotEquals($expected, $actual, $message); + } + + /** + * Asserts that two XML documents are equal. + * + * @param string $expectedFile + * @param string $actualXml + * @param string $message + * @since Method available since Release 3.3.0 + */ + public static function assertXmlStringEqualsXmlFile($expectedFile, $actualXml, $message = '') + { + self::assertFileExists($expectedFile); + + $expected = new DOMDocument; + $expected->preserveWhiteSpace = FALSE; + $expected->load($expectedFile); + + $actual = new DOMDocument; + $actual->preserveWhiteSpace = FALSE; + $actual->loadXML($actualXml); + + self::assertEquals($expected, $actual, $message); + } + + /** + * Asserts that two XML documents are not equal. + * + * @param string $expectedFile + * @param string $actualXml + * @param string $message + * @since Method available since Release 3.3.0 + */ + public static function assertXmlStringNotEqualsXmlFile($expectedFile, $actualXml, $message = '') + { + self::assertFileExists($expectedFile); + + $expected = new DOMDocument; + $expected->preserveWhiteSpace = FALSE; + $expected->load($expectedFile); + + $actual = new DOMDocument; + $actual->preserveWhiteSpace = FALSE; + $actual->loadXML($actualXml); + + self::assertNotEquals($expected, $actual, $message); + } + + /** + * Asserts that two XML documents are equal. + * + * @param string $expectedXml + * @param string $actualXml + * @param string $message + * @since Method available since Release 3.1.0 + */ + public static function assertXmlStringEqualsXmlString($expectedXml, $actualXml, $message = '') + { + $expected = new DOMDocument; + $expected->preserveWhiteSpace = FALSE; + $expected->loadXML($expectedXml); + + $actual = new DOMDocument; + $actual->preserveWhiteSpace = FALSE; + $actual->loadXML($actualXml); + + self::assertEquals($expected, $actual, $message); + } + + /** + * Asserts that two XML documents are not equal. + * + * @param string $expectedXml + * @param string $actualXml + * @param string $message + * @since Method available since Release 3.1.0 + */ + public static function assertXmlStringNotEqualsXmlString($expectedXml, $actualXml, $message = '') + { + $expected = new DOMDocument; + $expected->preserveWhiteSpace = FALSE; + $expected->loadXML($expectedXml); + + $actual = new DOMDocument; + $actual->preserveWhiteSpace = FALSE; + $actual->loadXML($actualXml); + + self::assertNotEquals($expected, $actual, $message); + } + + /** + * Asserts that a hierarchy of DOMNodes matches. + * + * @param DOMNode $expectedNode + * @param DOMNode $actualNode + * @param boolean $checkAttributes + * @param string $message + * @author Mattis Stordalen Flister + * @since Method available since Release 3.3.0 + */ + public static function assertEqualXMLStructure(DOMNode $expectedNode, DOMNode $actualNode, $checkAttributes = FALSE, $message = '') + { + self::assertEquals( + $expectedNode->tagName, + $actualNode->tagName, + $message + ); + + if ($checkAttributes) { + self::assertEquals( + $expectedNode->attributes->length, + $actualNode->attributes->length, + sprintf( + '%s%sNumber of attributes on node "%s" does not match', + $message, + !empty($message) ? "\n" : '', + $expectedNode->tagName + ) + ); + + for ($i = 0 ; $i < $expectedNode->attributes->length; $i++) { + $expectedAttribute = $expectedNode->attributes->item($i); + $actualAttribute = $actualNode->attributes->getNamedItem($expectedAttribute->name); + + if (!$actualAttribute) { + self::fail( + sprintf( + '%s%sCould not find attribute "%s" on node "%s"', + $message, + !empty($message) ? "\n" : '', + $expectedAttribute->name, + $expectedNode->tagName + ) + ); + } + } + } + + PHPUnit_Util_XML::removeCharacterDataNodes($expectedNode); + PHPUnit_Util_XML::removeCharacterDataNodes($actualNode); + + self::assertEquals( + $expectedNode->childNodes->length, + $actualNode->childNodes->length, + sprintf( + '%s%sNumber of child nodes of "%s" differs', + $message, + !empty($message) ? "\n" : '', + $expectedNode->tagName + ) + ); + + for ($i = 0; $i < $expectedNode->childNodes->length; $i++) { + self::assertEqualXMLStructure( + $expectedNode->childNodes->item($i), + $actualNode->childNodes->item($i), + $checkAttributes, + $message + ); + } + } + + /** + * Assert the presence, absence, or count of elements in a document matching + * the CSS $selector, regardless of the contents of those elements. + * + * The first argument, $selector, is the CSS selector used to match + * the elements in the $actual document. + * + * The second argument, $count, can be either boolean or numeric. When boolean, + * it asserts for presence of elements matching the selector (TRUE) or absence + * of elements (FALSE). When numeric, it asserts the count of elements + * + * assertSelectCount("#binder", true, $xml); // any? + * assertSelectCount(".binder", 3, $xml); // exactly 3? + * + * @param array $selector + * @param integer $count + * @param mixed $actual + * @param string $message + * @param boolean $isHtml + * @since Method available since Release 3.3.0 + * @author Mike Naberezny + * @author Derek DeVries + */ + public static function assertSelectCount($selector, $count, $actual, $message = '', $isHtml = TRUE) + { + self::assertSelectEquals($selector, TRUE, $count, $actual, $message, $isHtml); + } + + /** + * assertSelectRegExp("#binder .name", "/Mike|Derek/", true, $xml); // any? + * assertSelectRegExp("#binder .name", "/Mike|Derek/", 3, $xml); // exactly 3? + * + * @param array $selector + * @param string $pattern + * @param integer $count + * @param mixed $actual + * @param string $message + * @param boolean $isHtml + * @since Method available since Release 3.3.0 + * @author Mike Naberezny + * @author Derek DeVries + */ + public static function assertSelectRegExp($selector, $pattern, $count, $actual, $message = '', $isHtml = TRUE) + { + self::assertSelectEquals($selector, "regexp:$pattern", $count, $actual, $message, $isHtml); + } + + /** + * assertSelectEquals("#binder .name", "Chuck", true, $xml); // any? + * assertSelectEquals("#binder .name", "Chuck", false, $xml); // none? + * + * @param array $selector + * @param string $content + * @param integer $count + * @param mixed $actual + * @param string $message + * @param boolean $isHtml + * @since Method available since Release 3.3.0 + * @author Mike Naberezny + * @author Derek DeVries + */ + public static function assertSelectEquals($selector, $content, $count, $actual, $message = '', $isHtml = TRUE) + { + $tags = PHPUnit_Util_XML::cssSelect($selector, $content, $actual, $isHtml); + + // assert specific number of elements + if (is_numeric($count)) { + $counted = $tags ? count($tags) : 0; + self::assertEquals($count, $counted); + + // assert any elements exist if true, assert no elements exist if false + } else if (is_bool($count)) { + $any = count($tags) > 0 && $tags[0] instanceof DOMNode; + + if ($count) { + self::assertTrue($any, $message); + } else { + self::assertFalse($any, $message); + } + + // check for range number of elements + } else if (is_array($count) && (isset($count['>']) || isset($count['<']) || + isset($count['>=']) || isset($count['<=']))) { + $counted = $tags ? count($tags) : 0; + + if (isset($count['>'])) { + self::assertTrue($counted > $count['>'], $message); + } + + if (isset($count['>='])) { + self::assertTrue($counted >= $count['>='], $message); + } + + if (isset($count['<'])) { + self::assertTrue($counted < $count['<'], $message); + } + + if (isset($count['<='])) { + self::assertTrue($counted <= $count['<='], $message); + } + + } else { + throw new InvalidArgumentException(); + } + } + + /** + * Evaluate an HTML or XML string and assert its structure and/or contents. + * + * The first argument ($matcher) is an associative array that specifies the + * match criteria for the assertion: + * + * - `id` : the node with the given id attribute must match the corresponsing value. + * - `tag` : the node type must match the corresponding value. + * - `attributes` : a hash. The node's attributres must match the corresponsing values in the hash. + * - `content` : The text content must match the given value. + * - `parent` : a hash. The node's parent must match the corresponsing hash. + * - `child` : a hash. At least one of the node's immediate children must meet the criteria described by the hash. + * - `ancestor` : a hash. At least one of the node's ancestors must meet the criteria described by the hash. + * - `descendant` : a hash. At least one of the node's descendants must meet the criteria described by the hash. + * - `children` : a hash, for counting children of a node. Accepts the keys: + * - `count` : a number which must equal the number of children that match + * - `less_than` : the number of matching children must be greater than this number + * - `greater_than` : the number of matching children must be less than this number + * - `only` : another hash consisting of the keys to use to match on the children, and only matching children will be counted + * + * + * // Matcher that asserts that there is an element with an id="my_id". + * $matcher = array('id' => 'my_id'); + * + * // Matcher that asserts that there is a "span" tag. + * $matcher = array('tag' => 'span'); + * + * // Matcher that asserts that there is a "span" tag with the content + * // "Hello World". + * $matcher = array('tag' => 'span', 'content' => 'Hello World'); + * + * // Matcher that asserts that there is a "span" tag with content matching the + * // regular expression pattern. + * $matcher = array('tag' => 'span', 'content' => '/Try P(HP|ython)/'); + * + * // Matcher that asserts that there is a "span" with an "list" class attribute. + * $matcher = array( + * 'tag' => 'span', + * 'attributes' => array('class' => 'list') + * ); + * + * // Matcher that asserts that there is a "span" inside of a "div". + * $matcher = array( + * 'tag' => 'span', + * 'parent' => array('tag' => 'div') + * ); + * + * // Matcher that asserts that there is a "span" somewhere inside a "table". + * $matcher = array( + * 'tag' => 'span', + * 'ancestor' => array('tag' => 'table') + * ); + * + * // Matcher that asserts that there is a "span" with at least one "em" child. + * $matcher = array( + * 'tag' => 'span', + * 'child' => array('tag' => 'em') + * ); + * + * // Matcher that asserts that there is a "span" containing a (possibly nested) + * // "strong" tag. + * $matcher = array( + * 'tag' => 'span', + * 'descendant' => array('tag' => 'strong') + * ); + * + * // Matcher that asserts that there is a "span" containing 5-10 "em" tags as + * // immediate children. + * $matcher = array( + * 'tag' => 'span', + * 'children' => array( + * 'less_than' => 11, + * 'greater_than' => 4, + * 'only' => array('tag' => 'em') + * ) + * ); + * + * // Matcher that asserts that there is a "div", with an "ul" ancestor and a "li" + * // parent (with class="enum"), and containing a "span" descendant that contains + * // an element with id="my_test" and the text "Hello World". + * $matcher = array( + * 'tag' => 'div', + * 'ancestor' => array('tag' => 'ul'), + * 'parent' => array( + * 'tag' => 'li', + * 'attributes' => array('class' => 'enum') + * ), + * 'descendant' => array( + * 'tag' => 'span', + * 'child' => array( + * 'id' => 'my_test', + * 'content' => 'Hello World' + * ) + * ) + * ); + * + * // Use assertTag() to apply a $matcher to a piece of $html. + * $this->assertTag($matcher, $html); + * + * // Use assertTag() to apply a $matcher to a piece of $xml. + * $this->assertTag($matcher, $xml, '', FALSE); + * + * + * The second argument ($actual) is a string containing either HTML or + * XML text to be tested. + * + * The third argument ($message) is an optional message that will be + * used if the assertion fails. + * + * The fourth argument ($html) is an optional flag specifying whether + * to load the $actual string into a DOMDocument using the HTML or + * XML load strategy. It is TRUE by default, which assumes the HTML + * load strategy. In many cases, this will be acceptable for XML as well. + * + * @param array $matcher + * @param string $actual + * @param string $message + * @param boolean $isHtml + * @since Method available since Release 3.3.0 + * @author Mike Naberezny + * @author Derek DeVries + */ + public static function assertTag($matcher, $actual, $message = '', $isHtml = TRUE) + { + $dom = PHPUnit_Util_XML::load($actual, $isHtml); + $tags = PHPUnit_Util_XML::findNodes($dom, $matcher); + $matched = count($tags) > 0 && $tags[0] instanceof DOMNode; + + self::assertTrue($matched, $message); + } + + /** + * This assertion is the exact opposite of assertTag(). Rather than asserting + * that $matcher results in a match, it asserts that $matcher does not match. + * + * @param array $matcher + * @param string $actual + * @param string $message + * @param boolean $isHtml + * @since Method available since Release 3.3.0 + * @author Mike Naberezny + * @author Derek DeVries + */ + public static function assertNotTag($matcher, $actual, $message = '', $isHtml = TRUE) + { + $dom = PHPUnit_Util_XML::load($actual, $isHtml); + $tags = PHPUnit_Util_XML::findNodes($dom, $matcher); + $matched = count($tags) > 0 && $tags[0] instanceof DOMNode; + + self::assertFalse($matched, $message); + } + + /** + * Evaluates a PHPUnit_Framework_Constraint matcher object. + * + * @param mixed $value + * @param PHPUnit_Framework_Constraint $constraint + * @param string $message + * @since Method available since Release 3.0.0 + */ + public static function assertThat($value, PHPUnit_Framework_Constraint $constraint, $message = '') + { + self::$count++; + + if (!$constraint->evaluate($value)) { + $constraint->fail($value, $message); + } + } + + /** + * Returns a PHPUnit_Framework_Constraint_And matcher object. + * + * @return PHPUnit_Framework_Constraint_And + * @since Method available since Release 3.0.0 + */ + public static function logicalAnd() + { + $constraints = func_get_args(); + + $constraint = new PHPUnit_Framework_Constraint_And; + $constraint->setConstraints($constraints); + + return $constraint; + } + + /** + * Returns a PHPUnit_Framework_Constraint_Or matcher object. + * + * @return PHPUnit_Framework_Constraint_Or + * @since Method available since Release 3.0.0 + */ + public static function logicalOr() + { + $constraints = func_get_args(); + + $constraint = new PHPUnit_Framework_Constraint_Or; + $constraint->setConstraints($constraints); + + return $constraint; + } + + /** + * Returns a PHPUnit_Framework_Constraint_Not matcher object. + * + * @param PHPUnit_Framework_Constraint $constraint + * @return PHPUnit_Framework_Constraint_Not + * @since Method available since Release 3.0.0 + */ + public static function logicalNot(PHPUnit_Framework_Constraint $constraint) + { + return new PHPUnit_Framework_Constraint_Not($constraint); + } + + /** + * Returns a PHPUnit_Framework_Constraint_Xor matcher object. + * + * @return PHPUnit_Framework_Constraint_Xor + * @since Method available since Release 3.0.0 + */ + public static function logicalXor() + { + $constraints = func_get_args(); + + $constraint = new PHPUnit_Framework_Constraint_Xor; + $constraint->setConstraints($constraints); + + return $constraint; + } + + /** + * Returns a PHPUnit_Framework_Constraint_IsAnything matcher object. + * + * @return PHPUnit_Framework_Constraint_IsAnything + * @since Method available since Release 3.0.0 + */ + public static function anything() + { + return new PHPUnit_Framework_Constraint_IsAnything; + } + + /** + * Returns a PHPUnit_Framework_Constraint_IsTrue matcher object. + * + * @return PHPUnit_Framework_Constraint_IsTrue + * @since Method available since Release 3.3.0 + */ + public static function isTrue() + { + return new PHPUnit_Framework_Constraint_IsTrue; + } + + /** + * Returns a PHPUnit_Framework_Constraint_IsFalse matcher object. + * + * @return PHPUnit_Framework_Constraint_IsFalse + * @since Method available since Release 3.3.0 + */ + public static function isFalse() + { + return new PHPUnit_Framework_Constraint_IsFalse; + } + + /** + * Returns a PHPUnit_Framework_Constraint_IsNull matcher object. + * + * @return PHPUnit_Framework_Constraint_IsNull + * @since Method available since Release 3.3.0 + */ + public static function isNull() + { + return new PHPUnit_Framework_Constraint_IsNull; + } + + /** + * Returns a PHPUnit_Framework_Constraint_Attribute matcher object. + * + * @param PHPUnit_Framework_Constraint $constraint + * @param string $attributeName + * @return PHPUnit_Framework_Constraint_Attribute + * @since Method available since Release 3.1.0 + */ + public static function attribute(PHPUnit_Framework_Constraint $constraint, $attributeName) + { + return new PHPUnit_Framework_Constraint_Attribute( + $constraint, $attributeName + ); + } + + /** + * Returns a PHPUnit_Framework_Constraint_TraversableContains matcher + * object. + * + * @param mixed $value + * @return PHPUnit_Framework_Constraint_TraversableContains + * @since Method available since Release 3.0.0 + */ + public static function contains($value) + { + return new PHPUnit_Framework_Constraint_TraversableContains($value); + } + + /** + * Returns a PHPUnit_Framework_Constraint_TraversableContainsOnly matcher + * object. + * + * @param string $type + * @return PHPUnit_Framework_Constraint_TraversableContainsOnly + * @since Method available since Release 3.1.4 + */ + public static function containsOnly($type) + { + return new PHPUnit_Framework_Constraint_TraversableContainsOnly($type); + } + + /** + * Returns a PHPUnit_Framework_Constraint_ArrayHasKey matcher object. + * + * @param mixed $key + * @return PHPUnit_Framework_Constraint_ArrayHasKey + * @since Method available since Release 3.0.0 + */ + public static function arrayHasKey($key) + { + return new PHPUnit_Framework_Constraint_ArrayHasKey($key); + } + + /** + * Returns a PHPUnit_Framework_Constraint_IsEqual matcher object. + * + * @param mixed $value + * @param float $delta + * @param integer $maxDepth + * @return PHPUnit_Framework_Constraint_IsEqual + * @since Method available since Release 3.0.0 + */ + public static function equalTo($value, $delta = 0, $maxDepth = 10) + { + return new PHPUnit_Framework_Constraint_IsEqual($value, $delta, $maxDepth); + } + + /** + * Returns a PHPUnit_Framework_Constraint_IsEqual matcher object + * that is wrapped in a PHPUnit_Framework_Constraint_Attribute matcher + * object. + * + * @param string $attributeName + * @param mixed $value + * @param float $delta + * @param integer $maxDepth + * @return PHPUnit_Framework_Constraint_Attribute + * @since Method available since Release 3.1.0 + */ + public static function attributeEqualTo($attributeName, $value, $delta = 0, $maxDepth = 10) + { + return new PHPUnit_Framework_Constraint_Attribute( + new PHPUnit_Framework_Constraint_IsEqual($value, $delta, $maxDepth), + $attributeName + ); + } + + /** + * Returns a PHPUnit_Framework_Constraint_FileExists matcher object. + * + * @return PHPUnit_Framework_Constraint_FileExists + * @since Method available since Release 3.0.0 + */ + public static function fileExists() + { + return new PHPUnit_Framework_Constraint_FileExists; + } + + /** + * Returns a PHPUnit_Framework_Constraint_GreaterThan matcher object. + * + * @param mixed $value + * @return PHPUnit_Framework_Constraint_GreaterThan + * @since Method available since Release 3.0.0 + */ + public static function greaterThan($value) + { + return new PHPUnit_Framework_Constraint_GreaterThan($value); + } + + /** + * Returns a PHPUnit_Framework_Constraint_Or matcher object that wraps + * a PHPUnit_Framework_Constraint_IsEqual and a + * PHPUnit_Framework_Constraint_GreaterThan matcher object. + * + * @param mixed $value + * @return PHPUnit_Framework_Constraint_Or + * @since Method available since Release 3.1.0 + */ + public static function greaterThanOrEqual($value) + { + return self::logicalOr( + new PHPUnit_Framework_Constraint_IsEqual($value), + new PHPUnit_Framework_Constraint_GreaterThan($value) + ); + } + + /** + * Returns a PHPUnit_Framework_Constraint_ClassHasAttribute matcher object. + * + * @param string $attributeName + * @return PHPUnit_Framework_Constraint_ClassHasAttribute + * @since Method available since Release 3.1.0 + */ + public static function classHasAttribute($attributeName) + { + return new PHPUnit_Framework_Constraint_ClassHasAttribute($attributeName); + } + + /** + * Returns a PHPUnit_Framework_Constraint_ClassHasStaticAttribute matcher + * object. + * + * @param string $attributeName + * @return PHPUnit_Framework_Constraint_ClassHasStaticAttribute + * @since Method available since Release 3.1.0 + */ + public static function classHasStaticAttribute($attributeName) + { + return new PHPUnit_Framework_Constraint_ClassHasStaticAttribute($attributeName); + } + + /** + * Returns a PHPUnit_Framework_Constraint_ObjectHasAttribute matcher object. + * + * @param string $attributeName + * @return PHPUnit_Framework_Constraint_ObjectHasAttribute + * @since Method available since Release 3.0.0 + */ + public static function objectHasAttribute($attributeName) + { + return new PHPUnit_Framework_Constraint_ObjectHasAttribute($attributeName); + } + + /** + * Returns a PHPUnit_Framework_Constraint_IsIdentical matcher object. + * + * @param mixed $value + * @return PHPUnit_Framework_Constraint_IsIdentical + * @since Method available since Release 3.0.0 + */ + public static function identicalTo($value) + { + return new PHPUnit_Framework_Constraint_IsIdentical($value); + } + + /** + * Returns a PHPUnit_Framework_Constraint_IsInstanceOf matcher object. + * + * @param string $className + * @return PHPUnit_Framework_Constraint_IsInstanceOf + * @since Method available since Release 3.0.0 + */ + public static function isInstanceOf($className) + { + return new PHPUnit_Framework_Constraint_IsInstanceOf($className); + } + + /** + * Returns a PHPUnit_Framework_Constraint_IsType matcher object. + * + * @param string $type + * @return PHPUnit_Framework_Constraint_IsType + * @since Method available since Release 3.0.0 + */ + public static function isType($type) + { + return new PHPUnit_Framework_Constraint_IsType($type); + } + + /** + * Returns a PHPUnit_Framework_Constraint_LessThan matcher object. + * + * @param mixed $value + * @return PHPUnit_Framework_Constraint_LessThan + * @since Method available since Release 3.0.0 + */ + public static function lessThan($value) + { + return new PHPUnit_Framework_Constraint_LessThan($value); + } + + /** + * Returns a PHPUnit_Framework_Constraint_Or matcher object that wraps + * a PHPUnit_Framework_Constraint_IsEqual and a + * PHPUnit_Framework_Constraint_LessThan matcher object. + * + * @param mixed $value + * @return PHPUnit_Framework_Constraint_Or + * @since Method available since Release 3.1.0 + */ + public static function lessThanOrEqual($value) + { + return self::logicalOr( + new PHPUnit_Framework_Constraint_IsEqual($value), + new PHPUnit_Framework_Constraint_LessThan($value) + ); + } + + /** + * Returns a PHPUnit_Framework_Constraint_PCREMatch matcher object. + * + * @param string $pattern + * @return PHPUnit_Framework_Constraint_PCREMatch + * @since Method available since Release 3.0.0 + */ + public static function matchesRegularExpression($pattern) + { + return new PHPUnit_Framework_Constraint_PCREMatch($pattern); + } + + /** + * Returns a PHPUnit_Framework_Constraint_StringContains matcher object. + * + * @param string $string + * @param boolean $case + * @return PHPUnit_Framework_Constraint_StringContains + * @since Method available since Release 3.0.0 + */ + public static function stringContains($string, $case = TRUE) + { + return new PHPUnit_Framework_Constraint_StringContains($string, $case); + } + + + /** + * Fails a test with the given message. + * + * @param string $message + * @throws PHPUnit_Framework_AssertionFailedError + */ + public static function fail($message = '') + { + throw new PHPUnit_Framework_AssertionFailedError($message); + } + + /** + * Returns the value of an attribute of a class or an object. + * This also works for attributes that are declared protected or private. + * + * @param mixed $classOrObject + * @param string $attributeName + * @return mixed + * @throws InvalidArgumentException + */ + public static function readAttribute($classOrObject, $attributeName) + { + if (!is_string($attributeName)) { + throw new InvalidArgumentException; + } + + if (is_string($classOrObject)) { + if (!class_exists($classOrObject)) { + throw new InvalidArgumentException; + } + + return self::getStaticAttribute( + $classOrObject, + $attributeName + ); + } + + else if (is_object($classOrObject)) { + return self::getObjectAttribute( + $classOrObject, + $attributeName + ); + } + + else { + throw new InvalidArgumentException; + } + } + + /** + * Returns the value of a static attribute. + * This also works for attributes that are declared protected or private. + * + * @param string $className + * @param string $attributeName + * @return mixed + * @throws InvalidArgumentException + * @since Method available since Release 3.1.0 + */ + public static function getStaticAttribute($className, $attributeName) + { + if (!is_string($className) || !class_exists($className) || !is_string($attributeName)) { + throw new InvalidArgumentException; + } + + $class = new ReflectionClass($className); + $attributes = $class->getStaticProperties(); + + if (array_key_exists($attributeName, $attributes)) { + return $attributes[$attributeName]; + } + + if (version_compare(PHP_VERSION, '5.2', '<')) { + $protectedName = "\0*\0" . $attributeName; + } else { + $protectedName = '*' . $attributeName; + } + + if (array_key_exists($protectedName, $attributes)) { + return $attributes[$protectedName]; + } + + $classes = PHPUnit_Util_Class::getHierarchy($className); + + foreach ($classes as $class) { + $privateName = sprintf( + "\0%s\0%s", + + $class, + $attributeName + ); + + if (array_key_exists($privateName, $attributes)) { + return $attributes[$privateName]; + } + } + + throw new RuntimeException( + sprintf( + 'Attribute "%s" not found in class.', + + $attributeName + ) + ); + } + + /** + * Returns the value of an object's attribute. + * This also works for attributes that are declared protected or private. + * + * @param object $object + * @param string $attributeName + * @return mixed + * @throws InvalidArgumentException + * @since Method available since Release 3.1.0 + */ + public static function getObjectAttribute($object, $attributeName) + { + if (!is_object($object) || !is_string($attributeName)) { + throw new InvalidArgumentException; + } + + self::assertObjectHasAttribute($attributeName, $object); + + try { + $attribute = new ReflectionProperty($object, $attributeName); + } + + catch (ReflectionException $e) { + // Workaround for http://bugs.php.net/46064 + if (version_compare(PHP_VERSION, '5.2.7', '<')) { + $reflector = new ReflectionObject($object); + $attributes = $reflector->getProperties(); + + foreach ($attributes as $_attribute) { + if ($_attribute->getName() == $attributeName) { + $attribute = $_attribute; + break; + } + } + } + + $reflector = new ReflectionObject($object); + + while ($reflector = $reflector->getParentClass()) { + try { + $attribute = $reflector->getProperty($attributeName); + break; + } + + catch(ReflectionException $e) { + } + } + } + + if ($attribute->isPublic()) { + return $object->$attributeName; + } else { + $array = (array)$object; + $protectedName = "\0*\0" . $attributeName; + + if (array_key_exists($protectedName, $array)) { + return $array[$protectedName]; + } else { + $classes = PHPUnit_Util_Class::getHierarchy(get_class($object)); + + foreach ($classes as $class) { + $privateName = sprintf( + "\0%s\0%s", + + $class, + $attributeName + ); + + if (array_key_exists($privateName, $array)) { + return $array[$privateName]; + } + } + } + } + + throw new RuntimeException( + sprintf( + 'Attribute "%s" not found in object.', + + $attributeName + ) + ); + } + + /** + * Mark the test as incomplete. + * + * @param string $message + * @throws PHPUnit_Framework_IncompleteTestError + * @since Method available since Release 3.0.0 + */ + public static function markTestIncomplete($message = '') + { + throw new PHPUnit_Framework_IncompleteTestError($message); + } + + /** + * Mark the test as skipped. + * + * @param string $message + * @throws PHPUnit_Framework_SkippedTestError + * @since Method available since Release 3.0.0 + */ + public static function markTestSkipped($message = '') + { + throw new PHPUnit_Framework_SkippedTestError($message); + } + + /** + * Return the current assertion count. + * + * @return integer + * @since Method available since Release 3.3.3 + */ + public static function getCount() + { + return self::$count; + } + + /** + * Reset the assertion counter. + * + * @since Method available since Release 3.3.3 + */ + public static function resetCount() + { + self::$count = 0; + } +} + +} +?> diff --git a/tests/PHPUnit/Framework/AssertionFailedError.php b/tests/PHPUnit/Framework/AssertionFailedError.php new file mode 100755 index 00000000..891f8c49 --- /dev/null +++ b/tests/PHPUnit/Framework/AssertionFailedError.php @@ -0,0 +1,102 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!class_exists('PHPUnit_Framework_AssertionFailedError', FALSE)) { + +/** + * Thrown when an assertion failed. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class PHPUnit_Framework_AssertionFailedError extends Exception implements PHPUnit_Framework_SelfDescribing +{ + /** + * Returns the location where this failure occured. + * + * @return array + * @since Method available since Release 3.0.0 + */ + public function getLocation() + { + foreach ($this->getTrace() as $frame) { + if (!isset($frame['line'])) { + break; + } + + $result = array( + 'file' => $frame['file'], + 'line' => $frame['line'] + ); + } + + return $result; + } + + /** + * Wrapper for getMessage() which is declared as final. + * + * @return string + */ + public function toString() + { + return $this->getMessage(); + } +} + +} +?> diff --git a/tests/PHPUnit/Framework/ComparisonFailure.php b/tests/PHPUnit/Framework/ComparisonFailure.php new file mode 100755 index 00000000..ea647b48 --- /dev/null +++ b/tests/PHPUnit/Framework/ComparisonFailure.php @@ -0,0 +1,297 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!class_exists('PHPUnit_Framework_ComparisonFailure', FALSE)) { + +/** + * Thrown when an assertion for string equality failed. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +abstract class PHPUnit_Framework_ComparisonFailure extends PHPUnit_Framework_AssertionFailedError +{ + /** + * Expected value of the retrieval which does not match $actual. + * @var mixed + */ + protected $expected; + + /** + * Actually retrieved value which does not match $expected. + * @var mixed + */ + protected $actual; + + /** + * @var boolean + */ + protected $identical; + + /** + * Optional message which is placed in front of the first line + * returned by toString(). + * @var string + */ + protected $message; + + /** + * @var boolean + */ + protected static $hasDiff = NULL; + + /** + * Initialises with the expected value and the actual value. + * + * @param mixed $expected Expected value retrieved. + * @param mixed $actual Actual value retrieved. + * @param boolean $identical + * @param string $message A string which is prefixed on all returned lines + * in the difference output. + */ + public function __construct($expected, $actual, $identical = FALSE, $message = '') + { + $this->expected = $expected; + $this->actual = $actual; + $this->identical = $identical; + $this->message = $message; + } + + public function getActual() + { + return $this->actual; + } + + public function getExpected() + { + return $this->expected; + } + + public function identical() + { + return $this->identical; + } + + /** + * Figures out which diff class to use for the input types then + * instantiates that class and returns the object. + * @note The diff is type sensitive, if the type differs only the types + * are shown. + * + * @param mixed $expected Expected value retrieved. + * @param mixed $actual Actual value retrieved. + * @param string $message A string which is prefixed on all returned lines + * in the difference output. + * @return PHPUnit_Framework_ComparisonFailure + */ + public static function diffIdentical($expected, $actual, $message = '') + { + if (gettype($expected) !== gettype($actual)) { + return new PHPUnit_Framework_ComparisonFailure_Type($expected, $actual, TRUE, $message); + } + + elseif (is_string($expected)) { + return new PHPUnit_Framework_ComparisonFailure_String($expected, $actual, TRUE, $message); + } + + elseif (is_null($expected) || is_scalar($expected)) { + return new PHPUnit_Framework_ComparisonFailure_Scalar($expected, $actual, TRUE, $message); + } + + elseif (is_array($expected)) { + return new PHPUnit_Framework_ComparisonFailure_Array($expected, $actual, TRUE, $message); + } + + elseif (is_object($expected)) { + return new PHPUnit_Framework_ComparisonFailure_Object($expected, $actual, TRUE, $message); + } + } + + /** + * Figures out which diff class to use for the input types then + * instantiates that class and returns the object. + * @note The diff is not type sensitive, if the type differs the $actual + * value will be converted to the same type as the $expected. + * + * @param mixed $expected Expected value retrieved. + * @param mixed $actual Actual value retrieved. + * @param string $message A string which is prefixed on all returned lines + * in the difference output. + * @return PHPUnit_Framework_ComparisonFailure + */ + public static function diffEqual($expected, $actual, $message = '') + { + if (is_string($expected) && !is_object($actual)) { + return new PHPUnit_Framework_ComparisonFailure_String($expected, $actual, FALSE, $message); + } + + elseif (is_null($expected) || is_scalar($expected)) { + return new PHPUnit_Framework_ComparisonFailure_Scalar($expected, $actual, FALSE, $message); + } + + elseif (is_array($expected)) { + return new PHPUnit_Framework_ComparisonFailure_Array($expected, $actual, FALSE, $message); + } + + elseif (is_object($expected)) { + return new PHPUnit_Framework_ComparisonFailure_Object($expected, $actual, FALSE, $message); + } + } + + protected function diff($expected, $actual) + { + if (defined('PHPUNIT_TMPDIR')) { + $tmpDir = PHPUNIT_TMPDIR; + } + + else if (function_exists('sys_get_temp_dir')) { + $tmpDir = sys_get_temp_dir(); + } + + else { + $tmpDir = '/tmp'; + } + + $expectedFile = tempnam($tmpDir, 'expected'); + $actualFile = tempnam($tmpDir, 'actual'); + + file_put_contents($expectedFile, $expected); + file_put_contents($actualFile, $actual); + + $buffer = shell_exec( + sprintf( + 'diff -u %s %s', + escapeshellarg($expectedFile), + escapeshellarg($actualFile) + ) + ); + + unlink($expectedFile); + unlink($actualFile); + + if (!empty($buffer)) { + $buffer = explode("\n", $buffer); + + $buffer[0] = "--- Expected"; + $buffer[1] = "+++ Actual"; + + $buffer = implode("\n", $buffer); + } + + return $buffer; + } + + public static function hasDiff() + { + if (self::$hasDiff === NULL) + { + self::$hasDiff = FALSE; + + $binary = 'diff'; + + if (substr(php_uname('s'), 0, 7) == 'Windows') + { + $binary .= '.exe'; + } + + if (isset($_ENV['PATH'])) { + $var = $_ENV['PATH']; + } + + else if (isset($_ENV['Path'])) { + $var = $_ENV['Path']; + } + + else if (isset($_SERVER['PATH'])) { + $var = $_SERVER['PATH']; + } + + else if (isset($_SERVER['Path'])) { + $var = $_SERVER['Path']; + } + + if (isset($var)) { + $paths = explode(PATH_SEPARATOR, $var); + } else { + $paths = array(); + } + + foreach ($paths as $path) { + if (file_exists($path . DIRECTORY_SEPARATOR . $binary) && + is_executable($path . DIRECTORY_SEPARATOR . $binary)) + { + self::$hasDiff = TRUE; + break; + } + } + } + + return self::$hasDiff; + } +} + +} + +require_once 'PHPUnit/Framework/ComparisonFailure/Array.php'; +require_once 'PHPUnit/Framework/ComparisonFailure/Object.php'; +require_once 'PHPUnit/Framework/ComparisonFailure/Scalar.php'; +require_once 'PHPUnit/Framework/ComparisonFailure/String.php'; +require_once 'PHPUnit/Framework/ComparisonFailure/Type.php'; +?> diff --git a/tests/PHPUnit/Framework/ComparisonFailure/Array.php b/tests/PHPUnit/Framework/ComparisonFailure/Array.php new file mode 100755 index 00000000..3a59108b --- /dev/null +++ b/tests/PHPUnit/Framework/ComparisonFailure/Array.php @@ -0,0 +1,145 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Thrown when an assertion for array equality failed. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_ComparisonFailure_Array extends PHPUnit_Framework_ComparisonFailure +{ + /** + * Returns a string describing the difference between the expected and the + * actual array. + * + * @return string + */ + public function toString() + { + if ($this->hasDiff()) { + $diff = $this->diff( + print_r($this->expected, TRUE), print_r($this->actual, TRUE) + ); + + if (!empty($diff)) { + return $diff; + } + } + + // Fallback: Either diff is not available or the print_r() output for + // the expected and the actual array are equal (but the arrays are not). + + $expectedOnly = array(); + $actualOnly = array(); + $diff = ''; + + foreach ($this->expected as $expectedKey => $expectedValue) { + if (!array_key_exists($expectedKey, $this->actual)) { + $expectedOnly[] = $expectedKey; + continue; + } + + if ($expectedValue === $this->actual[$expectedKey]) { + continue; + } + + $diffObject = PHPUnit_Framework_ComparisonFailure::diffIdentical( + $expectedValue, + $this->actual[$expectedKey], + sprintf( + '%sarray key %s: ', + + $this->message, + PHPUnit_Util_Type::toString($expectedKey) + ) + ); + + $diff .= $diffObject->toString() . "\n"; + } + + foreach ($this->actual as $actualKey => $actualValue) { + if (!array_key_exists($actualKey, $this->expected)) { + $actualOnly[] = $actualKey; + continue; + } + } + + foreach ($expectedOnly as $expectedKey) { + $diff .= sprintf( + "array key %s: only in expected %s\n", + + PHPUnit_Util_Type::toString($expectedKey), + PHPUnit_Util_Type::toString($this->expected[$expectedKey]) + ); + } + + foreach ($actualOnly as $actualKey) { + $diff .= sprintf( + "array key %s: only in actual %s\n", + + PHPUnit_Util_Type::toString($actualKey), + PHPUnit_Util_Type::toString($this->actual[$actualKey]) + ); + } + + return $diff; + } +} +?> diff --git a/tests/PHPUnit/Framework/ComparisonFailure/Object.php b/tests/PHPUnit/Framework/ComparisonFailure/Object.php new file mode 100755 index 00000000..6c0e7625 --- /dev/null +++ b/tests/PHPUnit/Framework/ComparisonFailure/Object.php @@ -0,0 +1,150 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Thrown when an assertion for object equality failed. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_ComparisonFailure_Object extends PHPUnit_Framework_ComparisonFailure +{ + /** + * Returns a string describing the difference between the expected and the + * actual object. + * + * @return string + */ + public function toString() + { + if ($this->hasDiff()) { + $diff = $this->diff( + print_r($this->expected, TRUE), print_r($this->actual, TRUE) + ); + + if (!empty($diff)) { + return $diff; + } + } + + // Fallback: Either diff is not available or the print_r() output for + // the expected and the actual object are equal (but the objects are not). + + $expectedClass = get_class($this->expected); + $actualClass = get_class($this->actual); + + if ($expectedClass !== $actualClass) { + return sprintf( + "%s%sexpected class <%s>\n" . + '%sgot class <%s>', + + $this->message, + ($this->message != '') ? ' ' : '', + $expectedClass, + ($this->message != '') ? str_repeat(' ', strlen($this->message) + 1) : '', + $actualClass + ); + } else { + $expectedReflection = new ReflectionClass($expectedClass); + $actualReflection = new ReflectionClass($actualClass); + + $diff = "in object of class <{$expectedClass}>:\n"; + $i = 0; + + foreach($expectedReflection->getProperties() as $expectedAttribute) { + if ($expectedAttribute->isPrivate() || $expectedAttribute->isProtected()) continue; + + $actualAttribute = $actualReflection->getProperty($expectedAttribute->getName()); + $expectedValue = $expectedAttribute->getValue($this->expected); + $actualValue = $actualAttribute->getValue($this->actual); + + if ($expectedValue !== $actualValue) { + if ($i > 0) { + $diff .= "\n"; + } + + ++$i; + + $expectedType = gettype($expectedValue); + $actualType = gettype($actualValue); + + if ($expectedType !== $actualType) { + $diffObject = new PHPUnit_Framework_ComparisonFailure_Type($expectedValue, $actualValue, $this->message . 'attribute <' . $expectedAttribute->getName() . '>: '); + $diff .= $diffObject->toString(); + } + + elseif (is_object($expectedValue)) { + if (get_class($expectedValue) !== get_class($actualValue)) { + $diffObject = new PHPUnit_Framework_ComparisonFailure_Type($expectedValue, $actualValue, $this->message . 'attribute <' . $expectedAttribute->getName() . '>: '); + $diff .= $diffObject->toString(); + } else { + $diff .= 'attribute <' . $expectedAttribute->getName() . '> contains object <' . get_class($expectedValue) . '> with different attributes'; + } + } else { + $diffObject = PHPUnit_Framework_ComparisonFailure::diffIdentical($expectedValue, $actualValue, $this->message . 'attribute <' . $expectedAttribute->getName() . '>: '); + $diff .= $diffObject->toString(); + } + } + } + + return $diff; + } + } +} +?> diff --git a/tests/PHPUnit/Framework/ComparisonFailure/Scalar.php b/tests/PHPUnit/Framework/ComparisonFailure/Scalar.php new file mode 100755 index 00000000..976228d1 --- /dev/null +++ b/tests/PHPUnit/Framework/ComparisonFailure/Scalar.php @@ -0,0 +1,108 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Thrown when an assertion for scalar equality failed. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_ComparisonFailure_Scalar extends PHPUnit_Framework_ComparisonFailure +{ + /** + * Returns a string describing the difference between the expected and the + * actual scalar value. + */ + public function toString() + { + if (is_numeric($this->expected) && is_numeric($this->actual)) { + $type = gettype($this->expected); + $expectedString = print_r($this->expected, TRUE); + $actualString = print_r($this->actual, TRUE); + $differenceString = print_r(abs($this->actual - $this->expected), TRUE); + + $expectedLen = strlen($expectedString); + $actualLen = strlen($actualString); + $differenceLen = strlen($differenceString); + $maxLen = max($expectedLen, $actualLen, $differenceLen); + + $expectedString = str_pad($expectedString, $maxLen, ' ', STR_PAD_LEFT); + $differenceString = str_pad($differenceString, $maxLen, ' ', STR_PAD_LEFT); + $actualString = str_pad($actualString, $maxLen, ' ', STR_PAD_LEFT); + + return sprintf( + "%s%sexpected %s <%s>\n" . + "%sdifference%s<%s>\n" . + '%sgot %s <%s>', + + $this->message, + ($this->message != '') ? ' ' : '', + $type, + $expectedString, + ($this->message != '') ? str_repeat(' ', strlen($this->message) + 1) : '', + str_repeat(' ', strlen($type)), + $differenceString, + ($this->message != '') ? str_repeat(' ', strlen($this->message) + 1) : '', + $type, + $actualString + ); + } + } +} +?> diff --git a/tests/PHPUnit/Framework/ComparisonFailure/String.php b/tests/PHPUnit/Framework/ComparisonFailure/String.php new file mode 100755 index 00000000..edf722ee --- /dev/null +++ b/tests/PHPUnit/Framework/ComparisonFailure/String.php @@ -0,0 +1,120 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Thrown when an assertion for string equality failed. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_ComparisonFailure_String extends PHPUnit_Framework_ComparisonFailure +{ + /** + * Returns a string describing the difference between + * the expected and the actual string value. + */ + public function toString() + { + $expected = (string)$this->expected; + $actual = (string)$this->actual; + + if (strpos($expected, "\n") !== FALSE || strpos($actual, "\n") !== FALSE) { + if ($this->hasDiff()) { + return $this->diff($expected, $actual); + } else { + return ''; + } + } + + $expectedLen = strlen($expected); + $actualLen = strlen($actual); + $minLen = min($expectedLen, $actualLen); + $maxLen = max($expectedLen, $actualLen); + + for ($i = 0; $i < $minLen; ++$i) { + if ($expected[$i] != $actual[$i]) break; + } + + $startPos = $i; + $endPos = $minLen; + + if ($minLen > 0) { + for ($i = $minLen - 1; $i > $startPos; --$i) { + if ($expected[$i] != $actual[$i]) break; + } + + $endPos = $i + 1; + } + + return sprintf( + "%s%sexpected string <%s>\n" . + "%sdifference <%s>\n" . + '%sgot string <%s>', + + $this->message, + ($this->message != '') ? ' ' : '', + $expected, + ($this->message != '') ? str_repeat(' ', strlen($this->message) + 1) : '', + str_repeat(' ', $startPos) . str_repeat('x', $endPos - $startPos) . str_repeat('?', $maxLen - $minLen), + ($this->message != '') ? str_repeat(' ', strlen($this->message) + 1) : '', + $actual + ); + } +} +?> diff --git a/tests/PHPUnit/Framework/ComparisonFailure/Type.php b/tests/PHPUnit/Framework/ComparisonFailure/Type.php new file mode 100755 index 00000000..4f18a574 --- /dev/null +++ b/tests/PHPUnit/Framework/ComparisonFailure/Type.php @@ -0,0 +1,82 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Thrown when an assertion for type equality failed. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_ComparisonFailure_Type extends PHPUnit_Framework_ComparisonFailure +{ + /** + * Returns a string describing the type difference between the expected + * and the actual value. + */ + public function toString() + { + return sprintf( + '%s does not match expected type "%s".', + + PHPUnit_Util_Type::toString($this->actual), + gettype($this->expected) + ); + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint.php b/tests/PHPUnit/Framework/Constraint.php new file mode 100755 index 00000000..c27bbb55 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint.php @@ -0,0 +1,176 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!class_exists('PHPUnit_Framework_Constraint', FALSE)) { + +/** + * Abstract base class for constraints. which are placed upon any value. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 3.0.0 + */ +abstract class PHPUnit_Framework_Constraint implements PHPUnit_Framework_SelfDescribing +{ + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + abstract public function evaluate($other); + + /** + * Creates the appropriate exception for the constraint which can be caught + * by the unit test system. This can be called if a call to evaluate() fails. + * + * @param mixed $other The value passed to evaluate() which failed the + * constraint check. + * @param string $description A string with extra description of what was + * going on while the evaluation failed. + * @param boolean $not Flag to indicate negation. + * @throws PHPUnit_Framework_ExpectationFailedException + */ + public function fail($other, $description, $not = FALSE) + { + throw new PHPUnit_Framework_ExpectationFailedException( + $this->failureDescription($other, $description, $not), + NULL + ); + } + + protected function failureDescription($other, $description, $not) + { + $failureDescription = $this->customFailureDescription( + $other, $description, $not + ); + + if ($failureDescription === NULL) { + $failureDescription = sprintf( + 'Failed asserting that %s %s.', + + PHPUnit_Util_Type::toString($other), + $this->toString() + ); + } + + if ($not) { + $failureDescription = self::negate($failureDescription); + } + + if (!empty($description)) { + $failureDescription = $description . "\n" . $failureDescription; + } + + return $failureDescription; + } + + protected function customFailureDescription($other, $description, $not) + { + } + + public static function negate($string) + { + return str_replace( + array( + 'contains ', + 'exists', + 'has ', + 'is ', + 'matches ' + ), + array( + 'does not contain ', + 'does not exist', + 'does not have ', + 'is not ', + 'does not match ' + ), + $string + ); + } +} + +} + +require_once 'PHPUnit/Framework/Constraint/And.php'; +require_once 'PHPUnit/Framework/Constraint/ArrayHasKey.php'; +require_once 'PHPUnit/Framework/Constraint/Attribute.php'; +require_once 'PHPUnit/Framework/Constraint/ClassHasAttribute.php'; +require_once 'PHPUnit/Framework/Constraint/ClassHasStaticAttribute.php'; +require_once 'PHPUnit/Framework/Constraint/IsFalse.php'; +require_once 'PHPUnit/Framework/Constraint/FileExists.php'; +require_once 'PHPUnit/Framework/Constraint/GreaterThan.php'; +require_once 'PHPUnit/Framework/Constraint/IsAnything.php'; +require_once 'PHPUnit/Framework/Constraint/IsEqual.php'; +require_once 'PHPUnit/Framework/Constraint/IsIdentical.php'; +require_once 'PHPUnit/Framework/Constraint/IsInstanceOf.php'; +require_once 'PHPUnit/Framework/Constraint/IsType.php'; +require_once 'PHPUnit/Framework/Constraint/LessThan.php'; +require_once 'PHPUnit/Framework/Constraint/Not.php'; +require_once 'PHPUnit/Framework/Constraint/IsNull.php'; +require_once 'PHPUnit/Framework/Constraint/ObjectHasAttribute.php'; +require_once 'PHPUnit/Framework/Constraint/Or.php'; +require_once 'PHPUnit/Framework/Constraint/PCREMatch.php'; +require_once 'PHPUnit/Framework/Constraint/StringContains.php'; +require_once 'PHPUnit/Framework/Constraint/TraversableContains.php'; +require_once 'PHPUnit/Framework/Constraint/TraversableContainsOnly.php'; +require_once 'PHPUnit/Framework/Constraint/IsTrue.php'; +require_once 'PHPUnit/Framework/Constraint/Xor.php'; +?> diff --git a/tests/PHPUnit/Framework/Constraint/And.php b/tests/PHPUnit/Framework/Constraint/And.php new file mode 100755 index 00000000..6a0a7073 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/And.php @@ -0,0 +1,141 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Logical AND. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_Constraint_And extends PHPUnit_Framework_Constraint +{ + protected $constraints = array(); + + protected $lastConstraint = NULL; + + public function setConstraints(array $constraints) + { + $this->constraints = array(); + + foreach($constraints as $key => $constraint) { + if (!($constraint instanceof PHPUnit_Framework_Constraint)) { + throw new InvalidArgumentException('All parameters to ' . __CLASS__ . ' must be a constraint object.'); + } + + $this->constraints[] = $constraint; + } + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + $this->lastConstraint = NULL; + + foreach($this->constraints as $constraint) { + $this->lastConstraint = $constraint; + + if (!$constraint->evaluate($other)) { + return FALSE; + } + } + + return TRUE; + } + + /** + * @param mixed $other The value passed to evaluate() which failed the + * constraint check. + * @param string $description A string with extra description of what was + * going on while the evaluation failed. + * @param boolean $not Flag to indicate negation. + * @throws PHPUnit_Framework_ExpectationFailedException + */ + public function fail($other, $description, $not = FALSE) + { + $this->lastConstraint->fail($other, $description, $not); + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + $text = ''; + + foreach($this->constraints as $key => $constraint) { + if ($key > 0) { + $text .= ' and '; + } + + $text .= $constraint->toString(); + } + + return $text; + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/ArrayHasKey.php b/tests/PHPUnit/Framework/Constraint/ArrayHasKey.php new file mode 100755 index 00000000..49c68689 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/ArrayHasKey.php @@ -0,0 +1,112 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that asserts that the array it is evaluated for has a given key. + * + * Uses array_key_exists() to check if the key is found in the input array, if not + * found the evaluaton fails. + * + * The array key is passed in the constructor. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_Constraint_ArrayHasKey extends PHPUnit_Framework_Constraint +{ + protected $key; + + public function __construct($key) + { + $this->key = $key; + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + return array_key_exists($this->key, $other); + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + return 'has the key ' . PHPUnit_Util_Type::toString($this->key); + } + + protected function customFailureDescription($other, $description, $not) + { + return sprintf( + 'Failed asserting that an array %s.', + + $this->toString() + ); + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/Attribute.php b/tests/PHPUnit/Framework/Constraint/Attribute.php new file mode 100755 index 00000000..bfa6f9a9 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/Attribute.php @@ -0,0 +1,121 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.1.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.1.0 + */ + +class PHPUnit_Framework_Constraint_Attribute extends PHPUnit_Framework_Constraint +{ + protected $attributeName; + protected $constraint; + + public function __construct(PHPUnit_Framework_Constraint $constraint, $attributeName) + { + $this->attributeName = $attributeName; + $this->constraint = $constraint; + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + return $this->constraint->evaluate( + PHPUnit_Framework_Assert::readAttribute( + $other, $this->attributeName + ) + ); + } + + /** + * @param mixed $other The value passed to evaluate() which failed the + * constraint check. + * @param string $description A string with extra description of what was + * going on while the evaluation failed. + * @param boolean $not Flag to indicate negation. + * @throws PHPUnit_Framework_ExpectationFailedException + */ + public function fail($other, $description, $not = FALSE) + { + parent::fail( + PHPUnit_Framework_Assert::readAttribute( + $other, $this->attributeName + ), + $description, + $not + ); + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + return $this->constraint->toString(); + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/ClassHasAttribute.php b/tests/PHPUnit/Framework/Constraint/ClassHasAttribute.php new file mode 100755 index 00000000..d2117f63 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/ClassHasAttribute.php @@ -0,0 +1,112 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.1.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that asserts that the class it is evaluated for has a given + * attribute. + * + * The attribute name is passed in the constructor. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.1.0 + */ +class PHPUnit_Framework_Constraint_ClassHasAttribute extends PHPUnit_Framework_Constraint +{ + protected $attributeName; + + public function __construct($attributeName) + { + $this->attributeName = $attributeName; + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + $class = new ReflectionClass($other); + + return $class->hasProperty($this->attributeName); + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + return sprintf( + 'has attribute "%s"', + + $this->attributeName + ); + } + + protected function customFailureDescription($other, $description, $not) + { + return sprintf( + 'Failed asserting that class "%s" %s.', $other, $this->toString() + ); + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/ClassHasStaticAttribute.php b/tests/PHPUnit/Framework/Constraint/ClassHasStaticAttribute.php new file mode 100755 index 00000000..6f4a4513 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/ClassHasStaticAttribute.php @@ -0,0 +1,105 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.1.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that asserts that the class it is evaluated for has a given + * static attribute. + * + * The attribute name is passed in the constructor. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.1.0 + */ +class PHPUnit_Framework_Constraint_ClassHasStaticAttribute extends PHPUnit_Framework_Constraint_ClassHasAttribute +{ + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + $class = new ReflectionClass($other); + + if ($class->hasProperty($this->attributeName)) { + $attribute = $class->getProperty($this->attributeName); + + return $attribute->isStatic(); + } else { + return FALSE; + } + } + + /** + * Returns a string representation of the constraint. + * + * @return string + * @since Method available since Release 3.3.0 + */ + public function toString() + { + return sprintf( + 'has static attribute "%s"', + + $this->attributeName + ); + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/FileExists.php b/tests/PHPUnit/Framework/Constraint/FileExists.php new file mode 100755 index 00000000..10c3645f --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/FileExists.php @@ -0,0 +1,121 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that checks if the file(name) that it is evaluated for exists. + * + * The file path to check is passed as $other in evaluate(). + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_Constraint_FileExists extends PHPUnit_Framework_Constraint +{ + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + return file_exists($other); + } + + /** + * @param mixed $other The value passed to evaluate() which failed the + * constraint check. + * @param string $description A string with extra description of what was + * going on while the evaluation failed. + * @param boolean $not Flag to indicate negation. + * @throws PHPUnit_Framework_ExpectationFailedException + */ + public function fail($other, $description, $not = FALSE) + { + $failureDescription = sprintf( + 'Failed asserting that file "%s" exists.', + + $other + ); + + if ($not) { + $failureDescription = self::negate($failureDescription); + } + + if (!empty($description)) { + $failureDescription = $description . "\n" . $failureDescription; + } + + throw new PHPUnit_Framework_ExpectationFailedException( + $failureDescription + ); + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + return 'file exists'; + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/GreaterThan.php b/tests/PHPUnit/Framework/Constraint/GreaterThan.php new file mode 100755 index 00000000..3f7ff2fe --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/GreaterThan.php @@ -0,0 +1,99 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that asserts that the value it is evaluated for is greater + * than a given value. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_Constraint_GreaterThan extends PHPUnit_Framework_Constraint +{ + protected $value; + + public function __construct($value) + { + $this->value = $value; + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + return $this->value < $other; + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + return 'is greater than ' . PHPUnit_Util_Type::toString($this->value); + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/IsAnything.php b/tests/PHPUnit/Framework/Constraint/IsAnything.php new file mode 100755 index 00000000..ef771361 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/IsAnything.php @@ -0,0 +1,101 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that accepts any input value. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_Constraint_IsAnything extends PHPUnit_Framework_Constraint +{ + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + return TRUE; + } + + /** + * @param mixed $other The value passed to evaluate() which failed the + * constraint check. + * @param string $description A string with extra description of what was + * going on while the evaluation failed. + * @param boolean $not Flag to indicate negation. + */ + public function fail($other, $description, $not = FALSE) + { + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + return 'is anything'; + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/IsEqual.php b/tests/PHPUnit/Framework/Constraint/IsEqual.php new file mode 100755 index 00000000..117e2448 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/IsEqual.php @@ -0,0 +1,332 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Kore Nordmann + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that checks if one value is equal to another. + * + * Equality is checked with PHP's == operator, the operator is explained in detail + * at {@url http://www.php.net/manual/en/types.comparisons.php}. + * Two values are equal if they have the same value disregarding type. + * + * The expected value is passed in the constructor. + * + * @category Testing + * @package PHPUnit + * @author Kore Nordmann + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_Constraint_IsEqual extends PHPUnit_Framework_Constraint +{ + protected $value; + protected $delta = 0; + protected $maxDepth = 10; + protected $canonicalizeEol = FALSE; + + public function __construct($value, $delta = 0, $maxDepth = 10, $canonicalizeEol = FALSE) + { + $this->value = $value; + $this->delta = $delta; + $this->maxDepth = $maxDepth; + $this->canonicalizeEol = $canonicalizeEol; + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + return $this->recursiveComparison($this->value, $other); + } + + /** + * @param mixed $other The value passed to evaluate() which failed the + * constraint check. + * @param string $description A string with extra description of what was + * going on while the evaluation failed. + * @param boolean $not Flag to indicate negation. + * @throws PHPUnit_Framework_ExpectationFailedException + */ + public function fail($other, $description, $not = FALSE) + { + $failureDescription = $this->failureDescription( + $other, + $description, + $not + ); + + if (!$not) { + if ($this->value instanceof DOMDocument) { + $value = $this->domToText($this->value); + } else { + $value = $this->value; + } + + if ($other instanceof DOMDocument) { + $other = $this->domToText($other); + } + + throw new PHPUnit_Framework_ExpectationFailedException( + $failureDescription, + PHPUnit_Framework_ComparisonFailure::diffEqual($value, $other), + $description + ); + } else { + throw new PHPUnit_Framework_ExpectationFailedException( + $failureDescription, + NULL + ); + } + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + $delta = ''; + + if (is_string($this->value)) { + if (strpos($this->value, "\n") !== FALSE) { + return 'is equal to '; + } else { + return sprintf( + 'is equal to ', + + $this->value + ); + } + } else { + if ($this->delta != 0) { + $delta = sprintf( + ' with delta <%F>', + + $this->delta + ); + } + + return sprintf( + 'is equal to %s%s', + + PHPUnit_Util_Type::toString($this->value), + $delta + ); + } + } + + /** + * Perform the actual recursive comparision of two values + * + * @param mixed $a First value + * @param mixed $b Second value + * @param int $depth Depth + * @return bool + */ + protected function recursiveComparison($a, $b, $depth = 0) + { + if ($a === $b) { + return TRUE; + } + + if ($depth >= $this->maxDepth) { + return TRUE; + } + + if (is_numeric($a) XOR is_numeric($b)) { + return FALSE; + } + + if (is_array($a) XOR is_array($b)) { + return FALSE; + } + + if (is_object($a) XOR is_object($b)) { + return FALSE; + } + + if ($a instanceof SplObjectStorage XOR $b instanceof SplObjectStorage) { + return FALSE; + } + + if ($a instanceof SplObjectStorage) { + foreach ($a as $object) { + if (!$b->contains($object)) { + return FALSE; + } + } + + foreach ($b as $object) { + if (!$a->contains($object)) { + return FALSE; + } + } + + return TRUE; + } + + if ($a instanceof DOMDocument || $b instanceof DOMDocument) { + if (!$a instanceof DOMDocument) { + $_a = new DOMDocument; + $_a->preserveWhiteSpace = FALSE; + $_a->loadXML($a); + $a = $_a; + unset($_a); + } + + if (!$b instanceof DOMDocument) { + $_b = new DOMDocument; + $_b->preserveWhiteSpace = FALSE; + $_b->loadXML($b); + $b = $_b; + unset($_b); + } + + if (version_compare(PHP_VERSION, '5.2.0RC1', '>=')) { + return ($a->C14N() == $b->C14N()); + } else { + return ($a->saveXML() == $b->saveXML()); + } + } + + if (is_object($a) && is_object($b) && + (get_class($a) !== get_class($b))) { + return FALSE; + } + + // Normal comparision for scalar values. + if ((!is_array($a) && !is_object($a)) || + (!is_array($b) && !is_object($b))) { + if (is_numeric($a) && is_numeric($b)) { + // Optionally apply delta on numeric values. + return $this->numericComparison($a, $b); + } + + if ($this->canonicalizeEol && PHP_EOL != "\n" && + is_string($a) && is_string($b)) { + $a = str_replace(PHP_EOL, "\n", $a); + $b = str_replace(PHP_EOL, "\n", $b); + } + + return ($a == $b); + } + + if (is_object($a)) { + $a = (array)$a; + $b = (array)$b; + } + + foreach ($a as $key => $v) { + if (!array_key_exists($key, $b)) { + // Abort on missing key in $b. + return FALSE; + } + + if (!$this->recursiveComparison($a[$key], $b[$key], $depth + 1)) { + // FALSE, if child comparision fails. + return FALSE; + } + + // Unset key to check whether all keys of b are compared. + unset($b[$key]); + } + + if (count($b)) { + // There is something in $b, that is missing in $a. + return FALSE; + } + + return TRUE; + } + + /** + * Compares two numeric values - use delta if applicable. + * + * @param mixed $a + * @param mixed $b + * @return bool + */ + protected function numericComparison($a, $b) + { + if ($this->delta === FALSE) { + return ($a == $b); + } else { + return (abs($a - $b) <= $this->delta); + } + } + + /** + * Returns the normalized, whitespace-cleaned, and indented textual + * representation of a DOMDocument. + * + * @param DOMDocument $document + * @return string + */ + protected function domToText(DOMDocument $document) + { + $document->formatOutput = TRUE; + $document->normalizeDocument(); + + return $document->saveXML(); + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/IsFalse.php b/tests/PHPUnit/Framework/Constraint/IsFalse.php new file mode 100755 index 00000000..7229385c --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/IsFalse.php @@ -0,0 +1,88 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that accepts FALSE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class PHPUnit_Framework_Constraint_IsFalse extends PHPUnit_Framework_Constraint +{ + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + return $other === FALSE; + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + return 'is false'; + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/IsIdentical.php b/tests/PHPUnit/Framework/Constraint/IsIdentical.php new file mode 100755 index 00000000..03e320e0 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/IsIdentical.php @@ -0,0 +1,138 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that asserts that one value is identical to another. + * + * Identical check is performed with PHP's === operator, the operator is explained + * in detail at {@url http://www.php.net/manual/en/types.comparisons.php}. + * Two values are identical if they have the same value and are of the same type. + * + * The expected value is passed in the constructor. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_Constraint_IsIdentical extends PHPUnit_Framework_Constraint +{ + protected $value; + + public function __construct($value) + { + $this->value = $value; + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + return $this->value === $other; + } + + /** + * @param mixed $other The value passed to evaluate() which failed the + * constraint check. + * @param string $description A string with extra description of what was + * going on while the evaluation failed. + * @param boolean $not Flag to indicate negation. + * @throws PHPUnit_Framework_ExpectationFailedException + */ + public function fail($other, $description, $not = FALSE) + { + $failureDescription = $this->failureDescription( + $other, + $description, + $not + ); + + if (!$not) { + throw new PHPUnit_Framework_ExpectationFailedException( + $failureDescription, + PHPUnit_Framework_ComparisonFailure::diffIdentical($this->value, $other), + $description + ); + } else { + throw new PHPUnit_Framework_ExpectationFailedException( + $failureDescription, + NULL + ); + } + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + if (is_object($this->value)) { + return 'is identical to an object of class "' . get_class($this->value) . '"'; + } else { + return 'is identical to ' . PHPUnit_Util_Type::toString($this->value); + } + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/IsInstanceOf.php b/tests/PHPUnit/Framework/Constraint/IsInstanceOf.php new file mode 100755 index 00000000..0bfa73b6 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/IsInstanceOf.php @@ -0,0 +1,131 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that asserts that the object it is evaluated for is an instance + * of a given class. + * + * The expected class name is passed in the constructor. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_Constraint_IsInstanceOf extends PHPUnit_Framework_Constraint +{ + protected $className; + + public function __construct($className) + { + $this->className = $className; + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + return ($other instanceof $this->className); + } + + /** + * Creates the appropriate exception for the constraint which can be caught + * by the unit test system. This can be called if a call to evaluate() fails. + * + * @param mixed $other The value passed to evaluate() which failed the + * constraint check. + * @param string $description A string with extra description of what was + * going on while the evaluation failed. + * @param boolean $not Flag to indicate negation. + * @throws PHPUnit_Framework_ExpectationFailedException + */ + public function fail($other, $description, $not = FALSE) + { + throw new PHPUnit_Framework_ExpectationFailedException( + sprintf( + '%sFailed asserting that %s is %san instance of class "%s".', + + !empty($description) ? $description . "\n" : '', + PHPUnit_Util_Type::toString($other, TRUE), + $not ? 'not ' : '', + $this->className + ), + NULL + ); + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + return sprintf( + 'is instance of class "%s"', + + $this->className + ); + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/IsNull.php b/tests/PHPUnit/Framework/Constraint/IsNull.php new file mode 100755 index 00000000..881d0e74 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/IsNull.php @@ -0,0 +1,88 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that accepts NULL. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class PHPUnit_Framework_Constraint_IsNull extends PHPUnit_Framework_Constraint +{ + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + return $other === NULL; + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + return 'is null'; + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/IsTrue.php b/tests/PHPUnit/Framework/Constraint/IsTrue.php new file mode 100755 index 00000000..6dd84708 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/IsTrue.php @@ -0,0 +1,88 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that accepts TRUE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class PHPUnit_Framework_Constraint_IsTrue extends PHPUnit_Framework_Constraint +{ + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + return $other === TRUE; + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + return 'is true'; + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/IsType.php b/tests/PHPUnit/Framework/Constraint/IsType.php new file mode 100755 index 00000000..3959c66e --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/IsType.php @@ -0,0 +1,178 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that asserts that the value it is evaluated for is of a + * specified type. + * + * The expected value is passed in the constructor. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_Constraint_IsType extends PHPUnit_Framework_Constraint +{ + const TYPE_ARRAY = 'array'; + const TYPE_BOOL = 'bool'; + const TYPE_FLOAT = 'float'; + const TYPE_INT = 'int'; + const TYPE_NULL = 'null'; + const TYPE_NUMERIC = 'numeric'; + const TYPE_OBJECT = 'object'; + const TYPE_RESOURCE = 'resource'; + const TYPE_STRING = 'string'; + + protected $type; + + public function __construct($type) + { + switch ($type) { + case 'array': + case 'boolean': + case 'bool': + case 'float': + case 'integer': + case 'int': + case 'null': + case 'numeric': + case 'object': + case 'resource': + case 'string': { + break; + } + + default: { + throw new InvalidArgumentException( + sprintf( + 'Type specified for PHPUnit_Framework_Constraint_IsType <%s> is not a valid type.', + + $type + ) + ); + } + } + + $this->type = $type; + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + switch ($this->type) { + case 'numeric': { + return is_numeric($other); + } + + case 'integer': + case 'int': { + return is_integer($other); + } + + case 'float': { + return is_float($other); + } + + case 'string': { + return is_string($other); + } + + case 'boolean': + case 'bool': { + return is_bool($other); + } + + case 'null': { + return is_null($other); + } + + case 'array': { + return is_array($other); + } + + case 'object': { + return is_object($other); + } + + case 'resource': { + return is_resource($other); + } + } + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + return sprintf( + 'is of type "%s"', + + $this->type + ); + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/LessThan.php b/tests/PHPUnit/Framework/Constraint/LessThan.php new file mode 100755 index 00000000..9a41c004 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/LessThan.php @@ -0,0 +1,99 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that asserts that the value it is evaluated for is less than + * a given value. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_Constraint_LessThan extends PHPUnit_Framework_Constraint +{ + protected $value; + + public function __construct($value) + { + $this->value = $value; + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + return $this->value > $other; + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + return 'is less than ' . PHPUnit_Util_Type::toString($this->value); + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/Not.php b/tests/PHPUnit/Framework/Constraint/Not.php new file mode 100755 index 00000000..28b08a2d --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/Not.php @@ -0,0 +1,128 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Logical NOT. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ + +class PHPUnit_Framework_Constraint_Not extends PHPUnit_Framework_Constraint +{ + protected $constraint; + + public function __construct($constraint) + { + if (!($constraint instanceof PHPUnit_Framework_Constraint)) { + $constraint = new PHPUnit_Framework_Constraint_IsEqual($constraint); + } + + $this->constraint = $constraint; + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + return !$this->constraint->evaluate($other); + } + + /** + * @param mixed $other The value passed to evaluate() which failed the + * constraint check. + * @param string $description A string with extra description of what was + * going on while the evaluation failed. + * @param boolean $not Flag to indicate negation. + * @throws PHPUnit_Framework_ExpectationFailedException + */ + public function fail($other, $description, $not = FALSE) + { + $this->constraint->fail($other, $description, TRUE); + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + switch (get_class($this->constraint)) { + case 'PHPUnit_Framework_Constraint_And': + case 'PHPUnit_Framework_Constraint_Not': + case 'PHPUnit_Framework_Constraint_Or': { + return 'not( ' . $this->constraint->toString() . ' )'; + } + break; + + default: { + return PHPUnit_Framework_Constraint::negate( + $this->constraint->toString() + ); + } + } + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/ObjectHasAttribute.php b/tests/PHPUnit/Framework/Constraint/ObjectHasAttribute.php new file mode 100755 index 00000000..2c188d05 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/ObjectHasAttribute.php @@ -0,0 +1,91 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that asserts that the object it is evaluated for has a given + * attribute. + * + * The attribute name is passed in the constructor. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_Constraint_ObjectHasAttribute extends PHPUnit_Framework_Constraint_ClassHasAttribute +{ + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + $object = new ReflectionObject($other); + + return $object->hasProperty($this->attributeName); + } + + protected function customFailureDescription($other, $description, $not) + { + return sprintf( + 'Failed asserting that object of class "%s" %s.', get_class($other), $this->toString() + ); + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/Or.php b/tests/PHPUnit/Framework/Constraint/Or.php new file mode 100755 index 00000000..80205db6 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/Or.php @@ -0,0 +1,144 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Logical OR. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_Constraint_Or extends PHPUnit_Framework_Constraint +{ + protected $constraints = array(); + + public function setConstraints(array $constraints) + { + $this->constraints = array(); + + foreach($constraints as $key => $constraint) { + if (!($constraint instanceof PHPUnit_Framework_Constraint)) { + $constraint = new PHPUnit_Framework_Constraint_IsEqual($constraint); + } + + $this->constraints[] = $constraint; + } + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + foreach($this->constraints as $constraint) { + if ($constraint->evaluate($other)) { + return TRUE; + } + } + + return FALSE; + } + + /** + * @param mixed $other The value passed to evaluate() which failed the + * constraint check. + * @param string $description A string with extra description of what was + * going on while the evaluation failed. + * @param boolean $not Flag to indicate negation. + * @throws PHPUnit_Framework_ExpectationFailedException + */ + public function fail($other, $description, $not = FALSE) + { + throw new PHPUnit_Framework_ExpectationFailedException( + sprintf( + 'Failed asserting that %s %s.', + + PHPUnit_Util_Type::toString($other), + $this->toString() + ), + NULL, + $description + ); + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + $text = ''; + + foreach($this->constraints as $key => $constraint) { + if ($key > 0) { + $text .= ' or '; + } + + $text .= $constraint->toString(); + } + + return $text; + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/PCREMatch.php b/tests/PHPUnit/Framework/Constraint/PCREMatch.php new file mode 100755 index 00000000..c64f0e68 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/PCREMatch.php @@ -0,0 +1,108 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that asserts that the string it is evaluated for matches + * a regular expression. + * + * Checks a given value using the Perl Compatible Regular Expression extension + * in PHP. The pattern is matched by executing preg_match(). + * + * The pattern string passed in the constructor. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_Constraint_PCREMatch extends PHPUnit_Framework_Constraint +{ + protected $pattern; + + public function __construct($pattern) + { + $this->pattern = $pattern; + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + return preg_match($this->pattern, $other) > 0; + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + return sprintf( + 'matches PCRE pattern "%s"', + + $this->pattern + ); + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/StringContains.php b/tests/PHPUnit/Framework/Constraint/StringContains.php new file mode 100755 index 00000000..3e2fb6d8 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/StringContains.php @@ -0,0 +1,121 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that asserts that the string it is evaluated for contains + * a given string. + * + * Uses strpos() to find the position of the string in the input, if not found + * the evaluaton fails. + * + * The sub-string is passed in the constructor. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_Constraint_StringContains extends PHPUnit_Framework_Constraint +{ + protected $string; + + protected $case; + + public function __construct($string, $case = TRUE) + { + $this->string = $string; + $this->case = $case; + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + if ($this->case) { + return strpos($other, $this->string) !== FALSE; + } else { + return stripos($other, $this->string) !== FALSE; + } + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + if ($this->case) { + $string = $this->string; + } else { + $string = strtolower($this->string); + } + + return sprintf( + 'contains "%s"', + + $string + ); + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/TraversableContains.php b/tests/PHPUnit/Framework/Constraint/TraversableContains.php new file mode 100755 index 00000000..69f24ca2 --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/TraversableContains.php @@ -0,0 +1,121 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that asserts that the Traversable it is applied to contains + * a given value. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_Constraint_TraversableContains extends PHPUnit_Framework_Constraint +{ + protected $value; + + public function __construct($value) + { + $this->value = $value; + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + if ($other instanceof SplObjectStorage) { + return $other->contains($this->value); + } + + foreach ($other as $straw) { + if ($straw === $this->value) { + return TRUE; + } + } + + return FALSE; + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + if (is_string($this->value) && strpos($this->value, "\n") !== FALSE) { + return 'contains "' . $this->value . '"'; + } else { + return 'contains ' . PHPUnit_Util_Type::toString($this->value); + } + } + + protected function customFailureDescription($other, $description, $not) + { + return sprintf( + 'Failed asserting that an %s %s.', + + is_array($other) ? 'array' : 'iterator', + $this->toString() + ); + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/TraversableContainsOnly.php b/tests/PHPUnit/Framework/Constraint/TraversableContainsOnly.php new file mode 100755 index 00000000..3716f0db --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/TraversableContainsOnly.php @@ -0,0 +1,110 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.1.4 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Constraint that asserts that the Traversable it is applied to contains + * only values of a given type. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.1.4 + */ +class PHPUnit_Framework_Constraint_TraversableContainsOnly extends PHPUnit_Framework_Constraint +{ + protected $constraint; + protected $type; + + public function __construct($type, $isNativeType = TRUE) + { + if ($isNativeType) { + $this->constraint = new PHPUnit_Framework_Constraint_IsType($type); + } else { + $this->constraint = new PHPUnit_Framework_Constraint_IsInstanceOf($type); + } + + $this->type = $type; + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + foreach ($other as $item) { + if (!$this->constraint->evaluate($item)) { + return FALSE; + } + } + + return TRUE; + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + return 'contains only values of type "' . $this->type . '"'; + } +} +?> diff --git a/tests/PHPUnit/Framework/Constraint/Xor.php b/tests/PHPUnit/Framework/Constraint/Xor.php new file mode 100755 index 00000000..16689fff --- /dev/null +++ b/tests/PHPUnit/Framework/Constraint/Xor.php @@ -0,0 +1,149 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Type.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Logical XOR. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_Constraint_Xor extends PHPUnit_Framework_Constraint +{ + protected $constraints = array(); + + public function setConstraints(array $constraints) + { + $this->constraints = array(); + + foreach($constraints as $key => $constraint) { + if (!($constraint instanceof PHPUnit_Framework_Constraint)) { + $constraint = new PHPUnit_Framework_Constraint_IsEqual($constraint); + } + + $this->constraints[] = $constraint; + } + } + + /** + * Evaluates the constraint for parameter $other. Returns TRUE if the + * constraint is met, FALSE otherwise. + * + * @param mixed $other Value or object to evaluate. + * @return bool + */ + public function evaluate($other) + { + $result = FALSE; + + foreach($this->constraints as $constraint) { + if ($constraint->evaluate($other)) { + if ( $result ) + { + return FALSE; + } + + $result = TRUE; + } + } + + return $result; + } + + /** + * @param mixed $other The value passed to evaluate() which failed the + * constraint check. + * @param string $description A string with extra description of what was + * going on while the evaluation failed. + * @param boolean $not Flag to indicate negation. + * @throws PHPUnit_Framework_ExpectationFailedException + */ + public function fail($other, $description, $not = FALSE) + { + throw new PHPUnit_Framework_ExpectationFailedException( + sprintf( + 'Failed asserting that %s.', + + $this->toString(), + NULL, + $description + ) + ); + } + + /** + * Returns a string representation of the constraint. + * + * @return string + */ + public function toString() + { + $text = ''; + + foreach($this->constraints as $key => $constraint) { + if ($key > 0) { + $text .= ' xor '; + } + + $text .= $constraint->toString(); + } + + return $text; + } +} +?> diff --git a/tests/PHPUnit/Framework/Error.php b/tests/PHPUnit/Framework/Error.php new file mode 100755 index 00000000..44c83d3b --- /dev/null +++ b/tests/PHPUnit/Framework/Error.php @@ -0,0 +1,87 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.2.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!class_exists('PHPUnit_Framework_Error', FALSE)) { + +/** + * Wrapper for PHP errors. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.2.0 + */ +class PHPUnit_Framework_Error extends Exception +{ + /** + * Constructor. + * + * @param string $message + * @param integer $code + * @param string $file + * @param integer $line + * @param array $trace + */ + public function __construct($message, $code, $file, $line, $trace) + { + parent::__construct($message, $code); + + $this->file = $file; + $this->line = $line; + $this->trace = $trace; + } +} + +} +?> diff --git a/tests/PHPUnit/Framework/Error/Notice.php b/tests/PHPUnit/Framework/Error/Notice.php new file mode 100755 index 00000000..7091cff1 --- /dev/null +++ b/tests/PHPUnit/Framework/Error/Notice.php @@ -0,0 +1,76 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!class_exists('PHPUnit_Framework_Error_Notice', FALSE)) { + +/** + * Wrapper for PHP notices. + * You can disable notice-to-exception conversion by setting + * + * + * PHPUnit_Framework_Error_Notice::$enabled = FALSE; + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class PHPUnit_Framework_Error_Notice extends PHPUnit_Framework_Error +{ + public static $enabled = TRUE; +} + +} +?> diff --git a/tests/PHPUnit/Framework/Error/Warning.php b/tests/PHPUnit/Framework/Error/Warning.php new file mode 100755 index 00000000..096d4a95 --- /dev/null +++ b/tests/PHPUnit/Framework/Error/Warning.php @@ -0,0 +1,76 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!class_exists('PHPUnit_Framework_Error_Warning', FALSE)) { + +/** + * Wrapper for PHP warnings. + * You can disable notice-to-exception conversion by setting + * + * + * PHPUnit_Framework_Error_Warning::$enabled = FALSE; + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class PHPUnit_Framework_Error_Warning extends PHPUnit_Framework_Error +{ + public static $enabled = TRUE; +} + +} +?> diff --git a/tests/PHPUnit/Framework/ExpectationFailedException.php b/tests/PHPUnit/Framework/ExpectationFailedException.php new file mode 100755 index 00000000..dfdbb308 --- /dev/null +++ b/tests/PHPUnit/Framework/ExpectationFailedException.php @@ -0,0 +1,106 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!class_exists('PHPUnit_Framework_ExpectationFailedException', FALSE)) { + +/** + * Exception for expectations which failed their check. + * + * The exception contains the error message and optionally a + * PHPUnit_Framework_ComparisonFailure which is used to + * generate diff output of the failed expectations. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_ExpectationFailedException extends PHPUnit_Framework_AssertionFailedError +{ + protected $comparisonFailure; + protected $description; + protected $customMessage; + + public function __construct($description, PHPUnit_Framework_ComparisonFailure $comparisonFailure = NULL, $message = '') + { + $this->description = $description; + $this->comparisonFailure = $comparisonFailure; + $this->customMessage = $message; + + if (!empty($message)) { + $description .= "\n" . $message; + } + + parent::__construct($description); + } + + public function getComparisonFailure() + { + return $this->comparisonFailure; + } + + public function getDescription() + { + return $this->description; + } + + public function getCustomMessage() + { + return $this->customMessage; + } +} + +} +?> diff --git a/tests/PHPUnit/Framework/IncompleteTest.php b/tests/PHPUnit/Framework/IncompleteTest.php new file mode 100755 index 00000000..bc3c6a47 --- /dev/null +++ b/tests/PHPUnit/Framework/IncompleteTest.php @@ -0,0 +1,71 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!interface_exists('PHPUnit_Framework_IncompleteTest', FALSE)) { + +/** + * A marker interface for marking any exception/error as result of an unit + * test as incomplete implementation or currently not implemented. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 2.0.0 + */ +interface PHPUnit_Framework_IncompleteTest +{ +} + +} +?> diff --git a/tests/PHPUnit/Framework/IncompleteTestError.php b/tests/PHPUnit/Framework/IncompleteTestError.php new file mode 100755 index 00000000..96f9acec --- /dev/null +++ b/tests/PHPUnit/Framework/IncompleteTestError.php @@ -0,0 +1,72 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!class_exists('PHPUnit_Framework_IncompleteTestError', FALSE)) { + +/** + * Extension to PHPUnit_Framework_AssertionFailedError to mark the special + * case of an incomplete test. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class PHPUnit_Framework_IncompleteTestError extends PHPUnit_Framework_AssertionFailedError implements PHPUnit_Framework_IncompleteTest +{ +} + +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Builder/Identity.php b/tests/PHPUnit/Framework/MockObject/Builder/Identity.php new file mode 100755 index 00000000..7560fe4d --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Builder/Identity.php @@ -0,0 +1,80 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Builder interface for unique identifiers. + * + * Defines the interface for recording unique identifiers. The identifiers + * can be used to define the invocation order of expectations. The expectation + * is recorded using id() and then defined in order using + * PHPUnit_Framework_MockObject_Builder_Match::after(). + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 3.0.0 + */ +interface PHPUnit_Framework_MockObject_Builder_Identity +{ + /** + * Sets the identification of the expectation to $id. + * + * @note The identifier is unique per mock object. + * @param string $id Unique identifiation of expectation. + */ + public function id($id); +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Builder/InvocationMocker.php b/tests/PHPUnit/Framework/MockObject/Builder/InvocationMocker.php new file mode 100755 index 00000000..eca9a084 --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Builder/InvocationMocker.php @@ -0,0 +1,156 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Builder/MethodNameMatch.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher.php'; +require_once 'PHPUnit/Framework/MockObject/Stub.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Builder for mocked or stubbed invocations. + * + * Provides methods for building expectations without having to resort to + * instantiating the various matchers manually. These methods also form a + * more natural way of reading the expectation. This class should be together + * with the test case PHPUnit_Framework_MockObject_TestCase. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_MockObject_Builder_InvocationMocker implements PHPUnit_Framework_MockObject_Builder_MethodNameMatch +{ + protected $collection; + + protected $matcher; + + public function __construct(PHPUnit_Framework_MockObject_Stub_MatcherCollection $collection, PHPUnit_Framework_MockObject_Matcher_Invocation $invocationMatcher) + { + $this->collection = $collection; + $this->matcher = new PHPUnit_Framework_MockObject_Matcher($invocationMatcher); + + $this->collection->addMatcher($this->matcher); + } + + public function getMatcher() + { + return $this->matcher; + } + + public function id($id) + { + $this->collection->registerId($id, $this); + + return $this; + } + + public function will(PHPUnit_Framework_MockObject_Stub $stub) + { + $this->matcher->stub = $stub; + + return $this; + } + + public function after($id) + { + $this->matcher->afterMatchBuilderId = $id; + + return $this; + } + + public function with() + { + $args = func_get_args(); + + if ($this->matcher->methodNameMatcher === NULL) { + throw new RuntimeException('Method name matcher is not defined, cannot define parameter matcher without one'); + } + + if ( $this->matcher->parametersMatcher !== NULL) { + throw new RuntimeException('Parameter matcher is already defined, cannot redefine'); + } + + $this->matcher->parametersMatcher = new PHPUnit_Framework_MockObject_Matcher_Parameters($args); + + return $this; + } + + public function withAnyParameters() + { + if ($this->matcher->methodNameMatcher === NULL) { + throw new RuntimeException('Method name matcher is not defined, cannot define parameter matcher without one'); + } + + if ($this->matcher->parametersMatcher !== NULL) { + throw new RuntimeException('Parameter matcher is already defined, cannot redefine'); + } + + $this->matcher->parametersMatcher = new PHPUnit_Framework_MockObject_Matcher_AnyParameters(); + + return $this; + } + + public function method($constraint) + { + if ($this->matcher->methodNameMatcher !== NULL) { + throw new RuntimeException('Method name matcher is already defined, cannot redefine'); + } + + $this->matcher->methodNameMatcher = new PHPUnit_Framework_MockObject_Matcher_MethodName($constraint); + + return $this; + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Builder/Match.php b/tests/PHPUnit/Framework/MockObject/Builder/Match.php new file mode 100755 index 00000000..ed1278ef --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Builder/Match.php @@ -0,0 +1,77 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Builder/Stub.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Builder interface for invocation order matches. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 3.0.0 + */ +interface PHPUnit_Framework_MockObject_Builder_Match extends PHPUnit_Framework_MockObject_Builder_Stub +{ + /** + * Defines the expectation which must occur before the current is valid. + * + * @param string $id The identification of the expectation that should + * occur before this one. + * @return PHPUnit_Framework_MockObject_Builder_Stub + */ + public function after($id); +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Builder/MethodNameMatch.php b/tests/PHPUnit/Framework/MockObject/Builder/MethodNameMatch.php new file mode 100755 index 00000000..61a66c59 --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Builder/MethodNameMatch.php @@ -0,0 +1,79 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Builder/ParametersMatch.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Builder interface for matcher of method names. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 3.0.0 + */ +interface PHPUnit_Framework_MockObject_Builder_MethodNameMatch extends PHPUnit_Framework_MockObject_Builder_ParametersMatch +{ + /** + * Adds a new method name match and returns the parameter match object for + * further matching possibilities. + * + * @param PHPUnit_Framework_Constraint $name Constraint for matching method, if a + * string is passed it will use the + * PHPUnit_Framework_Constraint_IsEqual. + * @return PHPUnit_Framework_MockObject_Builder_ParametersMatch + */ + public function method($name); +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Builder/Namespace.php b/tests/PHPUnit/Framework/MockObject/Builder/Namespace.php new file mode 100755 index 00000000..99673bb2 --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Builder/Namespace.php @@ -0,0 +1,88 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Builder/Match.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Interface for builders which can register builders with a given identification. + * + * This interface relates to PHPUnit_Framework_MockObject_Builder_Identity. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 3.0.0 + */ +interface PHPUnit_Framework_MockObject_Builder_Namespace +{ + /** + * Looks up the match builder with identification $id and returns it. + * + * @param string $id The identifiction of the match builder. + * @return PHPUnit_Framework_MockObject_Builder_Match + */ + public function lookupId($id); + + /** + * Registers the match builder $builder with the identification $id. The + * builder can later be looked up using lookupId() to figure out if it + * has been invoked. + * + * @param string $id The identification of the match builder. + * @param PHPUnit_Framework_MockObject_Builder_Match $builder The builder which is being registered. + */ + public function registerId($id, PHPUnit_Framework_MockObject_Builder_Match $builder); +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Builder/ParametersMatch.php b/tests/PHPUnit/Framework/MockObject/Builder/ParametersMatch.php new file mode 100755 index 00000000..9f2ffa84 --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Builder/ParametersMatch.php @@ -0,0 +1,100 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Builder/Match.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Builder interface for parameter matchers. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 3.0.0 + */ +interface PHPUnit_Framework_MockObject_Builder_ParametersMatch extends PHPUnit_Framework_MockObject_Builder_Match +{ + /** + * Sets the parameters to match for, each parameter to this funtion will + * be part of match. To perform specific matches or constraints create a + * new PHPUnit_Framework_Constraint and use it for the parameter. + * If the parameter value is not a constraint it will use the + * PHPUnit_Framework_Constraint_IsEqual for the value. + * + * Some examples: + * + * // match first parameter with value 2 + * $b->with(2); + * // match first parameter with value 'smock' and second identical to 42 + * $b->with('smock', new PHPUnit_Framework_Constraint_IsEqual(42)); + * + * + * @return PHPUnit_Framework_MockObject_Builder_ParametersMatch + */ + public function with(); + + /** + * Sets a matcher which allows any kind of parameters. + * + * Some examples: + * + * // match any number of parameters + * $b->withAnyParamers(); + * + * + * @return PHPUnit_Framework_MockObject_Matcher_AnyParameters + */ + public function withAnyParameters(); +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Builder/Stub.php b/tests/PHPUnit/Framework/MockObject/Builder/Stub.php new file mode 100755 index 00000000..59e7b57f --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Builder/Stub.php @@ -0,0 +1,77 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Builder/Identity.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Builder interface for stubs which are actions replacing an invocation. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 3.0.0 + */ +interface PHPUnit_Framework_MockObject_Builder_Stub extends PHPUnit_Framework_MockObject_Builder_Identity +{ + /** + * Stubs the matching method with the stub object $stub. Any invocations of + * the matched method will now be handled by the stub instead. + * + * @param PHPUnit_Framework_MockObject_Stub $stub The stub object. + * @return PHPUnit_Framework_MockObject_Builder_Identity + */ + public function will(PHPUnit_Framework_MockObject_Stub $stub); +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Invocation.php b/tests/PHPUnit/Framework/MockObject/Invocation.php new file mode 100755 index 00000000..f3daf41b --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Invocation.php @@ -0,0 +1,138 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Encapsulates information on a method invocation which can be passed to matchers. + * + * The invocation consists of the object it occured from, the class name, the + * method name and all the parameters. The mock object must instantiate this + * class with the values from the mocked method and pass it to an object of + * PHPUnit_Framework_MockObject_Invokable. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_MockObject_Invocation implements PHPUnit_Framework_SelfDescribing +{ + public $object; + + public $className; + + public $methodName; + + public $parameters; + + public function __construct($object, $className, $methodName, $parameters) + { + $this->object = $object; + $this->className = $className; + $this->methodName = $methodName; + $this->parameters = $parameters; + + foreach ($this->parameters as $key => $value) { + if (is_object($value)) { + $this->parameters[$key] = $this->cloneObject($value); + } + } + } + + public function toString() + { + return sprintf( + "%s::%s(%s)", + + $this->className, + $this->methodName, + join( + ', ', + array_map( + create_function( + '$a', + 'return PHPUnit_Util_Type::shortenedExport($a);' + ), + $this->parameters + ) + ) + ); + } + + protected function cloneObject($original) + { + $object = new ReflectionObject($original); + + if ($object->hasMethod('__clone')) { + $method = $object->getMethod('__clone'); + + if (!$method->isPublic()) { + return $original; + } + + try { + return clone $original; + } + + catch (Exception $e) { + return $original; + } + } + + return clone $original; + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/InvocationMocker.php b/tests/PHPUnit/Framework/MockObject/InvocationMocker.php new file mode 100755 index 00000000..9c5d5ab4 --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/InvocationMocker.php @@ -0,0 +1,165 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Builder/InvocationMocker.php'; +require_once 'PHPUnit/Framework/MockObject/Builder/Match.php'; +require_once 'PHPUnit/Framework/MockObject/Builder/Namespace.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher.php'; +require_once 'PHPUnit/Framework/MockObject/Stub.php'; +require_once 'PHPUnit/Framework/MockObject/Invocation.php'; +require_once 'PHPUnit/Framework/MockObject/Invokable.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Mocker for invocations which are sent from + * PHPUnit_Framework_MockObject_MockObject objects. + * + * Keeps track of all expectations and stubs as well as registering + * identifications for builders. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_MockObject_InvocationMocker implements PHPUnit_Framework_MockObject_Stub_MatcherCollection, PHPUnit_Framework_MockObject_Invokable, PHPUnit_Framework_MockObject_Builder_Namespace +{ + protected $matchers = array(); + + protected $builderMap = array(); + + public function addMatcher(PHPUnit_Framework_MockObject_Matcher_Invocation $matcher) + { + $this->matchers[] = $matcher; + } + + public function lookupId($id) + { + if (isset($this->builderMap[$id])) { + return $this->builderMap[$id]; + } + + return NULL; + } + + public function registerId($id, PHPUnit_Framework_MockObject_Builder_Match $builder) + { + if (isset($this->builderMap[$id])) { + throw new RuntimeException("Match builder with id <{$id}> is already registered."); + } + + $this->builderMap[$id] = $builder; + } + + public function expects(PHPUnit_Framework_MockObject_Matcher_Invocation $matcher) + { + $builder = new PHPUnit_Framework_MockObject_Builder_InvocationMocker($this, $matcher); + + return $builder; + } + + public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation) + { + $exception = NULL; + $hasReturnValue = FALSE; + + if (strtolower($invocation->methodName) == '__tostring') { + $returnValue = ''; + } else { + $returnValue = NULL; + } + + foreach ($this->matchers as $match) { + try { + if ($match->matches($invocation)) { + $value = $match->invoked($invocation); + + if (!$hasReturnValue) { + $returnValue = $value; + $hasReturnValue = TRUE; + } + } + } + + catch (Exception $e) { + $exception = $e; + } + } + + if ($exception !== NULL) { + throw $exception; + } + + return $returnValue; + } + + public function matches(PHPUnit_Framework_MockObject_Invocation $invocation) + { + foreach($this->matchers as $matcher) { + if (!$matcher->matches($invocation)) { + return FALSE; + } + } + + return TRUE; + } + + public function verify() + { + foreach($this->matchers as $matcher) { + $matcher->verify(); + } + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Invokable.php b/tests/PHPUnit/Framework/MockObject/Invokable.php new file mode 100755 index 00000000..22f7b9de --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Invokable.php @@ -0,0 +1,91 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Invocation.php'; +require_once 'PHPUnit/Framework/MockObject/Verifiable.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Interface for classes which can be invoked. + * + * The invocation will be taken from a mock object and passed to an object + * of this class. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 3.0.0 + */ +interface PHPUnit_Framework_MockObject_Invokable extends PHPUnit_Framework_MockObject_Verifiable +{ + /** + * Invokes the invocation object $invocation so that it can be checked for + * expectations or matched against stubs. + * + * @return Object + * @param PHPUnit_Framework_MockObject_Invocation $invocation The invocation object passed from + * mock object. + */ + public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation); + + /** + * Checks if the invocation matches. + * + * @return bool + * @param PHPUnit_Framework_MockObject_Invocation $invocation The invocation object passed from + * mock object. + */ + public function matches(PHPUnit_Framework_MockObject_Invocation $invocation); +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Matcher.php b/tests/PHPUnit/Framework/MockObject/Matcher.php new file mode 100755 index 00000000..b7accdbb --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Matcher.php @@ -0,0 +1,280 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/Invocation.php'; +require_once 'PHPUnit/Framework/MockObject/Invocation.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Main matcher which defines a full expectation using method, parameter and invocation matchers. + * + * This matcher encapsulates all the other matchers and allows the builder to set + * the specific matchers when the appropriate methods are called (once(), where() + * etc.). + * + * All properties are public so that they can easily be accessed by the builder. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_MockObject_Matcher implements PHPUnit_Framework_MockObject_Matcher_Invocation +{ + public $invocationMatcher; + + public $afterMatchBuilderId = NULL; + + public $afterMatchBuilderIsInvoked = FALSE; + + public $methodNameMatcher = NULL; + + public $parametersMatcher = NULL; + + public $stub = NULL; + + public function __construct(PHPUnit_Framework_MockObject_Matcher_Invocation $invocationMatcher) + { + $this->invocationMatcher = $invocationMatcher; + } + + public function toString() + { + $list = array(); + + if ($this->invocationMatcher !== NULL) { + $list[] = $this->invocationMatcher->toString(); + } + + if ($this->methodNameMatcher !== NULL) { + $list[] = 'where ' . $this->methodNameMatcher->toString(); + } + + if ($this->parametersMatcher !== NULL) { + $list[] = 'and ' . $this->parametersMatcher->toString(); + } + + if ($this->afterMatchBuilderId !== NULL) { + $list[] = 'after ' . $this->afterMatchBuilderId; + } + + if ($this->stub !== NULL) { + $list[] = 'will ' . $this->stub->toString(); + } + + return join(' ', $list); + } + + public function invoked(PHPUnit_Framework_MockObject_Invocation $invocation) + { + if ($this->invocationMatcher === NULL) { + throw new RuntimeException('No invocation matcher is set'); + } + + if ($this->methodNameMatcher === NULL) { + throw new RuntimeException('No method matcher is set'); + } + + if ($this->afterMatchBuilderId !== NULL) { + $builder = $invocation->object->__phpunit_getInvocationMocker()->lookupId($this->afterMatchBuilderId); + + if (!$builder) { + throw new RuntimeException( + sprintf( + 'No builder found for match builder identification <%s>', + + $this->afterMatchBuilderId + ) + ); + } + + $matcher = $builder->getMatcher(); + + if ($matcher && $matcher->invocationMatcher->hasBeenInvoked()) { + $this->afterMatchBuilderIsInvoked = TRUE; + } + } + + $this->invocationMatcher->invoked($invocation); + + try { + if ( $this->parametersMatcher !== NULL && + !$this->parametersMatcher->matches($invocation)) { + $this->parametersMatcher->verify(); + } + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + throw new PHPUnit_Framework_ExpectationFailedException( + sprintf( + "Expectation failed for %s when %s\n%s", + + $this->methodNameMatcher->toString(), + $this->invocationMatcher->toString(), + $e->getDescription() + ), + $e->getComparisonFailure() + ); + } + + if ($this->stub) { + return $this->stub->invoke($invocation); + } + + return NULL; + } + + public function matches(PHPUnit_Framework_MockObject_Invocation $invocation) + { + if ($this->afterMatchBuilderId !== NULL) { + $builder = $invocation->object->__phpunit_getInvocationMocker()->lookupId($this->afterMatchBuilderId); + + if (!$builder) { + throw new RuntimeException( + sprintf( + 'No builder found for match builder identification <%s>', + + $this->afterMatchBuilderId + ) + ); + } + + $matcher = $builder->getMatcher(); + + if (!$matcher) { + return FALSE; + } + + if (!$matcher->invocationMatcher->hasBeenInvoked()) { + return FALSE; + } + } + + if ($this->invocationMatcher === NULL) { + throw new RuntimeException('No invocation matcher is set'); + } + + if ($this->methodNameMatcher === NULL) { + throw new RuntimeException('No method matcher is set'); + } + + if (!$this->invocationMatcher->matches($invocation)) { + return FALSE; + } + + try { + if (!$this->methodNameMatcher->matches($invocation)) { + return FALSE; + } + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + throw new PHPUnit_Framework_ExpectationFailedException( + sprintf( + "Expectation failed for %s when %s\n%s", + + $this->methodNameMatcher->toString(), + $this->invocationMatcher->toString(), + $e->getDescription() + ), + $e->getComparisonFailure() + ); + } + + return TRUE; + } + + public function verify() + { + if ($this->invocationMatcher === NULL) { + throw new RuntimeException('No invocation matcher is set'); + } + + if ($this->methodNameMatcher === NULL) { + throw new RuntimeException('No method matcher is set'); + } + + try { + $this->invocationMatcher->verify(); + + if ($this->parametersMatcher !== NULL) { + $this->parametersMatcher->verify(); + } + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + throw new PHPUnit_Framework_ExpectationFailedException( + sprintf( + "Expectation failed for %s when %s.\n%s", + + $this->methodNameMatcher->toString(), + $this->invocationMatcher->toString(), + $e->getDescription() + ) + ); + } + } +} + +require_once 'PHPUnit/Framework/MockObject/Matcher/AnyInvokedCount.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/AnyParameters.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/InvokedAtIndex.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/InvokedAtLeastOnce.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/InvokedCount.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/InvokedRecorder.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/MethodName.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/Parameters.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/StatelessInvocation.php'; +?> diff --git a/tests/PHPUnit/Framework/MockObject/Matcher/AnyInvokedCount.php b/tests/PHPUnit/Framework/MockObject/Matcher/AnyInvokedCount.php new file mode 100755 index 00000000..eab8106a --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Matcher/AnyInvokedCount.php @@ -0,0 +1,79 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/InvokedRecorder.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Invocation matcher which checks if a method has been invoked zero or more + * times. This matcher will always match. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount extends PHPUnit_Framework_MockObject_Matcher_InvokedRecorder +{ + public function toString() + { + return 'invoked zero or more times'; + } + + public function verify() + { + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Matcher/AnyParameters.php b/tests/PHPUnit/Framework/MockObject/Matcher/AnyParameters.php new file mode 100755 index 00000000..288a0910 --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Matcher/AnyParameters.php @@ -0,0 +1,79 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/StatelessInvocation.php'; +require_once 'PHPUnit/Framework/MockObject/Invocation.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Invocation matcher which allos any parameters to a method. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_MockObject_Matcher_AnyParameters extends PHPUnit_Framework_MockObject_Matcher_StatelessInvocation +{ + public function toString() + { + return 'with any parameters'; + } + + public function matches(PHPUnit_Framework_MockObject_Invocation $invocation) + { + return TRUE; + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Matcher/Invocation.php b/tests/PHPUnit/Framework/MockObject/Matcher/Invocation.php new file mode 100755 index 00000000..7a0cac82 --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Matcher/Invocation.php @@ -0,0 +1,99 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Invocation.php'; +require_once 'PHPUnit/Framework/MockObject/Verifiable.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Interface for classes which matches an invocation based on its + * method name, argument, order or call count. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 3.0.0 + */ +interface PHPUnit_Framework_MockObject_Matcher_Invocation extends PHPUnit_Framework_SelfDescribing, PHPUnit_Framework_MockObject_Verifiable +{ + /** + * Registers the invocation $invocation in the object as being invoked. + * This will only occur after matches() returns true which means the + * current invocation is the correct one. + * + * The matcher can store information from the invocation which can later + * be checked in verify(), or it can check the values directly and throw + * and exception if an expectation is not met. + * + * If the matcher is a stub it will also have a return value. + * + * @param PHPUnit_Framework_MockObject_Invocation Object containing information on a mocked or + * stubbed method which was invoked. + * @return mixed + */ + public function invoked(PHPUnit_Framework_MockObject_Invocation $invocation); + + /** + * Checks if the invocation $invocation matches the current rules. If it does + * the matcher will get the invoked() method called which should check if an + * expectation is met. + * + * @param PHPUnit_Framework_MockObject_Invocation Object containing information on a mocked or + * stubbed method which was invoked. + * @return bool + */ + public function matches(PHPUnit_Framework_MockObject_Invocation $invocation); +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Matcher/InvokedAtIndex.php b/tests/PHPUnit/Framework/MockObject/Matcher/InvokedAtIndex.php new file mode 100755 index 00000000..0ebdb63d --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Matcher/InvokedAtIndex.php @@ -0,0 +1,115 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/Invocation.php'; +require_once 'PHPUnit/Framework/MockObject/Invocation.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Invocation matcher which checks if a method was invoked at a certain index. + * + * If the expected index number does not match the current invocation index it + * will not match which means it skips all method and parameter matching. Only + * once the index is reached will the method and parameter start matching and + * verifying. + * + * If the index is never reached it will throw an exception in index. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_MockObject_Matcher_InvokedAtIndex implements PHPUnit_Framework_MockObject_Matcher_Invocation +{ + protected $sequenceIndex; + + protected $currentIndex = -1; + + public function __construct($sequenceIndex) + { + $this->sequenceIndex = $sequenceIndex; + } + + public function toString() + { + return 'invoked at sequence index ' . $this->sequenceIndex; + } + + public function matches(PHPUnit_Framework_MockObject_Invocation $invocation) + { + $this->currentIndex++; + + return $this->currentIndex == $this->sequenceIndex; + } + + public function invoked(PHPUnit_Framework_MockObject_Invocation $invocation) + { + } + + public function verify() + { + if ($this->currentIndex < $this->sequenceIndex) { + throw new PHPUnit_Framework_ExpectationFailedException( + sprintf( + 'The expected invocation at index %s was never reached.', + + $this->sequenceIndex + ) + ); + } + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Matcher/InvokedAtLeastOnce.php b/tests/PHPUnit/Framework/MockObject/Matcher/InvokedAtLeastOnce.php new file mode 100755 index 00000000..b5f5cbfc --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Matcher/InvokedAtLeastOnce.php @@ -0,0 +1,87 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/InvokedRecorder.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Invocation matcher which checks if a method has been invoked at least one time. + * + * If the number of invocations is 0 it will throw an exception in verify. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_MockObject_Matcher_InvokedAtLeastOnce extends PHPUnit_Framework_MockObject_Matcher_InvokedRecorder +{ + public function toString() + { + return 'invoked at least once'; + } + + public function verify() + { + $count = $this->getInvocationCount(); + + if ($count < 1) { + throw new PHPUnit_Framework_ExpectationFailedException( + 'Expected invocation at least once but it never occured.' + ); + } + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Matcher/InvokedCount.php b/tests/PHPUnit/Framework/MockObject/Matcher/InvokedCount.php new file mode 100755 index 00000000..a0e3f219 --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Matcher/InvokedCount.php @@ -0,0 +1,134 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/InvokedRecorder.php'; +require_once 'PHPUnit/Framework/MockObject/Invocation.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Invocation matcher which checks if a method has been invoked a certain amount of times. + * + * If the number of invocations exceeds the value it will immediately throw an exception, + * If the number is less it will later be checked in verify() and also throw an exception. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_MockObject_Matcher_InvokedCount extends PHPUnit_Framework_MockObject_Matcher_InvokedRecorder +{ + protected $expectedCount; + + public function __construct($expectedCount) + { + $this->expectedCount = $expectedCount; + } + + public function toString() + { + return 'invoked ' . $this->expectedCount . ' time(s)'; + } + + public function invoked(PHPUnit_Framework_MockObject_Invocation $invocation) + { + parent::invoked($invocation); + + $count = $this->getInvocationCount(); + + if ($count > $this->expectedCount) { + $message = $invocation->toString(); + + switch ($this->expectedCount) { + case 0: { + $message .= ' was not expected to be called.'; + } + break; + + case 1: { + $message .= ' was not expected to be called more than once.'; + } + break; + + default: { + $message .= sprintf( + ' was not expected to be called more than %d times.', + + $this->expectedCount + ); + } + } + + throw new PHPUnit_Framework_ExpectationFailedException($message); + } + } + + public function verify() + { + $count = $this->getInvocationCount(); + + if ($count !== $this->expectedCount) { + throw new PHPUnit_Framework_ExpectationFailedException( + sprintf( + 'Method was expected to be called %d times, actually called %d times.', + + $this->expectedCount, + $count + ) + ); + } + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Matcher/InvokedRecorder.php b/tests/PHPUnit/Framework/MockObject/Matcher/InvokedRecorder.php new file mode 100755 index 00000000..93df0292 --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Matcher/InvokedRecorder.php @@ -0,0 +1,100 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/Invocation.php'; +require_once 'PHPUnit/Framework/MockObject/Invocation.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Records invocations and provides convenience methods for checking them later on. + * + * This abstract class can be implemented by matchers which needs to check the + * number of times an invocation has occured. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + * @abstract + */ +abstract class PHPUnit_Framework_MockObject_Matcher_InvokedRecorder implements PHPUnit_Framework_MockObject_Matcher_Invocation +{ + protected $invocations = array(); + + public function getInvocationCount() + { + return count($this->invocations); + } + + public function getInvocations() + { + return $this->invocations; + } + + public function hasBeenInvoked() + { + return count($this->invocations) > 0; + } + + public function invoked(PHPUnit_Framework_MockObject_Invocation $invocation) + { + $this->invocations[] = $invocation; + } + + public function matches(PHPUnit_Framework_MockObject_Invocation $invocation) + { + return TRUE; + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Matcher/MethodName.php b/tests/PHPUnit/Framework/MockObject/Matcher/MethodName.php new file mode 100755 index 00000000..5d91747f --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Matcher/MethodName.php @@ -0,0 +1,95 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/StatelessInvocation.php'; +require_once 'PHPUnit/Framework/MockObject/Invocation.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Invocation matcher which looks for a specific method name in the invocations. + * + * Checks the method name all incoming invocations, the name is checked against + * the defined constraint $constraint. If the constraint is met it will return + * true in matches(). + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_MockObject_Matcher_MethodName extends PHPUnit_Framework_MockObject_Matcher_StatelessInvocation +{ + protected $constraint; + + public function __construct($constraint) + { + if (!($constraint instanceof PHPUnit_Framework_Constraint)) { + $constraint = new PHPUnit_Framework_Constraint_IsEqual($constraint); + } + + $this->constraint = $constraint; + } + + public function toString() + { + return 'method name ' . $this->constraint->toString(); + } + + public function matches(PHPUnit_Framework_MockObject_Invocation $invocation) + { + return $this->constraint->evaluate($invocation->methodName); + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Matcher/Parameters.php b/tests/PHPUnit/Framework/MockObject/Matcher/Parameters.php new file mode 100755 index 00000000..92dcd00a --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Matcher/Parameters.php @@ -0,0 +1,145 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/StatelessInvocation.php'; +require_once 'PHPUnit/Framework/MockObject/Invocation.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Invocation matcher which looks for specific parameters in the invocations. + * + * Checks the parameters of all incoming invocations, the parameter list is + * checked against the defined constraints in $parameters. If the constraint + * is met it will return true in matches(). + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_MockObject_Matcher_Parameters extends PHPUnit_Framework_MockObject_Matcher_StatelessInvocation +{ + protected $parameters = array(); + + protected $invocation; + + public function __construct($parameters) + { + foreach($parameters as $parameter) { + if (!($parameter instanceof PHPUnit_Framework_Constraint)) { + $parameter = new PHPUnit_Framework_Constraint_IsEqual($parameter); + } + + $this->parameters[] = $parameter; + } + } + + public function toString() + { + $text = 'with parameter'; + + foreach($this->parameters as $index => $parameter) { + if ($index > 0) { + $text .= ' and'; + } + + $text .= ' ' . $index . ' ' . $parameter->toString(); + } + + return $text; + } + + public function matches(PHPUnit_Framework_MockObject_Invocation $invocation) + { + $this->invocation = $invocation; + $this->verify(); + + return count($invocation->parameters) < count($this->parameters); + } + + public function verify() + { + if ($this->invocation === NULL) { + throw new PHPUnit_Framework_ExpectationFailedException( + 'Mocked method does not exist.' + ); + } + + if (count($this->invocation->parameters) < count($this->parameters)) { + throw new PHPUnit_Framework_ExpectationFailedException( + sprintf( + 'Parameter count for invocation %s is too low.', + + $this->invocation->toString() + ) + ); + } + + foreach ($this->parameters as $i => $parameter) { + if (!$parameter->evaluate($this->invocation->parameters[$i])) { + $parameter->fail( + $this->invocation->parameters[$i], + sprintf( + 'Parameter %s for invocation %s does not match expected value.', + + $i, + $this->invocation->toString() + ) + ); + } + } + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Matcher/StatelessInvocation.php b/tests/PHPUnit/Framework/MockObject/Matcher/StatelessInvocation.php new file mode 100755 index 00000000..85c2e74b --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Matcher/StatelessInvocation.php @@ -0,0 +1,81 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/Invocation.php'; +require_once 'PHPUnit/Framework/MockObject/Invocation.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Invocation matcher which does not care about previous state from earlier invocations. + * + * This abstract class can be implemented by matchers which does not care about + * state but only the current run-time value of the invocation itself. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + * @abstract + */ +abstract class PHPUnit_Framework_MockObject_Matcher_StatelessInvocation implements PHPUnit_Framework_MockObject_Matcher_Invocation +{ + public function invoked(PHPUnit_Framework_MockObject_Invocation $invocation) + { + } + + public function verify() + { + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Mock.php b/tests/PHPUnit/Framework/MockObject/Mock.php new file mode 100755 index 00000000..463cc5ce --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Mock.php @@ -0,0 +1,445 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Class.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher.php'; +require_once 'PHPUnit/Framework/MockObject/Invocation.php'; +require_once 'PHPUnit/Framework/MockObject/MockObject.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Provides generation of mock classes and objects from existing classes. + * + * The mocked class will contain all the methods of the original class but with + * a different implementation which will call the current + * PHPUnit_Framework_MockObject_InvocationMocker object, this objects takes + * care of checking expectations and stubs. + * It is also possible to define which methods are mocked by passing an array + * of method names. + * + * The simplest way to define a mock object is to do: + * + * + * PHPUnit_Framework_MockObject_Mock::generate('MyClass'); + * $o = new Mock_MyClass; + * + * + * The generate() method returns an object which can be queried. + * + * + * $m = PHPUnit_Framework_MockObject::generate('MyClass'); + * $o = new $m->mockClassName; + * print "original class was: . $m->className; + * + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_MockObject_Mock +{ + public $mockClassName; + public $className; + public $fullClassName; + public $namespaceName; + public $methods; + protected $callOriginalConstructor; + protected $callOriginalClone; + protected $callAutoload; + protected static $cache = array(); + + public function __construct($className, $methods = array(), $mockClassName = '', $callOriginalConstructor = TRUE, $callOriginalClone = TRUE, $callAutoload = TRUE) + { + $classNameParts = explode('\\', $className); + + if (count($classNameParts) > 1) { + $className = array_pop($classNameParts); + $namespaceName = join('\\', $classNameParts); + $this->fullClassName = $namespaceName . '\\' . $className; + } else { + $namespaceName = ''; + $this->fullClassName = $className; + } + + if ($mockClassName === '') { + do { + $mockClassName = 'Mock_' . $className . '_' . substr(md5(microtime()), 0, 8); + } + while (class_exists($mockClassName, FALSE)); + } + + else if (class_exists($mockClassName, FALSE)) { + throw new RuntimeException( + sprintf( + 'Class "%s" already exists.', + $mockClassName + ) + ); + } + + $isClass = class_exists($className, $callAutoload); + $isInterface = interface_exists($className, $callAutoload); + + if (is_array($methods) && empty($methods) && ($isClass || $isInterface)) { + $methods = get_class_methods($className); + } + + if ($isInterface) { + $callOriginalConstructor = FALSE; + } + + $this->mockClassName = $mockClassName; + $this->className = $className; + $this->namespaceName = $namespaceName; + $this->methods = $methods; + $this->callOriginalConstructor = $callOriginalConstructor; + $this->callOriginalClone = $callOriginalClone; + $this->callAutoload = $callAutoload; + } + + public static function generate($className, $methods = array(), $mockClassName = '', $callOriginalConstructor = TRUE, $callOriginalClone = TRUE, $callAutoload = TRUE) + { + if ($mockClassName == '') { + $key = md5( + $className . + serialize($methods) . + serialize($callOriginalConstructor) . + serialize($callOriginalClone) + ); + + if (!isset(self::$cache[$key])) { + self::$cache[$key] = self::generateMock( + $className, + $methods, + $mockClassName, + $callOriginalConstructor, + $callOriginalClone, + $callAutoload + ); + } + + return self::$cache[$key]; + } + + return self::generateMock( + $className, + $methods, + $mockClassName, + $callOriginalConstructor, + $callOriginalClone, + $callAutoload + ); + } + + protected static function generateMock($className, $methods, $mockClassName, $callOriginalConstructor, $callOriginalClone, $callAutoload) + { + $mock = new PHPUnit_Framework_MockObject_Mock( + $className, + $methods, + $mockClassName, + $callOriginalConstructor, + $callOriginalClone, + $callAutoload + ); + + $mock->generateClass(); + + return $mock; + } + + protected function generateClass() + { + if (!class_exists($this->fullClassName, $this->callAutoload) && !interface_exists($this->fullClassName, $this->callAutoload)) { + $code = 'class ' . $this->className . ' {}'; + + if (!empty($this->namespaceName)) { + $code = 'namespace ' . $this->namespaceName . ';' . $code; + } + + eval($code); + } + + try { + $class = new ReflectionClass($this->fullClassName); + + if ($class->isFinal()) { + throw new RuntimeException( + sprintf( + 'Class "%s" is declared "final" and cannot be mocked.', + $this->fullClassName + ) + ); + } + + $code = $this->generateClassDefinition($class); + + eval($code); + } + + catch (Exception $e) { + throw new RuntimeException( + sprintf( + 'Failed to generate mock class "%s" for class "%s".\n%s', + $this->mockClassName, + $this->fullClassName, + $e->getMessage() + ) + ); + } + } + + protected function generateClassDefinition(ReflectionClass $class) + { + $code = 'class '; + + if ($class->isInterface()) { + $code .= sprintf( + "%s implements %s%s {\n", + $this->mockClassName, + !empty($this->namespaceName) ? $this->namespaceName . '\\' : '', + $this->className + ); + } else { + $code .= sprintf( + "%s extends %s%s {\n", + $this->mockClassName, + !empty($this->namespaceName) ? $this->namespaceName . '\\' : '', + $this->className + ); + } + + $code .= $this->generateMockApi($class); + + if (is_array($this->methods)) { + foreach ($this->methods as $methodName) { + try { + $method = $class->getMethod($methodName); + + if ($this->canMockMethod($method)) { + $code .= $this->generateMethodDefinitionFromExisting($method); + } + } + + catch (ReflectionException $e) { + $code .= $this->generateMethodDefinition($class->getName(), $methodName, 'public'); + } + } + } + + $code .= "}\n"; + + return $code; + } + + protected function canMockMethod(ReflectionMethod $method) + { + $className = $method->getDeclaringClass()->getName(); + $methodName = $method->getName(); + + if ($method->isFinal() || $method->isStatic() || + $methodName == '__construct' || $methodName == $className || + $methodName == '__destruct' || $method->getName() == '__clone') { + return FALSE; + } + + return TRUE; + } + + protected function generateMethodDefinitionFromExisting(ReflectionMethod $method) + { + if ($method->isPrivate()) { + $modifier = 'private'; + } + + else if ($method->isProtected()) { + $modifier = 'protected'; + } + + else { + $modifier = 'public'; + } + + if ($method->returnsReference()) { + $reference = '&'; + } else { + $reference = ''; + } + + return $this->generateMethodDefinition( + $method->getDeclaringClass()->getName(), + $method->getName(), + $modifier, + $reference, + PHPUnit_Util_Class::getMethodParameters($method) + ); + } + + protected function generateMethodDefinition($className, $methodName, $modifier, $reference = '', $parameters = '') + { + return sprintf( + "\n %s function %s%s(%s) {\n" . + " \$args = func_get_args();\n" . + " \$result = \$this->invocationMocker->invoke(\n" . + " new PHPUnit_Framework_MockObject_Invocation(\$this, \"%s\", \"%s\", \$args)\n" . + " );\n\n" . + " return \$result;\n" . + " }\n", + + $modifier, + $reference, + $methodName, + $parameters, + $className, + $methodName + ); + } + + protected function generateMockApi(ReflectionClass $class) + { + if ($this->callOriginalConstructor) { + $constructorCode = $this->generateConstructorCodeWithParentCall($class); + } else { + $constructorCode = $this->generateConstructorCode($class); + } + + if ($this->callOriginalClone && $class->hasMethod('__clone')) { + $cloneCode = $this->generateCloneCodeWithParentCall(); + } else { + $cloneCode = $this->generateCloneCode(); + } + + return sprintf( + " private \$invocationMocker;\n\n" . + "%s" . + "%s" . + " public function expects(PHPUnit_Framework_MockObject_Matcher_Invocation \$matcher) {\n" . + " return \$this->invocationMocker->expects(\$matcher);\n" . + " }\n\n" . + " public function __phpunit_getInvocationMocker() {\n" . + " return \$this->invocationMocker;\n" . + " }\n\n" . + " public function __phpunit_verify() {\n" . + " \$this->invocationMocker->verify();\n" . + " }\n", + + $constructorCode, + $cloneCode + ); + } + + protected function generateConstructorCode(ReflectionClass $class) + { + $arguments = ''; + $constructor = $class->getConstructor(); + + if ($constructor !== NULL) { + $constructorName = $constructor->getName(); + + foreach (PHPUnit_Util_Class::getHierarchy($class->getName(), TRUE) as $_class) { + foreach ($_class->getInterfaces() as $interface) { + if ($interface->hasMethod($constructorName)) { + $arguments = PHPUnit_Util_Class::getMethodParameters($constructor); + break 2; + } + } + } + } + + return sprintf( + " public function __construct(%s) {\n" . + " \$this->invocationMocker = new PHPUnit_Framework_MockObject_InvocationMocker(\$this);\n" . + " }\n\n", + + $arguments + ); + } + + protected function generateConstructorCodeWithParentCall(ReflectionClass $class) + { + $constructor = $class->getConstructor(); + + if ($constructor !== NULL) { + return sprintf( + " public function __construct(%s) {\n" . + " \$args = func_get_args();\n" . + " \$this->invocationMocker = new PHPUnit_Framework_MockObject_InvocationMocker;\n" . + " \$class = new ReflectionClass('%s');\n" . + " \$class->getParentClass()->getConstructor()->invokeArgs(\$this, \$args);\n" . + " }\n\n", + + PHPUnit_Util_Class::getMethodParameters($constructor), + $this->mockClassName + ); + } else { + return $this->generateConstructorCode($class); + } + } + + protected function generateCloneCode() + { + return " public function __clone() {\n" . + " \$this->invocationMocker = clone \$this->invocationMocker;\n" . + " }\n\n"; + } + + protected function generateCloneCodeWithParentCall() + { + return " public function __clone() {\n" . + " \$this->invocationMocker = clone \$this->invocationMocker;\n" . + " parent::__clone();\n" . + " }\n\n"; + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/MockObject.php b/tests/PHPUnit/Framework/MockObject/MockObject.php new file mode 100755 index 00000000..23a1eacc --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/MockObject.php @@ -0,0 +1,88 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Builder/MethodNameMatch.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher.php'; +require_once 'PHPUnit/Framework/MockObject/InvocationMocker.php'; +require_once 'PHPUnit/Framework/MockObject/Verifiable.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Interface for all mock objects which are generated by + * PHPUnit_Framework_MockObject_Mock. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 3.0.0 + */ +interface PHPUnit_Framework_MockObject_MockObject extends PHPUnit_Framework_MockObject_Verifiable +{ + /** + * Returns the current invocation mocker which keeps track of expecations + * and stubs. + * @return PHPUnit_Framework_MockObject_InvocationMocker + */ + public function /*__phpunit_*/getInvocationMocker(); + + /** + * Registers a new expectation in the mock object and returns the match + * object which can be infused with further details. + * + * @param PHPUnit_Framework_MockObject_Matcher_Invocation $invocation The invocation handler for the method calls. + * @return PHPUnit_Framework_MockObject_Builder_MethodNameMatch + */ + public function expects(PHPUnit_Framework_MockObject_Matcher_Invocation $invocation); +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Stub.php b/tests/PHPUnit/Framework/MockObject/Stub.php new file mode 100755 index 00000000..cfe4b244 --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Stub.php @@ -0,0 +1,90 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Invocation.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * An object that stubs the process of a normal method for a mock object. + * + * The stub object will replace the code for the stubbed method and return a + * specific value instead of the original value. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 3.0.0 + */ +interface PHPUnit_Framework_MockObject_Stub extends PHPUnit_Framework_SelfDescribing +{ + /** + * Fakes the processesing of the invocation $invocation by returning a + * specific value. + * + * @return mixed + * @param PHPUnit_Framework_MockObject_Invocation $invocation The invocation which was mocked + * and matched by the current method + * and argument matchers. + */ + public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation); +} + +require_once 'PHPUnit/Framework/MockObject/Stub/ConsecutiveCalls.php'; +require_once 'PHPUnit/Framework/MockObject/Stub/Exception.php'; +require_once 'PHPUnit/Framework/MockObject/Stub/MatcherCollection.php'; +require_once 'PHPUnit/Framework/MockObject/Stub/Return.php'; +require_once 'PHPUnit/Framework/MockObject/Stub/ReturnArgument.php'; +require_once 'PHPUnit/Framework/MockObject/Stub/ReturnCallback.php'; +?> diff --git a/tests/PHPUnit/Framework/MockObject/Stub/ConsecutiveCalls.php b/tests/PHPUnit/Framework/MockObject/Stub/ConsecutiveCalls.php new file mode 100755 index 00000000..df04a663 --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Stub/ConsecutiveCalls.php @@ -0,0 +1,97 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Patrick Müller + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Invocation.php'; +require_once 'PHPUnit/Framework/MockObject/Stub.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Stubs a method by returning a user-defined stack of values. + * + * @category Testing + * @package PHPUnit + * @author Patrick Müller + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_MockObject_Stub_ConsecutiveCalls implements PHPUnit_Framework_MockObject_Stub +{ + protected $stack; + protected $value; + + public function __construct($stack) + { + $this->stack = $stack; + } + + public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation) + { + $this->value = array_shift($this->stack); + + if ($this->value instanceof PHPUnit_Framework_MockObject_Stub) { + $this->value = $this->value->invoke($invocation); + } + + return $this->value; + } + + public function toString() + { + return sprintf( + 'return user-specified value %s', + + PHPUnit_Util_Type::toString($this->value) + ); + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Stub/Exception.php b/tests/PHPUnit/Framework/MockObject/Stub/Exception.php new file mode 100755 index 00000000..9ef77f94 --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Stub/Exception.php @@ -0,0 +1,90 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Oliver Schlicht + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.1.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Invocation.php'; +require_once 'PHPUnit/Framework/MockObject/Stub.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Stubs a method by raising a user-defined exception. + * + * @category Testing + * @package PHPUnit + * @author Oliver Schlicht + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.1.0 + */ +class PHPUnit_Framework_MockObject_Stub_Exception implements PHPUnit_Framework_MockObject_Stub +{ + protected $exception; + + public function __construct(Exception $exception) + { + $this->exception = $exception; + } + + public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation) + { + throw $this->exception; + } + + public function toString() + { + return sprintf( + 'raise user-specified exception %s', + + PHPUnit_Util_Type::toString($this->exception) + ); + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Stub/MatcherCollection.php b/tests/PHPUnit/Framework/MockObject/Stub/MatcherCollection.php new file mode 100755 index 00000000..94c3562a --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Stub/MatcherCollection.php @@ -0,0 +1,76 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Stubs a method by returning a user-defined value. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 3.0.0 + */ +interface PHPUnit_Framework_MockObject_Stub_MatcherCollection +{ + /** + * Adds a new matcher to the collection which can be used as an expectation + * or a stub. + * + * @param PHPUnit_Framework_MockObject_Matcher_Invocation $matcher Matcher for invocations to mock objects. + */ + public function addMatcher(PHPUnit_Framework_MockObject_Matcher_Invocation $matcher); +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Stub/Return.php b/tests/PHPUnit/Framework/MockObject/Stub/Return.php new file mode 100755 index 00000000..1b4da191 --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Stub/Return.php @@ -0,0 +1,90 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Invocation.php'; +require_once 'PHPUnit/Framework/MockObject/Stub.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Stubs a method by returning a user-defined value. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_MockObject_Stub_Return implements PHPUnit_Framework_MockObject_Stub +{ + protected $value; + + public function __construct($value) + { + $this->value = $value; + } + + public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation) + { + return $this->value; + } + + public function toString() + { + return sprintf( + 'return user-specified value %s', + + PHPUnit_Util_Type::toString($this->value) + ); + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Stub/ReturnArgument.php b/tests/PHPUnit/Framework/MockObject/Stub/ReturnArgument.php new file mode 100755 index 00000000..69f20f3a --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Stub/ReturnArgument.php @@ -0,0 +1,87 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Stub/Return.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Stubs a method by returning an argument that was passed to the mocked method. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class PHPUnit_Framework_MockObject_Stub_ReturnArgument extends PHPUnit_Framework_MockObject_Stub_Return +{ + protected $argumentIndex; + + public function __construct($argumentIndex) + { + $this->argumentIndex = $argumentIndex; + } + + public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation) + { + if (isset($invocation->parameters[$this->argumentIndex])) { + return $invocation->parameters[$this->argumentIndex]; + } else { + return NULL; + } + } + + public function toString() + { + return sprintf('return argument #%d', $this->argumentIndex); + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Stub/ReturnCallback.php b/tests/PHPUnit/Framework/MockObject/Stub/ReturnCallback.php new file mode 100755 index 00000000..4c200a95 --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Stub/ReturnCallback.php @@ -0,0 +1,102 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Framework/MockObject/Invocation.php'; +require_once 'PHPUnit/Framework/MockObject/Stub.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class PHPUnit_Framework_MockObject_Stub_ReturnCallback implements PHPUnit_Framework_MockObject_Stub +{ + protected $callback; + + public function __construct($callback) + { + $this->callback = $callback; + } + + public function invoke(PHPUnit_Framework_MockObject_Invocation $invocation) + { + return call_user_func_array($this->callback, $invocation->parameters); + } + + public function toString() + { + if (is_array($this->callback)) { + if (is_object($this->callback[0])) { + $class = get_class($this->callback[0]); + $type = '->'; + } else { + $class = $this->callback[0]; + $type = '::'; + } + + return sprintf( + 'return result of user defined callback %s%s%s() with the passed arguments', + + $class, + $type, + $this->callback[1] + ); + } else { + return 'return result of user defined callback ' . $this->callback . ' with the passed arguments'; + } + } +} +?> diff --git a/tests/PHPUnit/Framework/MockObject/Verifiable.php b/tests/PHPUnit/Framework/MockObject/Verifiable.php new file mode 100755 index 00000000..a64c501e --- /dev/null +++ b/tests/PHPUnit/Framework/MockObject/Verifiable.php @@ -0,0 +1,75 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Interface for classes which must verify a given expectation. + * + * @category Testing + * @package PHPUnit + * @author Jan Borsodi + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 3.0.0 + */ +interface PHPUnit_Framework_MockObject_Verifiable +{ + /** + * Verifies that the current expectation is valid. If everything is OK the + * code should just return, if not it must throw an exception. + * + * @throw PHPUnit_Framework_ExpectationFailedException + */ + public function /*__phpunit_*/verify(); +} +?> diff --git a/tests/PHPUnit/Framework/SelfDescribing.php b/tests/PHPUnit/Framework/SelfDescribing.php new file mode 100755 index 00000000..62fc3bd6 --- /dev/null +++ b/tests/PHPUnit/Framework/SelfDescribing.php @@ -0,0 +1,76 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!interface_exists('PHPUnit_Framework_SelfDescribing', FALSE)) { + +/** + * Interface for classes that can return a description of itself. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 3.0.0 + */ +interface PHPUnit_Framework_SelfDescribing +{ + /** + * Returns a string representation of the object. + * + * @return string + */ + public function toString(); +} + +} +?> diff --git a/tests/PHPUnit/Framework/SkippedTest.php b/tests/PHPUnit/Framework/SkippedTest.php new file mode 100755 index 00000000..787a9465 --- /dev/null +++ b/tests/PHPUnit/Framework/SkippedTest.php @@ -0,0 +1,70 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!interface_exists('PHPUnit_Framework_SkippedTest', FALSE)) { + +/** + * A marker interface for marking a unit test as being skipped. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 3.0.0 + */ +interface PHPUnit_Framework_SkippedTest +{ +} + +} +?> diff --git a/tests/PHPUnit/Framework/SkippedTestError.php b/tests/PHPUnit/Framework/SkippedTestError.php new file mode 100755 index 00000000..bd783c5f --- /dev/null +++ b/tests/PHPUnit/Framework/SkippedTestError.php @@ -0,0 +1,72 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!class_exists('PHPUnit_Framework_SkippedTestError', FALSE)) { + +/** + * Extension to PHPUnit_Framework_AssertionFailedError to mark the special + * case of a skipped test. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Framework_SkippedTestError extends PHPUnit_Framework_AssertionFailedError implements PHPUnit_Framework_SkippedTest +{ +} + +} +?> diff --git a/tests/PHPUnit/Framework/SkippedTestSuiteError.php b/tests/PHPUnit/Framework/SkippedTestSuiteError.php new file mode 100755 index 00000000..c8d1e3b5 --- /dev/null +++ b/tests/PHPUnit/Framework/SkippedTestSuiteError.php @@ -0,0 +1,72 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.1.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!class_exists('PHPUnit_Framework_SkippedTestSuiteError', FALSE)) { + +/** + * Extension to PHPUnit_Framework_AssertionFailedError to mark the special + * case of a skipped test suite. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.1.0 + */ +class PHPUnit_Framework_SkippedTestSuiteError extends PHPUnit_Framework_AssertionFailedError implements PHPUnit_Framework_SkippedTest +{ +} + +} +?> diff --git a/tests/PHPUnit/Framework/Test.php b/tests/PHPUnit/Framework/Test.php new file mode 100755 index 00000000..26c17dc5 --- /dev/null +++ b/tests/PHPUnit/Framework/Test.php @@ -0,0 +1,78 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!interface_exists('PHPUnit_Framework_Test', FALSE)) { + +/** + * A Test can be run and collect its results. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 2.0.0 + */ +interface PHPUnit_Framework_Test extends Countable +{ + /** + * Runs a test and collects its result in a TestResult instance. + * + * @param PHPUnit_Framework_TestResult $result + * @return PHPUnit_Framework_TestResult + */ + public function run(PHPUnit_Framework_TestResult $result = NULL); +} + +} +?> diff --git a/tests/PHPUnit/Framework/TestCase.php b/tests/PHPUnit/Framework/TestCase.php new file mode 100755 index 00000000..c786adab --- /dev/null +++ b/tests/PHPUnit/Framework/TestCase.php @@ -0,0 +1,1043 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Framework/MockObject/Mock.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/InvokedAtLeastOnce.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/InvokedAtIndex.php'; +require_once 'PHPUnit/Framework/MockObject/Matcher/InvokedCount.php'; +require_once 'PHPUnit/Framework/MockObject/Stub.php'; +require_once 'PHPUnit/Runner/BaseTestRunner.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!class_exists('PHPUnit_Framework_TestCase', FALSE)) { + +/** + * A TestCase defines the fixture to run multiple tests. + * + * To define a TestCase + * + * 1) Implement a subclass of PHPUnit_Framework_TestCase. + * 2) Define instance variables that store the state of the fixture. + * 3) Initialize the fixture state by overriding setUp(). + * 4) Clean-up after a test by overriding tearDown(). + * + * Each test runs in its own fixture so there can be no side effects + * among test runs. + * + * Here is an example: + * + * + * value1 = 2; + * $this->value2 = 3; + * } + * } + * ?> + * + * + * For each test implement a method which interacts with the fixture. + * Verify the expected results with assertions specified by calling + * assert with a boolean. + * + * + * assertTrue($this->value1 + $this->value2 == 5); + * } + * ?> + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + * @abstract + */ +abstract class PHPUnit_Framework_TestCase extends PHPUnit_Framework_Assert implements PHPUnit_Framework_Test, PHPUnit_Framework_SelfDescribing +{ + /** + * Enable or disable the backup and restoration of the $GLOBALS array. + * Overwrite this attribute in a child class of TestCase. + * Setting this attribute in setUp() has no effect! + * + * @var boolean + */ + protected $backupGlobals = NULL; + + /** + * @var array + */ + protected $globalsBackup = array(); + + /** + * @var array + */ + protected $data = array(); + + /** + * @var string + */ + protected $dataName = ''; + + /** + * The name of the expected Exception. + * + * @var mixed + */ + protected $expectedException = NULL; + + /** + * The message of the expected Exception. + * + * @var string + */ + protected $expectedExceptionMessage = ''; + + /** + * The code of the expected Exception. + * + * @var integer + */ + protected $expectedExceptionCode; + + /** + * Fixture that is shared between the tests of a test suite. + * + * @var mixed + */ + protected $sharedFixture; + + /** + * The name of the test case. + * + * @var string + */ + protected $name = NULL; + + /** + * @var string + */ + protected $exceptionMessage = NULL; + + /** + * @var integer + */ + protected $exceptionCode = 0; + + /** + * @var Array + */ + protected $iniSettings = array(); + + /** + * @var Array + */ + protected $locale = array(); + + /** + * @var Array + */ + protected $mockObjects = array(); + + /** + * @var integer + */ + protected $status; + + /** + * @var string + */ + protected $statusMessage = ''; + + /** + * @var integer + */ + protected $numAssertions = 0; + + /** + * @var array + */ + protected static $superGlobalArrays = array( + '_ENV', + '_POST', + '_GET', + '_COOKIE', + '_SERVER', + '_FILES', + '_REQUEST' + ); + + /** + * @var array + */ + protected static $superGlobalArraysLong = array( + 'HTTP_ENV_VARS', + 'HTTP_POST_VARS', + 'HTTP_GET_VARS', + 'HTTP_COOKIE_VARS', + 'HTTP_SERVER_VARS', + 'HTTP_POST_FILES' + ); + + /** + * Constructs a test case with the given name. + * + * @param string $name + * @param array $data + * @param string $dataName + */ + public function __construct($name = NULL, array $data = array(), $dataName = '') + { + if ($name !== NULL) { + $this->setName($name); + } + + $this->data = $data; + $this->dataName = $dataName; + } + + /** + * Returns a string representation of the test case. + * + * @return string + */ + public function toString() + { + $class = new ReflectionClass($this); + + $buffer = sprintf( + '%s(%s)', + + $this->getName(FALSE), + $class->name + ); + + return $buffer . $this->getDataSetAsString(); + } + + /** + * Counts the number of test cases executed by run(TestResult result). + * + * @return integer + */ + public function count() + { + return 1; + } + + /** + * Gets the name of a TestCase. + * + * @param boolean $withDataSet + * @return string + */ + public function getName($withDataSet = TRUE) + { + if ($withDataSet) { + return $this->name . $this->getDataSetAsString(FALSE); + } else { + return $this->name; + } + } + + /** + * @return string + * @since Method available since Release 3.2.0 + */ + public function getExpectedException() + { + return $this->expectedException; + } + + /** + * @param mixed $exceptionName + * @param string $exceptionMessage + * @param integer $exceptionCode + * @since Method available since Release 3.2.0 + */ + public function setExpectedException($exceptionName, $exceptionMessage = '', $exceptionCode = 0) + { + $this->expectedException = $exceptionName; + $this->expectedExceptionMessage = $exceptionMessage; + $this->expectedExceptionCode = $exceptionCode; + } + + /** + * Returns the status of this test. + * + * @return integer + * @since Method available since Release 3.1.0 + */ + public function getStatus() + { + return $this->status; + } + + /** + * Returns the status message of this test. + * + * @return string + * @since Method available since Release 3.3.0 + */ + public function getStatusMessage() + { + return $this->statusMessage; + } + + /** + * Returns whether or not this test has failed. + * + * @return boolean + * @since Method available since Release 3.0.0 + */ + public function hasFailed() + { + $status = $this->getStatus(); + + return $status == PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE || + $status == PHPUnit_Runner_BaseTestRunner::STATUS_ERROR; + } + + /** + * Runs the test case and collects the results in a TestResult object. + * If no TestResult object is passed a new one will be created. + * + * @param PHPUnit_Framework_TestResult $result + * @return PHPUnit_Framework_TestResult + * @throws InvalidArgumentException + */ + public function run(PHPUnit_Framework_TestResult $result = NULL) + { + if ($result === NULL) { + $result = $this->createResult(); + } + + $result->run($this); + + return $result; + } + + /** + * Runs the bare test sequence. + * + */ + public function runBare() + { + $this->numAssertions = 0; + + // Backup the $GLOBALS array. + if ($this->backupGlobals === NULL || $this->backupGlobals === TRUE) { + $this->backupGlobals(); + } + + // Set up the fixture. + $this->setUp(); + + // Clean up stat cache. + clearstatcache(); + + // Run the test. + try { + // Assert pre-conditions. + $this->assertPreConditions(); + + $this->runTest(); + + // Assert post-conditions. + $this->assertPostConditions(); + + // Verify Mock Object conditions. + foreach ($this->mockObjects as $mockObject) { + $this->numAssertions++; + $mockObject->__phpunit_verify(); + } + + $this->status = PHPUnit_Runner_BaseTestRunner::STATUS_PASSED; + } + + catch (Exception $e) { + if ($e instanceof PHPUnit_Framework_IncompleteTest) { + $this->status = PHPUnit_Runner_BaseTestRunner::STATUS_INCOMPLETE; + } + + if ($e instanceof PHPUnit_Framework_SkippedTest) { + $this->status = PHPUnit_Runner_BaseTestRunner::STATUS_SKIPPED; + } + + if ($e instanceof PHPUnit_Framework_AssertionFailedError) { + $this->status = PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE; + } + + $this->statusMessage = $e->getMessage(); + } + + $this->mockObjects = array(); + + // Tear down the fixture. + $this->tearDown(); + + // Clean up stat cache. + clearstatcache(); + + // Restore the $GLOBALS array. + if ($this->backupGlobals === NULL || $this->backupGlobals === TRUE) { + $this->restoreGlobals(); + } + + // Clean up INI settings. + foreach ($this->iniSettings as $varName => $oldValue) { + ini_set($varName, $oldValue); + } + + $this->iniSettings = array(); + + // Clean up locale settings. + foreach ($this->locale as $category => $locale) { + setlocale($category, $locale); + } + + // Workaround for missing "finally". + if (isset($e)) { + throw $e; + } + } + + /** + * Override to run the test and assert its state. + * + * @throws RuntimeException + */ + protected function runTest() + { + if ($this->name === NULL) { + throw new RuntimeException( + 'PHPUnit_Framework_TestCase::$name must not be NULL.' + ); + } + + try { + $class = new ReflectionClass($this); + $method = $class->getMethod($this->name); + } + + catch (ReflectionException $e) { + $this->fail($e->getMessage()); + } + + try { + if (empty($this->data)) { + $method->invoke($this); + } else { + $method->invokeArgs($this, $this->data); + } + } + + catch (Exception $e) { + if (!$e instanceof PHPUnit_Framework_IncompleteTest && + !$e instanceof PHPUnit_Framework_SkippedTest && + is_string($this->expectedException) && + $e instanceof $this->expectedException) { + if (is_string($this->expectedExceptionMessage) && + !empty($this->expectedExceptionMessage)) { + $this->assertContains( + $this->expectedExceptionMessage, + $e->getMessage() + ); + } + + if (is_int($this->expectedExceptionCode) && + $this->expectedExceptionCode !== 0) { + $this->assertEquals( + $this->expectedExceptionCode, $e->getCode() + ); + } + + $this->numAssertions++; + + return; + } else { + throw $e; + } + } + + if ($this->expectedException !== NULL) { + $this->numAssertions++; + $this->fail('Expected exception ' . $this->expectedException); + } + } + + /** + * Sets the name of a TestCase. + * + * @param string + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * Calling this method in setUp() has no effect! + * + * @param boolean $backupGlobals + * @since Method available since Release 3.3.0 + */ + public function setBackupGlobals($backupGlobals) + { + if (is_null($this->backupGlobals) && is_bool($backupGlobals)) { + $this->backupGlobals = $backupGlobals; + } + } + + /** + * Sets the shared fixture. + * + * @param mixed $sharedFixture + * @since Method available since Release 3.1.0 + */ + public function setSharedFixture($sharedFixture) + { + $this->sharedFixture = $sharedFixture; + } + + /** + * This method is a wrapper for the ini_set() function that automatically + * resets the modified php.ini setting to its original value after the + * test is run. + * + * @param string $varName + * @param string $newValue + * @throws InvalidArgumentException + * @throws RuntimeException + * @since Method available since Release 3.0.0 + */ + protected function iniSet($varName, $newValue) + { + if (!is_string($varName)) { + throw new InvalidArgumentException; + } + + $currentValue = ini_set($varName, $newValue); + + if ($currentValue !== FALSE) { + $this->iniSettings[$varName] = $currentValue; + } else { + throw new RuntimeException; + } + } + + /** + * This method is a wrapper for the setlocale() function that automatically + * resets the locale to its original value after the test is run. + * + * @param integer $category + * @param string $locale + * @throws InvalidArgumentException + * @throws RuntimeException + * @since Method available since Release 3.1.0 + */ + protected function setLocale() + { + $args = func_get_args(); + + if (count($args) < 2) { + throw new InvalidArgumentException; + } + + $category = $args[0]; + $locale = $args[1]; + + $categories = array( + LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME + ); + + if (defined('LC_MESSAGES')) { + $categories[] = LC_MESSAGES; + } + + if (!in_array($category, $categories)) { + throw new InvalidArgumentException; + } + + if (!is_array($locale) && !is_string($locale)) { + throw new InvalidArgumentException; + } + + $this->locale[$category] = setlocale($category, NULL); + + $result = call_user_func_array( 'setlocale', $args ); + + if ($result === FALSE) { + throw new RuntimeException( + 'The locale functionality is not implemented on your platform, ' . + 'the specified locale does not exist or the category name is ' . + 'invalid.' + ); + } + } + + /** + * Returns a mock object for the specified class. + * + * @param string $className + * @param array $methods + * @param array $arguments + * @param string $mockClassName + * @param boolean $callOriginalConstructor + * @param boolean $callOriginalClone + * @param boolean $callAutoload + * @return object + * @since Method available since Release 3.0.0 + */ + protected function getMock($className, $methods = array(), array $arguments = array(), $mockClassName = '', $callOriginalConstructor = TRUE, $callOriginalClone = TRUE, $callAutoload = TRUE) + { + if (!is_string($className) || !is_string($mockClassName)) { + throw new InvalidArgumentException; + } + + if (!is_array($methods) && !is_null($methods)) { + throw new InvalidArgumentException; + } + + $mock = PHPUnit_Framework_MockObject_Mock::generate( + $className, + $methods, + $mockClassName, + $callOriginalConstructor, + $callOriginalClone, + $callAutoload + ); + + if (count($arguments) == 0) { + $mockObject = new $mock->mockClassName; + } else { + $mockClass = new ReflectionClass($mock->mockClassName); + $mockObject = $mockClass->newInstanceArgs($arguments); + } + + $this->mockObjects[] = $mockObject; + + return $mockObject; + } + + /** + * Adds a value to the assertion counter. + * + * @param integer $count + * @since Method available since Release 3.3.3 + */ + public function addToAssertionCount($count) + { + $this->numAssertions += $count; + } + + /** + * Returns the number of assertions performed by this test. + * + * @return integer + * @since Method available since Release 3.3.0 + */ + public function getNumAssertions() + { + return $this->numAssertions; + } + + /** + * Returns a matcher that matches when the method it is evaluated for + * is executed zero or more times. + * + * @return PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount + * @since Method available since Release 3.0.0 + */ + protected function any() + { + return new PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount; + } + + /** + * Returns a matcher that matches when the method it is evaluated for + * is never executed. + * + * @return PHPUnit_Framework_MockObject_Matcher_InvokedCount + * @since Method available since Release 3.0.0 + */ + protected function never() + { + return new PHPUnit_Framework_MockObject_Matcher_InvokedCount(0); + } + + /** + * Returns a matcher that matches when the method it is evaluated for + * is executed at least once. + * + * @return PHPUnit_Framework_MockObject_Matcher_InvokedAtLeastOnce + * @since Method available since Release 3.0.0 + */ + protected function atLeastOnce() + { + return new PHPUnit_Framework_MockObject_Matcher_InvokedAtLeastOnce; + } + + /** + * Returns a matcher that matches when the method it is evaluated for + * is executed exactly once. + * + * @return PHPUnit_Framework_MockObject_Matcher_InvokedCount + * @since Method available since Release 3.0.0 + */ + protected function once() + { + return new PHPUnit_Framework_MockObject_Matcher_InvokedCount(1); + } + + /** + * Returns a matcher that matches when the method it is evaluated for + * is executed exactly $count times. + * + * @param integer $count + * @return PHPUnit_Framework_MockObject_Matcher_InvokedCount + * @since Method available since Release 3.0.0 + */ + protected function exactly($count) + { + return new PHPUnit_Framework_MockObject_Matcher_InvokedCount($count); + } + + /** + * Returns a matcher that matches when the method it is evaluated for + * is invoked at the given $index. + * + * @param integer $index + * @return PHPUnit_Framework_MockObject_Matcher_InvokedAtIndex + * @since Method available since Release 3.0.0 + */ + protected function at($index) + { + return new PHPUnit_Framework_MockObject_Matcher_InvokedAtIndex($index); + } + + /** + * + * + * @param mixed $value + * @return PHPUnit_Framework_MockObject_Stub_Return + * @since Method available since Release 3.0.0 + */ + protected function returnValue($value) + { + return new PHPUnit_Framework_MockObject_Stub_Return($value); + } + + /** + * + * + * @param integer $argumentIndex + * @return PHPUnit_Framework_MockObject_Stub_ReturnArgument + * @since Method available since Release 3.3.0 + */ + protected function returnArgument($argumentIndex) + { + return new PHPUnit_Framework_MockObject_Stub_ReturnArgument($argumentIndex); + } + + /** + * + * + * @param mixed $callback + * @return PHPUnit_Framework_MockObject_Stub_ReturnCallback + * @since Method available since Release 3.3.0 + */ + protected function returnCallback($callback) + { + return new PHPUnit_Framework_MockObject_Stub_ReturnCallback($callback); + } + + /** + * + * + * @param Exception $exception + * @return PHPUnit_Framework_MockObject_Stub_Exception + * @since Method available since Release 3.1.0 + */ + protected function throwException(Exception $exception) + { + return new PHPUnit_Framework_MockObject_Stub_Exception($exception); + } + + /** + * + * + * @param mixed $value, ... + * @return PHPUnit_Framework_MockObject_Stub_ConsecutiveCalls + * @since Method available since Release 3.0.0 + */ + protected function onConsecutiveCalls() + { + $args = func_get_args(); + + return new PHPUnit_Framework_MockObject_Stub_ConsecutiveCalls($args); + } + + /** + * @param mixed $data + * @return string + * @since Method available since Release 3.2.1 + */ + protected function dataToString($data) + { + $result = array(); + + foreach ($data as $_data) { + if (is_array($_data)) { + $result[] = 'array(' . $this->dataToString($_data) . ')'; + } + + else if (is_object($_data)) { + $object = new ReflectionObject($_data); + + if ($object->hasMethod('__toString')) { + $result[] = (string)$_data; + } else { + $result[] = get_class($_data); + } + } + + else if (is_resource($_data)) { + $result[] = ''; + } + + else { + $result[] = var_export($_data, TRUE); + } + } + + return join(', ', $result); + } + + /** + * Gets the data set description of a TestCase. + * + * @param boolean $includeData + * @return string + * @since Method available since Release 3.3.0 + */ + protected function getDataSetAsString($includeData = TRUE) + { + $buffer = ''; + + if (!empty($this->data)) { + if (is_int($this->dataName)) { + $buffer .= sprintf(' with data set #%d', $this->dataName); + } else { + $buffer .= sprintf(' with data set "%s"', $this->dataName); + } + + if ($includeData) { + $buffer .= sprintf(' (%s)', $this->dataToString($this->data)); + } + } + + return $buffer; + } + + /** + * Creates a default TestResult object. + * + * @return PHPUnit_Framework_TestResult + */ + protected function createResult() + { + return new PHPUnit_Framework_TestResult; + } + + /** + * Sets up the fixture, for example, open a network connection. + * This method is called before a test is executed. + * + */ + protected function setUp() + { + } + + /** + * Performs assertions shared by all tests of a test case. + * + * This method is called before the execution of a test starts + * and after setUp() is called. + * + * @since Method available since Release 3.2.8 + */ + protected function assertPreConditions() + { + } + + /** + * Performs assertions shared by all tests of a test case. + * + * This method is called before the execution of a test ends + * and before tearDown() is called. + * + * @since Method available since Release 3.2.8 + */ + protected function assertPostConditions() + { + // assertPostConditions() was named sharedAssertions() in + // PHPUnit 3.0.0-3.2.7. + if (method_exists($this, 'sharedAssertions')) { + $this->sharedAssertions(); + } + } + + /** + * Tears down the fixture, for example, close a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { + } + + /** + * @since Method available since Release 3.3.0 + */ + protected function backupGlobals() + { + $this->globalsBackup = array(); + + if (ini_get('register_long_arrays') == '1') { + $superGlobalArrays = array_merge( + self::$superGlobalArrays, self::$superGlobalArraysLong + ); + } else { + $superGlobalArrays = self::$superGlobalArrays; + } + + foreach ($superGlobalArrays as $superGlobalArray) { + $this->backupSuperGlobalArray($superGlobalArray); + } + + foreach (array_keys($GLOBALS) as $key) { + if ($key != 'GLOBALS' && !in_array($key, $superGlobalArrays)) { + $this->globalsBackup['GLOBALS'][$key] = serialize($GLOBALS[$key]); + } + } + } + + /** + * @since Method available since Release 3.3.0 + */ + protected function restoreGlobals() + { + if (ini_get('register_long_arrays') == '1') { + $superGlobalArrays = array_merge( + self::$superGlobalArrays, self::$superGlobalArraysLong + ); + } else { + $superGlobalArrays = self::$superGlobalArrays; + } + + foreach ($superGlobalArrays as $superGlobalArray) { + $this->restoreSuperGlobalArray($superGlobalArray); + } + + foreach (array_keys($GLOBALS) as $key) { + if ($key != 'GLOBALS' && !in_array($key, $superGlobalArrays)) { + if (isset($this->globalsBackup['GLOBALS'][$key])) { + $GLOBALS[$key] = unserialize($this->globalsBackup['GLOBALS'][$key]); + } else { + unset($GLOBALS[$key]); + } + } + } + + $this->globalsBackup = array(); + } + + protected function backupSuperGlobalArray($superGlobalArray) + { + $this->globalsBackup[$superGlobalArray] = array(); + + if (isset($GLOBALS[$superGlobalArray])) { + foreach ($GLOBALS[$superGlobalArray] as $key => $value) { + $this->globalsBackup[$superGlobalArray][$key] = serialize($value); + } + } + } + + protected function restoreSuperGlobalArray($superGlobalArray) + { + if (isset($GLOBALS[$superGlobalArray])) { + foreach ($GLOBALS[$superGlobalArray] as $key => $value) { + if (isset($this->globalsBackup[$superGlobalArray][$key])) { + $GLOBALS[$superGlobalArray][$key] = unserialize($this->globalsBackup[$superGlobalArray][$key]); + } else { + unset($GLOBALS[$superGlobalArray][$key]); + } + } + } + + $this->globalsBackup[$superGlobalArray] = array(); + } +} + +} +?> diff --git a/tests/PHPUnit/Framework/TestFailure.php b/tests/PHPUnit/Framework/TestFailure.php new file mode 100755 index 00000000..bee59ab2 --- /dev/null +++ b/tests/PHPUnit/Framework/TestFailure.php @@ -0,0 +1,251 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!class_exists('PHPUnit_Framework_TestFailure', FALSE)) { + +/** + * A TestFailure collects a failed test together with the caught exception. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class PHPUnit_Framework_TestFailure +{ + /** + * @var PHPUnit_Framework_Test + */ + protected $failedTest; + + /** + * @var Exception + */ + protected $thrownException; + + /** + * Constructs a TestFailure with the given test and exception. + * + * @param PHPUnit_Framework_Test $failedTest + * @param Exception $thrownException + */ + public function __construct(PHPUnit_Framework_Test $failedTest, Exception $thrownException) + { + $this->failedTest = $failedTest; + $this->thrownException = $thrownException; + } + + /** + * Returns a short description of the failure. + * + * @return string + */ + public function toString() + { + return sprintf( + '%s: %s', + + $this->failedTest, + $this->thrownException->getMessage() + ); + } + + /** + * Returns a verbose description of the failure. + * + * @param bool $verbose + * @return string + * @since Method available since Release 3.2.0 + */ + public function toStringVerbose($verbose = FALSE) + { + return self::exceptionToString($this->thrownException, $verbose); + } + + /** + * Returns a verbose description for an exception. + * + * @param Exception $e + * @param bool $verbose + * @return string + * @since Method available since Release 3.2.0 + */ + public static function exceptionToString(Exception $e, $verbose = FALSE) + { + if ($e instanceof PHPUnit_Framework_SelfDescribing) { + if ($e instanceof PHPUnit_Framework_ExpectationFailedException) { + $comparisonFailure = $e->getComparisonFailure(); + $description = $e->getDescription(); + $message = $e->getCustomMessage(); + + if ($message == '') { + $buffer = ''; + } else { + $buffer = $message . "\n"; + } + + if ($comparisonFailure !== NULL) { + if ($comparisonFailure->identical()) { + if ($comparisonFailure instanceof PHPUnit_Framework_ComparisonFailure_Object) { + $buffer .= "Failed asserting that two variables reference the same object.\n"; + } else { + $buffer .= $comparisonFailure->toString() . "\n"; + } + } else { + if ($comparisonFailure instanceof PHPUnit_Framework_ComparisonFailure_Scalar) { + $buffer .= sprintf( + "Failed asserting that %s matches expected value %s.\n", + + PHPUnit_Util_Type::toString($comparisonFailure->getActual()), + PHPUnit_Util_Type::toString($comparisonFailure->getExpected()) + ); + } + + else if ($comparisonFailure instanceof PHPUnit_Framework_ComparisonFailure_Array || + $comparisonFailure instanceof PHPUnit_Framework_ComparisonFailure_Object || + $comparisonFailure instanceof PHPUnit_Framework_ComparisonFailure_String) { + $buffer .= sprintf( + "Failed asserting that two %ss are equal.\n%s\n", + + strtolower(substr(get_class($comparisonFailure), 36)), + $comparisonFailure->toString() + ); + } + + if ($verbose && + !$comparisonFailure instanceof PHPUnit_Framework_ComparisonFailure_Array && + !$comparisonFailure instanceof PHPUnit_Framework_ComparisonFailure_Object && + !$comparisonFailure instanceof PHPUnit_Framework_ComparisonFailure_String) { + $buffer .= $comparisonFailure->toString() . "\n"; + } + } + } else { + $buffer .= $e->toString(); + $equal = $buffer == $description; + + if (!empty($buffer)) { + $buffer .= "\n"; + } + + if (!$equal) { + $buffer .= $description . "\n"; + } + } + } + + else { + $buffer = $e->toString(); + + if (!empty($buffer)) { + $buffer .= "\n"; + } + } + } + + else if ($e instanceof PHPUnit_Framework_Error) { + $buffer = $e->getMessage() . "\n"; + } + + else { + $buffer = get_class($e) . ': ' . $e->getMessage() . "\n"; + } + + return $buffer; + } + + /** + * Gets the failed test. + * + * @return Test + */ + public function failedTest() + { + return $this->failedTest; + } + + /** + * Gets the thrown exception. + * + * @return Exception + */ + public function thrownException() + { + return $this->thrownException; + } + + /** + * Returns the exception's message. + * + * @return string + */ + public function exceptionMessage() + { + return $this->thrownException()->getMessage(); + } + + /** + * Returns TRUE if the thrown exception + * is of type AssertionFailedError. + * + * @return boolean + */ + public function isFailure() + { + return ($this->thrownException() instanceof PHPUnit_Framework_AssertionFailedError); + } +} + +} +?> diff --git a/tests/PHPUnit/Framework/TestListener.php b/tests/PHPUnit/Framework/TestListener.php new file mode 100755 index 00000000..bd9c148c --- /dev/null +++ b/tests/PHPUnit/Framework/TestListener.php @@ -0,0 +1,138 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!interface_exists('PHPUnit_Framework_TestListener', FALSE)) { + +/** + * A Listener for test progress. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 2.0.0 + */ +interface PHPUnit_Framework_TestListener +{ + /** + * An error occurred. + * + * @param PHPUnit_Framework_Test $test + * @param Exception $e + * @param float $time + */ + public function addError(PHPUnit_Framework_Test $test, Exception $e, $time); + + /** + * A failure occurred. + * + * @param PHPUnit_Framework_Test $test + * @param PHPUnit_Framework_AssertionFailedError $e + * @param float $time + */ + public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time); + + /** + * Incomplete test. + * + * @param PHPUnit_Framework_Test $test + * @param Exception $e + * @param float $time + */ + public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time); + + /** + * Skipped test. + * + * @param PHPUnit_Framework_Test $test + * @param Exception $e + * @param float $time + * @since Method available since Release 3.0.0 + */ + public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time); + + /** + * A test suite started. + * + * @param PHPUnit_Framework_TestSuite $suite + * @since Method available since Release 2.2.0 + */ + public function startTestSuite(PHPUnit_Framework_TestSuite $suite); + + /** + * A test suite ended. + * + * @param PHPUnit_Framework_TestSuite $suite + * @since Method available since Release 2.2.0 + */ + public function endTestSuite(PHPUnit_Framework_TestSuite $suite); + + /** + * A test started. + * + * @param PHPUnit_Framework_Test $test + */ + public function startTest(PHPUnit_Framework_Test $test); + + /** + * A test ended. + * + * @param PHPUnit_Framework_Test $test + * @param float $time + */ + public function endTest(PHPUnit_Framework_Test $test, $time); +} + +} +?> diff --git a/tests/PHPUnit/Framework/TestResult.php b/tests/PHPUnit/Framework/TestResult.php new file mode 100755 index 00000000..4bf038be --- /dev/null +++ b/tests/PHPUnit/Framework/TestResult.php @@ -0,0 +1,729 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/CodeCoverage.php'; +require_once 'PHPUnit/Util/ErrorHandler.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Printer.php'; +require_once 'PHPUnit/Util/Test.php'; +require_once 'PHPUnit/Util/Timer.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!class_exists('PHPUnit_Framework_TestResult', FALSE)) { + +/** + * A TestResult collects the results of executing a test case. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class PHPUnit_Framework_TestResult implements Countable +{ + protected static $xdebugLoaded = NULL; + protected static $useXdebug = NULL; + + /** + * @var array + */ + protected $errors = array(); + + /** + * @var array + */ + protected $failures = array(); + + /** + * @var array + */ + protected $notImplemented = array(); + + /** + * @var array + */ + protected $skipped = array(); + + /** + * @var array + */ + protected $listeners = array(); + + /** + * @var integer + */ + protected $runTests = 0; + + /** + * @var float + */ + protected $time = 0; + + /** + * @var PHPUnit_Framework_TestSuite + */ + protected $topTestSuite = NULL; + + /** + * Code Coverage information provided by Xdebug. + * + * @var array + */ + protected $codeCoverageInformation = array(); + + /** + * @var boolean + */ + protected $collectCodeCoverageInformation = FALSE; + + /** + * @var boolean + */ + protected $convertErrorsToExceptions = TRUE; + + /** + * @var boolean + */ + protected $stop = FALSE; + + /** + * @var boolean + */ + protected $stopOnFailure = FALSE; + + /** + * @var boolean + */ + protected $lastTestFailed = FALSE; + + /** + * Registers a TestListener. + * + * @param PHPUnit_Framework_TestListener + */ + public function addListener(PHPUnit_Framework_TestListener $listener) + { + $this->listeners[] = $listener; + } + + /** + * Unregisters a TestListener. + * + * @param PHPUnit_Framework_TestListener $listener + */ + public function removeListener(PHPUnit_Framework_TestListener $listener) + { + foreach ($this->listeners as $key => $_listener) { + if ($listener === $_listener) { + unset($this->listeners[$key]); + } + } + } + + /** + * Flushes all flushable TestListeners. + * + * @since Method available since Release 3.0.0 + */ + public function flushListeners() + { + foreach ($this->listeners as $listener) { + if ($listener instanceof PHPUnit_Util_Printer) { + $listener->flush(); + } + } + } + + /** + * Adds an error to the list of errors. + * The passed in exception caused the error. + * + * @param PHPUnit_Framework_Test $test + * @param Exception $e + * @param float $time + */ + public function addError(PHPUnit_Framework_Test $test, Exception $e, $time) + { + if ($e instanceof PHPUnit_Framework_IncompleteTest) { + $this->notImplemented[] = new PHPUnit_Framework_TestFailure($test, $e); + $notifyMethod = 'addIncompleteTest'; + } + + else if ($e instanceof PHPUnit_Framework_SkippedTest) { + $this->skipped[] = new PHPUnit_Framework_TestFailure($test, $e); + $notifyMethod = 'addSkippedTest'; + } + + else { + $this->errors[] = new PHPUnit_Framework_TestFailure($test, $e); + $notifyMethod = 'addError'; + + if ($this->stopOnFailure) { + $this->stop(); + } + } + + foreach ($this->listeners as $listener) { + $listener->$notifyMethod($test, $e, $time); + } + + $this->lastTestFailed = TRUE; + $this->time += $time; + } + + /** + * Adds a failure to the list of failures. + * The passed in exception caused the failure. + * + * @param PHPUnit_Framework_Test $test + * @param PHPUnit_Framework_AssertionFailedError $e + * @param float $time + */ + public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time) + { + if ($e instanceof PHPUnit_Framework_IncompleteTest) { + $this->notImplemented[] = new PHPUnit_Framework_TestFailure($test, $e); + $notifyMethod = 'addIncompleteTest'; + } + + else if ($e instanceof PHPUnit_Framework_SkippedTest) { + $this->skipped[] = new PHPUnit_Framework_TestFailure($test, $e); + $notifyMethod = 'addSkippedTest'; + } + + else { + $this->failures[] = new PHPUnit_Framework_TestFailure($test, $e); + $notifyMethod = 'addFailure'; + + if ($this->stopOnFailure) { + $this->stop(); + } + } + + foreach ($this->listeners as $listener) { + $listener->$notifyMethod($test, $e, $time); + } + + $this->lastTestFailed = TRUE; + $this->time += $time; + } + + /** + * Informs the result that a testsuite will be started. + * + * @param PHPUnit_Framework_TestSuite $suite + * @since Method available since Release 2.2.0 + */ + public function startTestSuite(PHPUnit_Framework_TestSuite $suite) + { + if ($this->topTestSuite === NULL) { + $this->topTestSuite = $suite; + } + + foreach ($this->listeners as $listener) { + $listener->startTestSuite($suite); + } + } + + /** + * Informs the result that a testsuite was completed. + * + * @param PHPUnit_Framework_TestSuite $suite + * @since Method available since Release 2.2.0 + */ + public function endTestSuite(PHPUnit_Framework_TestSuite $suite) + { + foreach ($this->listeners as $listener) { + $listener->endTestSuite($suite); + } + } + + /** + * Informs the result that a test will be started. + * + * @param PHPUnit_Framework_Test $test + */ + public function startTest(PHPUnit_Framework_Test $test) + { + $this->lastTestFailed = FALSE; + $this->runTests += count($test); + + foreach ($this->listeners as $listener) { + $listener->startTest($test); + } + } + + /** + * Informs the result that a test was completed. + * + * @param PHPUnit_Framework_Test $test + * @param float $time + */ + public function endTest(PHPUnit_Framework_Test $test, $time) + { + foreach ($this->listeners as $listener) { + $listener->endTest($test, $time); + } + + if (!$this->lastTestFailed) { + $this->time += $time; + } + } + + /** + * Returns TRUE if no incomplete test occured. + * + * @return boolean + */ + public function allCompletlyImplemented() + { + return $this->notImplementedCount() == 0; + } + + /** + * Gets the number of incomplete tests. + * + * @return integer + */ + public function notImplementedCount() + { + return count($this->notImplemented); + } + + /** + * Returns an Enumeration for the incomplete tests. + * + * @return array + */ + public function notImplemented() + { + return $this->notImplemented; + } + + /** + * Returns TRUE if no test has been skipped. + * + * @return boolean + * @since Method available since Release 3.0.0 + */ + public function noneSkipped() + { + return $this->skippedCount() == 0; + } + + /** + * Gets the number of skipped tests. + * + * @return integer + * @since Method available since Release 3.0.0 + */ + public function skippedCount() + { + return count($this->skipped); + } + + /** + * Returns an Enumeration for the skipped tests. + * + * @return array + * @since Method available since Release 3.0.0 + */ + public function skipped() + { + return $this->skipped; + } + + /** + * Gets the number of detected errors. + * + * @return integer + */ + public function errorCount() + { + return count($this->errors); + } + + /** + * Returns an Enumeration for the errors. + * + * @return array + */ + public function errors() + { + return $this->errors; + } + + /** + * Gets the number of detected failures. + * + * @return integer + */ + public function failureCount() + { + return count($this->failures); + } + + /** + * Returns an Enumeration for the failures. + * + * @return array + */ + public function failures() + { + return $this->failures; + } + + /** + * Returns the (top) test suite. + * + * @return PHPUnit_Framework_TestSuite + * @since Method available since Release 3.0.0 + */ + public function topTestSuite() + { + return $this->topTestSuite; + } + + /** + * Enables or disables the collection of Code Coverage information. + * + * @param boolean $flag + * @throws InvalidArgumentException + * @since Method available since Release 2.3.0 + */ + public function collectCodeCoverageInformation($flag) + { + if (is_bool($flag)) { + $this->collectCodeCoverageInformation = $flag; + } else { + throw new InvalidArgumentException; + } + } + + /** + * Returns whether code coverage information should be collected. + * + * @return boolean If code coverage should be collected + * @since Method available since Release 3.2.0 + */ + public function getCollectCodeCoverageInformation() + { + return $this->collectCodeCoverageInformation; + } + + /** + * Appends code coverage information to the test + * + * @param PHPUnit_Framework_Test $test + * @param array $data + * @since Method available since Release 3.2.0 + */ + public function appendCodeCoverageInformation(PHPUnit_Framework_Test $test, $data) + { + $deadCode = array(); + $executableCode = array(); + + foreach (array_keys($data) as $file) { + if (PHPUnit_Util_Filter::isFiltered($file, FALSE)) { + unset($data[$file]); + } + } + + $newFilesToCollect = array_diff_key($data, PHPUnit_Util_Filter::getCoveredFiles()); + + if (count($newFilesToCollect) > 0) { + $deadCode = PHPUnit_Util_CodeCoverage::getDeadLines($newFilesToCollect); + $executableCode = PHPUnit_Util_CodeCoverage::getExecutableLines($newFilesToCollect); + + foreach (array_keys($newFilesToCollect) as $file) { + PHPUnit_Util_Filter::addCoveredFile($file); + } + + unset($newFilesToCollect); + } + + if ($test instanceof PHPUnit_Framework_TestCase) { + $linesToBeCovered = PHPUnit_Util_Test::getLinesToBeCovered( + get_class($test), $test->getName() + ); + + if (!empty($linesToBeCovered)) { + $data = array_intersect_key($data, $linesToBeCovered); + + foreach (array_keys($data) as $file) { + $data[$file] = array_intersect_key($data[$file], array_flip($linesToBeCovered[$file])); + } + } + } + + $executed = PHPUnit_Util_CodeCoverage::getExecutedLines($data); + unset($data); + + $this->codeCoverageInformation[] = array( + 'test' => $test, + 'files' => $executed, + 'dead' => $deadCode, + 'executable' => $executableCode, + ); + } + + /** + * Returns Code Coverage data per test case. + * + * Format of the result array: + * + * + * array( + * array( + * 'test' => PHPUnit_Framework_Test + * 'files' => array( + * "/tested/code.php" => array( + * linenumber => flag + * ) + * ) + * ) + * ) + * + * + * flag < 0: Line is executable but was not executed. + * flag > 0: Line was executed. + * + * @param boolean $filterTests + * @return array + */ + public function getCodeCoverageInformation($filterTests = TRUE) + { + return PHPUnit_Util_Filter::getFilteredCodeCoverage( + $this->codeCoverageInformation, $filterTests + ); + } + + /** + * Returns unfiltered Code Coverage data per test case. + * Returns data in the same form as getCodeCoverageInformation(). + * + * @return array + */ + public function getUncoveredWhitelistFiles() + { + list(, $missing) = PHPUnit_Util_Filter::getFileCodeCoverageDisposition( + $this->codeCoverageInformation + ); + + return $missing; + } + + /** + * Runs a TestCase. + * + * @param PHPUnit_Framework_Test $test + */ + public function run(PHPUnit_Framework_Test $test) + { + PHPUnit_Framework_Assert::resetCount(); + + $error = FALSE; + $failure = FALSE; + + $this->startTest($test); + + $errorHandlerSet = FALSE; + + if ($this->convertErrorsToExceptions) { + $oldErrorHandler = set_error_handler( + array('PHPUnit_Util_ErrorHandler', 'handleError'), E_ALL | E_STRICT + ); + + if ($oldErrorHandler === NULL) { + $errorHandlerSet = TRUE; + } else { + restore_error_handler(); + } + } + + if (self::$xdebugLoaded === NULL) { + self::$xdebugLoaded = extension_loaded('xdebug'); + self::$useXdebug = self::$xdebugLoaded; + } + + $useXdebug = self::$useXdebug && $this->collectCodeCoverageInformation && !$test instanceof PHPUnit_Extensions_SeleniumTestCase; + + if ($useXdebug) { + xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE); + } + + PHPUnit_Util_Timer::start(); + + try { + $test->runBare(); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + $failure = TRUE; + } + + catch (Exception $e) { + $error = TRUE; + } + + $time = PHPUnit_Util_Timer::stop(); + + if ($useXdebug) { + $codeCoverage = xdebug_get_code_coverage(); + xdebug_stop_code_coverage(); + + $this->appendCodeCoverageInformation( + $test, $codeCoverage + ); + } + + if ($errorHandlerSet === TRUE) { + restore_error_handler(); + } + + $test->addToAssertionCount(PHPUnit_Framework_Assert::getCount()); + + if ($error === TRUE) { + $this->addError($test, $e, $time); + } + + else if ($failure === TRUE) { + $this->addFailure($test, $e, $time); + } + + $this->endTest($test, $time); + } + + /** + * Gets the number of run tests. + * + * @return integer + */ + public function count() + { + return $this->runTests; + } + + /** + * Checks whether the test run should stop. + * + * @return boolean + */ + public function shouldStop() + { + return $this->stop; + } + + /** + * Marks that the test run should stop. + * + */ + public function stop() + { + $this->stop = TRUE; + } + + /** + * Enables or disables the error-to-exception conversion. + * + * @param boolean $flag + * @throws InvalidArgumentException + * @since Method available since Release 3.2.14 + */ + public function convertErrorsToExceptions($flag) + { + if (is_bool($flag)) { + $this->convertErrorsToExceptions = $flag; + } else { + throw new InvalidArgumentException; + } + } + + /** + * Enables or disables the stopping when a failure or error occurs. + * + * @param boolean $flag + * @throws InvalidArgumentException + * @since Method available since Release 3.1.0 + */ + public function stopOnFailure($flag) + { + if (is_bool($flag)) { + $this->stopOnFailure = $flag; + } else { + throw new InvalidArgumentException; + } + } + + /** + * Returns the time spent running the tests. + * + * @return float + */ + public function time() + { + return $this->time; + } + + /** + * Returns whether the entire test was successful or not. + * + * @return boolean + */ + public function wasSuccessful() + { + return empty($this->errors) && empty($this->failures); + } +} + +} +?> diff --git a/tests/PHPUnit/Framework/TestSuite.php b/tests/PHPUnit/Framework/TestSuite.php new file mode 100755 index 00000000..4fe9fa1f --- /dev/null +++ b/tests/PHPUnit/Framework/TestSuite.php @@ -0,0 +1,855 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Runner/BaseTestRunner.php'; +require_once 'PHPUnit/Util/Class.php'; +require_once 'PHPUnit/Util/Fileloader.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Test.php'; +require_once 'PHPUnit/Util/TestSuiteIterator.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!class_exists('PHPUnit_Framework_TestSuite', FALSE)) { + +/** + * A TestSuite is a composite of Tests. It runs a collection of test cases. + * + * Here is an example using the dynamic test definition. + * + * + * addTest(new MathTest('testPass')); + * ?> + * + * + * Alternatively, a TestSuite can extract the tests to be run automatically. + * To do so you pass a ReflectionClass instance for your + * PHPUnit_Framework_TestCase class to the PHPUnit_Framework_TestSuite + * constructor. + * + * + * + * + * + * This constructor creates a suite with all the methods starting with + * "test" that take no arguments. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class PHPUnit_Framework_TestSuite implements PHPUnit_Framework_Test, PHPUnit_Framework_SelfDescribing, IteratorAggregate +{ + /** + * Enable or disable the backup and restoration of the $GLOBALS array. + * + * @var boolean + */ + protected $backupGlobals = NULL; + + /** + * Fixture that is shared between the tests of this test suite. + * + * @var mixed + */ + protected $sharedFixture; + + /** + * The name of the test suite. + * + * @var string + */ + protected $name = ''; + + /** + * The test groups of the test suite. + * + * @var array + */ + protected $groups = array(); + + /** + * The tests in the test suite. + * + * @var array + */ + protected $tests = array(); + + /** + * The number of tests in the test suite. + * + * @var integer + */ + protected $numTests = -1; + + /** + * Constructs a new TestSuite: + * + * - PHPUnit_Framework_TestSuite() constructs an empty TestSuite. + * + * - PHPUnit_Framework_TestSuite(ReflectionClass) constructs a + * TestSuite from the given class. + * + * - PHPUnit_Framework_TestSuite(ReflectionClass, String) + * constructs a TestSuite from the given class with the given + * name. + * + * - PHPUnit_Framework_TestSuite(String) either constructs a + * TestSuite from the given class (if the passed string is the + * name of an existing class) or constructs an empty TestSuite + * with the given name. + * + * @param mixed $theClass + * @param string $name + * @throws InvalidArgumentException + */ + public function __construct($theClass = '', $name = '') + { + $argumentsValid = FALSE; + + if (is_object($theClass) && + $theClass instanceof ReflectionClass) { + $argumentsValid = TRUE; + } + + else if (is_string($theClass) && $theClass !== '' + && class_exists($theClass, FALSE)) { + $argumentsValid = TRUE; + + if ($name == '') { + $name = $theClass; + } + + $theClass = new ReflectionClass($theClass); + } + + else if (is_string($theClass)) { + $this->setName($theClass); + return; + } + + if (!$argumentsValid) { + throw new InvalidArgumentException; + } + + $filename = $theClass->getFilename(); + + if (strpos($filename, 'eval()') === FALSE) { + PHPUnit_Util_Filter::addFileToFilter(realpath($filename), 'TESTS'); + } + + if ($name != '') { + $this->setName($name); + } else { + $this->setName($theClass->getName()); + } + + $constructor = $theClass->getConstructor(); + + if ($constructor !== NULL && + !$constructor->isPublic()) { + $this->addTest( + self::warning( + sprintf( + 'Class "%s" has no public constructor.', + + $theClass->getName() + ) + ) + ); + + return; + } + + $className = $theClass->getName(); + $classDocComment = $theClass->getDocComment(); + $names = array(); + $classGroups = PHPUnit_Util_Test::getGroups($classDocComment); + + foreach ($theClass->getMethods() as $method) { + if (strpos($method->getDeclaringClass()->getName(), 'PHPUnit_') !== 0) { + $methodDocComment = $method->getDocComment(); + + $this->addTestMethod( + $theClass, + $method, + PHPUnit_Util_Test::getGroups($methodDocComment, $classGroups), + $names + ); + } + } + + if (empty($this->tests)) { + $this->addTest( + self::warning( + sprintf( + 'No tests found in class "%s".', + + $theClass->getName() + ) + ) + ); + } + } + + /** + * Returns a string representation of the test suite. + * + * @return string + */ + public function toString() + { + return $this->getName(); + } + + /** + * Adds a test to the suite. + * + * @param PHPUnit_Framework_Test $test + * @param array $groups + */ + public function addTest(PHPUnit_Framework_Test $test, $groups = array()) + { + $class = new ReflectionClass($test); + + if (!$class->isAbstract()) { + $this->tests[] = $test; + $this->numTests = -1; + + if ($test instanceof PHPUnit_Framework_TestSuite && empty($groups)) { + $groups = $test->getGroups(); + } + + if (empty($groups)) { + $groups = array('__nogroup__'); + } + + foreach ($groups as $group) { + if (!isset($this->groups[$group])) { + $this->groups[$group] = array($test); + } else { + $this->groups[$group][] = $test; + } + } + } + } + + /** + * Adds the tests from the given class to the suite. + * + * @param mixed $testClass + * @throws InvalidArgumentException + */ + public function addTestSuite($testClass) + { + if (is_string($testClass) && class_exists($testClass)) { + $testClass = new ReflectionClass($testClass); + } + + if (!is_object($testClass)) { + throw new InvalidArgumentException; + } + + if ($testClass instanceof PHPUnit_Framework_TestSuite) { + $this->addTest($testClass); + } + + else if ($testClass instanceof ReflectionClass) { + $suiteMethod = FALSE; + + if (!$testClass->isAbstract()) { + if ($testClass->hasMethod(PHPUnit_Runner_BaseTestRunner::SUITE_METHODNAME)) { + $method = $testClass->getMethod( + PHPUnit_Runner_BaseTestRunner::SUITE_METHODNAME + ); + + if ($method->isStatic()) { + $this->addTest($method->invoke(NULL, $testClass->getName())); + $suiteMethod = TRUE; + } + } + } + + if (!$suiteMethod && !$testClass->isAbstract()) { + $this->addTest(new PHPUnit_Framework_TestSuite($testClass)); + } + } + + else { + throw new InvalidArgumentException; + } + } + + /** + * Wraps both addTest() and addTestSuite + * as well as the separate import statements for the user's convenience. + * + * If the named file cannot be read or there are no new tests that can be + * added, a PHPUnit_Framework_Warning will be created instead, + * leaving the current test run untouched. + * + * @param string $filename + * @param boolean $syntaxCheck + * @param array $phptOptions Array with ini settings for the php instance + * run, key being the name if the setting, + * value the ini value. + * @throws InvalidArgumentException + * @since Method available since Release 2.3.0 + * @author Stefano F. Rausch + */ + public function addTestFile($filename, $syntaxCheck = TRUE, $phptOptions = array()) + { + if (!is_string($filename)) { + throw new InvalidArgumentException; + } + + if (file_exists($filename) && substr($filename, -5) == '.phpt') { + require_once 'PHPUnit/Extensions/PhptTestCase.php'; + + $this->addTest( + new PHPUnit_Extensions_PhptTestCase($filename, $phptOptions) + ); + + return; + } + + if (!file_exists($filename)) { + $includePaths = explode(PATH_SEPARATOR, get_include_path()); + + foreach ($includePaths as $includePath) { + $file = $includePath . DIRECTORY_SEPARATOR . $filename; + + if (file_exists($file)) { + $filename = $file; + break; + } + } + } + + PHPUnit_Util_Class::collectStart(); + PHPUnit_Util_Fileloader::checkAndLoad($filename, $syntaxCheck); + $newClasses = PHPUnit_Util_Class::collectEnd(); + + $testsFound = FALSE; + + foreach ($newClasses as $className) { + $class = new ReflectionClass($className); + + if (!$class->isAbstract()) { + if ($class->hasMethod(PHPUnit_Runner_BaseTestRunner::SUITE_METHODNAME)) { + $method = $class->getMethod( + PHPUnit_Runner_BaseTestRunner::SUITE_METHODNAME + ); + + if ($method->isStatic()) { + $this->addTest($method->invoke(NULL, $className)); + + $testsFound = TRUE; + } + } + + else if ($class->implementsInterface('PHPUnit_Framework_Test')) { + $this->addTestSuite($class); + + $testsFound = TRUE; + } + } + } + + if (!$testsFound) { + $this->addTest( + new PHPUnit_Framework_Warning( + 'No tests found in file "' . $filename . '".' + ) + ); + } + + $this->numTests = -1; + } + + /** + * Wrapper for addTestFile() that adds multiple test files. + * + * @param array|Iterator $filenames + * @throws InvalidArgumentException + * @since Method available since Release 2.3.0 + */ + public function addTestFiles($filenames, $syntaxCheck = TRUE) + { + if (!(is_array($filenames) || + (is_object($filenames) && $filenames instanceof Iterator))) { + throw new InvalidArgumentException; + } + + foreach ($filenames as $filename) { + $this->addTestFile((string)$filename, $syntaxCheck); + } + } + + /** + * Counts the number of test cases that will be run by this test. + * + * @return integer + */ + public function count() + { + if ($this->numTests > -1) { + return $this->numTests; + } + + $this->numTests = 0; + + foreach ($this->tests as $test) { + $this->numTests += count($test); + } + + return $this->numTests; + } + + /** + * @param ReflectionClass $theClass + * @param string $name + * @param array $classGroups + * @return PHPUnit_Framework_Test + */ + public static function createTest(ReflectionClass $theClass, $name, array $classGroups = array()) + { + $className = $theClass->getName(); + $method = new ReflectionMethod($className, $name); + $methodDocComment = $method->getDocComment(); + + if (!$theClass->isInstantiable()) { + return self::warning( + sprintf('Cannot instantiate class "%s".', $className) + ); + } + + $constructor = $theClass->getConstructor(); + $expectedException = PHPUnit_Util_Test::getExpectedException($methodDocComment); + + if ($constructor !== NULL) { + $parameters = $constructor->getParameters(); + + // TestCase() or TestCase($name) + if (count($parameters) < 2) { + $test = new $className; + } + + // TestCase($name, $data) + else { + $data = PHPUnit_Util_Test::getProvidedData($className, $name, $methodDocComment); + $groups = PHPUnit_Util_Test::getGroups($methodDocComment, $classGroups); + + if (is_array($data) || $data instanceof Iterator) { + $test = new PHPUnit_Framework_TestSuite( + $className . '::' . $name + ); + + foreach ($data as $_dataName => $_data) { + $_test = new $className($name, $_data, $_dataName); + + if ($_test instanceof PHPUnit_Framework_TestCase && + isset($expectedException)) { + $_test->setExpectedException( + $expectedException['class'], + $expectedException['message'], + $expectedException['code'] + ); + } + + $test->addTest($_test, $groups); + } + } else { + $test = new $className; + } + } + } + + if ($test instanceof PHPUnit_Framework_TestCase) { + $test->setName($name); + + if (isset($expectedException)) { + $test->setExpectedException( + $expectedException['class'], + $expectedException['message'], + $expectedException['code'] + ); + } + } + + return $test; + } + + /** + * Creates a default TestResult object. + * + * @return PHPUnit_Framework_TestResult + */ + protected function createResult() + { + return new PHPUnit_Framework_TestResult; + } + + /** + * Returns the name of the suite. + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Returns the test groups of the suite. + * + * @return array + * @since Method available since Release 3.2.0 + */ + public function getGroups() + { + return array_keys($this->groups); + } + + /** + * Runs the tests and collects their result in a TestResult. + * + * @param PHPUnit_Framework_TestResult $result + * @param mixed $filter + * @param array $groups + * @param array $excludeGroups + * @return PHPUnit_Framework_TestResult + * @throws InvalidArgumentException + */ + public function run(PHPUnit_Framework_TestResult $result = NULL, $filter = FALSE, array $groups = array(), array $excludeGroups = array()) + { + if ($result === NULL) { + $result = $this->createResult(); + } + + try { + $this->setUp(); + } + + catch (PHPUnit_Framework_SkippedTestSuiteError $e) { + $numTests = count($this); + + for ($i = 0; $i < $numTests; $i++) { + $result->addFailure($this, $e, 0); + } + + return $result; + } + + $result->startTestSuite($this); + + if (empty($groups)) { + $tests = $this->tests; + } else { + $tests = new SplObjectStorage; + + foreach ($groups as $group) { + if (isset($this->groups[$group])) { + foreach ($this->groups[$group] as $test) { + $tests->attach($test); + } + } + } + } + + foreach ($tests as $test) { + if ($result->shouldStop()) { + break; + } + + if ($test instanceof PHPUnit_Framework_TestSuite) { + $test->setBackupGlobals($this->backupGlobals); + $test->setSharedFixture($this->sharedFixture); + $test->run($result, $filter, $groups, $excludeGroups); + } else { + $runTest = TRUE; + + if ($filter !== FALSE ) { + $tmp = PHPUnit_Util_Test::describe($test, FALSE); + + if ($tmp[0] != '') { + $name = join('::', $tmp); + } else { + $name = $tmp[1]; + } + + if (preg_match($filter, $name) == 0) { + $runTest = FALSE; + } + } + + if ($runTest && !empty($excludeGroups)) { + foreach ($this->groups as $_group => $_tests) { + if (in_array($_group, $excludeGroups)) { + foreach ($_tests as $_test) { + if ($test === $_test) { + $runTest = FALSE; + break 2; + } + } + } + } + } + + if ($runTest) { + if ($test instanceof PHPUnit_Framework_TestCase) { + $test->setBackupGlobals($this->backupGlobals); + $test->setSharedFixture($this->sharedFixture); + } + + $this->runTest($test, $result); + } + } + } + + $result->endTestSuite($this); + $this->tearDown(); + + return $result; + } + + /** + * Runs a test. + * + * @param PHPUnit_Framework_Test $test + * @param PHPUnit_Framework_TestResult $testResult + */ + public function runTest(PHPUnit_Framework_Test $test, PHPUnit_Framework_TestResult $result) + { + $test->run($result); + } + + /** + * Sets the name of the suite. + * + * @param string + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * Returns the test at the given index. + * + * @param integer + * @return PHPUnit_Framework_Test + */ + public function testAt($index) + { + if (isset($this->tests[$index])) { + return $this->tests[$index]; + } else { + return FALSE; + } + } + + /** + * Returns the tests as an enumeration. + * + * @return array + */ + public function tests() + { + return $this->tests; + } + + /** + * Mark the test suite as skipped. + * + * @param string $message + * @throws PHPUnit_Framework_SkippedTestSuiteError + * @since Method available since Release 3.0.0 + */ + public function markTestSuiteSkipped($message = '') + { + throw new PHPUnit_Framework_SkippedTestSuiteError($message); + } + + /** + * @param ReflectionClass $class + * @param ReflectionMethod $method + * @param string $groups + * @param array $names + */ + protected function addTestMethod(ReflectionClass $class, ReflectionMethod $method, array $groups, array &$names) + { + $name = $method->getName(); + + if (in_array($name, $names)) { + return; + } + + if ($this->isPublicTestMethod($method)) { + $names[] = $name; + + $test = self::createTest($class, $name, $groups); + + $this->addTest($test, $groups); + } + + else if ($this->isTestMethod($method)) { + $this->addTest( + self::warning( + sprintf( + 'Test method "%s" is not public.', + + $name + ) + ) + ); + } + } + + /** + * @param ReflectionMethod $method + * @return boolean + */ + public static function isPublicTestMethod(ReflectionMethod $method) + { + return (self::isTestMethod($method) && $method->isPublic()); + } + + /** + * @param ReflectionMethod $method + * @return boolean + */ + public static function isTestMethod(ReflectionMethod $method) + { + if (strpos($method->name, 'test') === 0) { + return TRUE; + } + + // @scenario on TestCase::testMethod() + // @test on TestCase::testMethod() + return strpos($method->getDocComment(), '@test') !== FALSE || + strpos($method->getDocComment(), '@scenario') !== FALSE; + } + + /** + * @param string $message + * @return PHPUnit_Framework_Warning + */ + protected static function warning($message) + { + return new PHPUnit_Framework_Warning($message); + } + + /** + * @param boolean $backupGlobals + * @since Method available since Release 3.3.0 + */ + public function setBackupGlobals($backupGlobals) + { + if (is_null($this->backupGlobals) && is_bool($backupGlobals)) { + $this->backupGlobals = $backupGlobals; + } + } + + /** + * Sets the shared fixture for the tests of this test suite. + * + * @param mixed $sharedFixture + * @since Method available since Release 3.1.0 + */ + public function setSharedFixture($sharedFixture) + { + $this->sharedFixture = $sharedFixture; + } + + /** + * Returns an iterator for this test suite. + * + * @return RecursiveIteratorIterator + * @since Method available since Release 3.1.0 + */ + public function getIterator() + { + return new RecursiveIteratorIterator( + new PHPUnit_Util_TestSuiteIterator($this) + ); + } + + /** + * Template Method that is called before the tests + * of this test suite are run. + * + * @since Method available since Release 3.1.0 + */ + protected function setUp() + { + } + + /** + * Template Method that is called after the tests + * of this test suite have finished running. + * + * @since Method available since Release 3.1.0 + */ + protected function tearDown() + { + } +} + +} +?> diff --git a/tests/PHPUnit/Framework/Warning.php b/tests/PHPUnit/Framework/Warning.php new file mode 100755 index 00000000..ef9448bf --- /dev/null +++ b/tests/PHPUnit/Framework/Warning.php @@ -0,0 +1,100 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +if (!class_exists('PHPUnit_Framework_Warning', FALSE)) { + +/** + * A warning. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class PHPUnit_Framework_Warning extends PHPUnit_Framework_TestCase +{ + /** + * @var string + */ + protected $message = ''; + + /** + * @param string $message + */ + public function __construct($message = '') + { + $this->message = $message; + parent::__construct('Warning'); + } + + /** + */ + protected function runTest() + { + $this->fail($this->message); + } + + /** + * @return string + * @since Method available since Release 3.0.0 + */ + public function getMessage() + { + return $this->message; + } +} + +} +?> diff --git a/tests/PHPUnit/Runner/BaseTestRunner.php b/tests/PHPUnit/Runner/BaseTestRunner.php new file mode 100755 index 00000000..32bd3b13 --- /dev/null +++ b/tests/PHPUnit/Runner/BaseTestRunner.php @@ -0,0 +1,304 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Runner/StandardTestSuiteLoader.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Base class for all test runners. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + * @abstract + */ +abstract class PHPUnit_Runner_BaseTestRunner implements PHPUnit_Framework_TestListener +{ + const STATUS_PASSED = 0; + const STATUS_SKIPPED = 1; + const STATUS_INCOMPLETE = 2; + const STATUS_FAILURE = 3; + const STATUS_ERROR = 4; + const SUITE_METHODNAME = 'suite'; + + /** + * An error occurred. + * + * @param PHPUnit_Framework_Test $test + * @param Exception $e + * @param float $time + */ + public function addError(PHPUnit_Framework_Test $test, Exception $e, $time) + { + $this->testFailed(self::STATUS_ERROR, $test, $e); + } + + /** + * A failure occurred. + * + * @param PHPUnit_Framework_Test $test + * @param PHPUnit_Framework_AssertionFailedError $e + * @param float $time + */ + public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time) + { + $this->testFailed(self::STATUS_FAILURE, $test, $e); + } + + /** + * Incomplete test. + * + * @param PHPUnit_Framework_Test $test + * @param Exception $e + * @param float $time + */ + public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time) + { + $this->testFailed(self::STATUS_INCOMPLETE, $test, $e); + } + + /** + * Skipped test. + * + * @param PHPUnit_Framework_Test $test + * @param Exception $e + * @param float $time + * @since Method available since Release 3.0.0 + */ + public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time) + { + $this->testFailed(self::STATUS_SKIPPED, $test, $e); + } + + /** + * A testsuite started. + * + * @param PHPUnit_Framework_TestSuite $suite + * @since Method available since Release 2.2.0 + */ + public function startTestSuite(PHPUnit_Framework_TestSuite $suite) + { + } + + /** + * A testsuite ended. + * + * @param PHPUnit_Framework_TestSuite $suite + * @since Method available since Release 2.2.0 + */ + public function endTestSuite(PHPUnit_Framework_TestSuite $suite) + { + } + + /** + * A test started. + * + * @param PHPUnit_Framework_Test $test + */ + public function startTest(PHPUnit_Framework_Test $test) + { + $this->testStarted($test->getName()); + } + + /** + * A test ended. + * + * @param PHPUnit_Framework_Test $test + * @param float $time + */ + public function endTest(PHPUnit_Framework_Test $test, $time) + { + $this->testEnded($test->getName()); + } + + /** + * Returns the loader to be used. + * + * @return PHPUnit_Runner_TestSuiteLoader + */ + public function getLoader() + { + return new PHPUnit_Runner_StandardTestSuiteLoader; + } + + /** + * Returns the Test corresponding to the given suite. + * This is a template method, subclasses override + * the runFailed() and clearStatus() methods. + * + * @param string $suiteClassName + * @param string $suiteClassFile + * @param boolean $syntaxCheck + * @return PHPUnit_Framework_Test + */ + public function getTest($suiteClassName, $suiteClassFile = '', $syntaxCheck = TRUE) + { + if (is_dir($suiteClassName) && !is_file($suiteClassName . '.php') && empty($suiteClassFile)) { + $testCollector = new PHPUnit_Runner_IncludePathTestCollector( + array($suiteClassName) + ); + + $suite = new PHPUnit_Framework_TestSuite($suiteClassName); + $suite->addTestFiles($testCollector->collectTests(), $syntaxCheck); + + return $suite; + } + + try { + $testClass = $this->loadSuiteClass( + $suiteClassName, $suiteClassFile, $syntaxCheck + ); + } + + catch (Exception $e) { + $this->runFailed($e->getMessage()); + return NULL; + } + + try { + $suiteMethod = $testClass->getMethod(self::SUITE_METHODNAME); + + if (!$suiteMethod->isStatic()) { + $this->runFailed( + 'suite() method must be static.' + ); + + return NULL; + } + + try { + $test = $suiteMethod->invoke(NULL, $testClass->getName()); + } + + catch (ReflectionException $e) { + $this->runFailed( + sprintf( + "Failed to invoke suite() method.\n%s", + + $e->getMessage() + ) + ); + + return NULL; + } + } + + catch (ReflectionException $e) { + $test = new PHPUnit_Framework_TestSuite($testClass); + } + + $this->clearStatus(); + + return $test; + } + + /** + * Override to define how to handle a failed loading of + * a test suite. + * + * @param string $message + */ + abstract protected function runFailed($message); + + /** + * Returns the loaded ReflectionClass for a suite name. + * + * @param string $suiteClassName + * @param string $suiteClassFile + * @param boolean $syntaxCheck + * @return ReflectionClass + */ + protected function loadSuiteClass($suiteClassName, $suiteClassFile = '', $syntaxCheck = TRUE) + { + $loader = $this->getLoader(); + + if ($loader instanceof PHPUnit_Runner_StandardTestSuiteLoader) { + return $loader->load($suiteClassName, $suiteClassFile, $syntaxCheck); + } else { + return $loader->load($suiteClassName, $suiteClassFile); + } + } + + /** + * Clears the status message. + * + */ + protected function clearStatus() + { + } + + /** + * A test started. + * + * @param string $testName + */ + abstract public function testStarted($testName); + + /** + * A test ended. + * + * @param string $testName + */ + abstract public function testEnded($testName); + + /** + * A test failed. + * + * @param integer $status + * @param PHPUnit_Framework_Test $test + * @param PHPUnit_Framework_AssertionFailedError $e + */ + abstract public function testFailed($status, PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e); +} +?> diff --git a/tests/PHPUnit/Runner/IncludePathTestCollector.php b/tests/PHPUnit/Runner/IncludePathTestCollector.php new file mode 100755 index 00000000..a7f14293 --- /dev/null +++ b/tests/PHPUnit/Runner/IncludePathTestCollector.php @@ -0,0 +1,160 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.1.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Runner/TestCollector.php'; +require_once 'PHPUnit/Util/FilterIterator.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * A test collector that collects tests from one or more directories + * recursively. If no directories are specified, the include_path is searched. + * + * + * $testCollector = new PHPUnit_Runner_IncludePathTestCollector( + * array('/path/to/*Test.php files') + * ); + * + * $suite = new PHPUnit_Framework_TestSuite('My Test Suite'); + * $suite->addTestFiles($testCollector->collectTests()); + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.1.0 + */ +class PHPUnit_Runner_IncludePathTestCollector implements PHPUnit_Runner_TestCollector +{ + /** + * @var string + */ + protected $filterIterator; + + /** + * @var array + */ + protected $paths; + + /** + * @var string + */ + protected $suffix; + + /** + * @param array $paths + * @param string $suffix + */ + public function __construct(array $paths = array(), $suffix = 'Test.php') + { + if (!empty($paths)) { + $this->paths = $paths; + } else { + $this->paths = explode(PATH_SEPARATOR, get_include_path()); + } + + $this->suffix = $suffix; + } + + /** + * @return array + */ + public function collectTests() + { + $pathIterator = new AppendIterator; + $result = array(); + + foreach ($this->paths as $path) { + $pathIterator->append( + new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($path) + ) + ); + } + + $filterIterator = new PHPUnit_Util_FilterIterator( + $pathIterator, $this->suffix + ); + + if ($this->filterIterator !== NULL) { + $class = new ReflectionClass($this->filterIterator); + $filterIterator = $class->newInstance($filterIterator); + } + + return $filterIterator; + } + + /** + * Adds a FilterIterator to filter the source files to be collected. + * + * @param string $filterIterator + * @throws InvalidArgumentException + */ + public function setFilterIterator($filterIterator) + { + if (is_string($filterIterator) && class_exists($filterIterator)) { + try { + $class = new ReflectionClass($filterIterator); + + if ($class->isSubclassOf('FilterIterator')) { + $this->filterIterator = $filterIterator; + } + } + + catch (ReflectionException $e) { + throw new InvalidArgumentException; + } + } else { + throw new InvalidArgumentException; + } + } +} +?> diff --git a/tests/PHPUnit/Runner/StandardTestSuiteLoader.php b/tests/PHPUnit/Runner/StandardTestSuiteLoader.php new file mode 100755 index 00000000..ac7ddfcf --- /dev/null +++ b/tests/PHPUnit/Runner/StandardTestSuiteLoader.php @@ -0,0 +1,166 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Runner/TestSuiteLoader.php'; +require_once 'PHPUnit/Util/Class.php'; +require_once 'PHPUnit/Util/Fileloader.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * The standard test suite loader. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class PHPUnit_Runner_StandardTestSuiteLoader implements PHPUnit_Runner_TestSuiteLoader +{ + /** + * @param string $suiteClassName + * @param string $suiteClassFile + * @param boolean $syntaxCheck + * @return ReflectionClass + * @throws RuntimeException + */ + public function load($suiteClassName, $suiteClassFile = '', $syntaxCheck = TRUE) + { + $suiteClassName = str_replace('.php', '', $suiteClassName); + + if (empty($suiteClassFile)) { + $suiteClassFile = str_replace(array('_', '\\'), DIRECTORY_SEPARATOR, $suiteClassName) . '.php'; + } + + if (!class_exists($suiteClassName, FALSE)) { + if (!file_exists($suiteClassFile)) { + $includePaths = explode(PATH_SEPARATOR, get_include_path()); + + foreach ($includePaths as $includePath) { + $file = $includePath . DIRECTORY_SEPARATOR . $suiteClassFile; + + if (file_exists($file)) { + $suiteClassFile = $file; + break; + } + } + } + + PHPUnit_Util_Class::collectStart(); + PHPUnit_Util_Fileloader::checkAndLoad($suiteClassFile, $syntaxCheck); + $loadedClasses = PHPUnit_Util_Class::collectEnd(); + } + + if (!class_exists($suiteClassName, FALSE) && !empty($loadedClasses)) { + $offset = 0 - strlen($suiteClassName); + + foreach ($loadedClasses as $loadedClass) { + if (substr($loadedClass, $offset) === $suiteClassName) { + $suiteClassName = $loadedClass; + break; + } + } + } + + if (!class_exists($suiteClassName, FALSE) && !empty($loadedClasses)) { + $testCaseClass = 'PHPUnit_Framework_TestCase'; + + foreach ($loadedClasses as $loadedClass) { + $class = new ReflectionClass($loadedClass); + + if ($class->isSubclassOf($testCaseClass)) { + $suiteClassName = $loadedClass; + $testCaseClass = $loadedClass; + + if ($class->getFileName() == realpath($suiteClassFile)) { + break; + } + } + + if ($class->hasMethod('suite')) { + $method = $class->getMethod('suite'); + + if (!$method->isAbstract() && $method->isPublic() && $method->isStatic()) { + $suiteClassName = $loadedClass; + break; + } + } + } + } + + if (class_exists($suiteClassName, FALSE)) { + $class = new ReflectionClass($suiteClassName); + + if ($class->getFileName() == realpath($suiteClassFile)) { + return $class; + } + } + + throw new RuntimeException( + sprintf( + 'Class %s could not be found in %s.', + + $suiteClassName, + $suiteClassFile + ) + ); + } + + /** + * @param ReflectionClass $aClass + * @return ReflectionClass + */ + public function reload(ReflectionClass $aClass) + { + return $aClass; + } +} +?> diff --git a/tests/PHPUnit/Runner/TestCollector.php b/tests/PHPUnit/Runner/TestCollector.php new file mode 100755 index 00000000..cd1f63b1 --- /dev/null +++ b/tests/PHPUnit/Runner/TestCollector.php @@ -0,0 +1,71 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Collects Test class names to be presented + * by the TestSelector. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 2.0.0 + */ +interface PHPUnit_Runner_TestCollector +{ + /** + * @return array + */ + public function collectTests(); +} +?> diff --git a/tests/PHPUnit/Runner/TestSuiteLoader.php b/tests/PHPUnit/Runner/TestSuiteLoader.php new file mode 100755 index 00000000..f8a83e79 --- /dev/null +++ b/tests/PHPUnit/Runner/TestSuiteLoader.php @@ -0,0 +1,78 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * An interface to define how a test suite should be loaded. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Interface available since Release 2.0.0 + */ +interface PHPUnit_Runner_TestSuiteLoader +{ + /** + * @param string $suiteClassName + * @param string $suiteClassFile + * @return ReflectionClass + */ + public function load($suiteClassName, $suiteClassFile = ''); + + /** + * @param ReflectionClass $aClass + * @return ReflectionClass + */ + public function reload(ReflectionClass $aClass); +} +?> diff --git a/tests/PHPUnit/Runner/Version.php b/tests/PHPUnit/Runner/Version.php new file mode 100755 index 00000000..d7e85c1a --- /dev/null +++ b/tests/PHPUnit/Runner/Version.php @@ -0,0 +1,83 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * This class defines the current version of PHPUnit. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class PHPUnit_Runner_Version +{ + /** + * Returns the current version of PHPUnit. + * + * @return string + */ + public static function id() + { + return '3.3.17'; + } + + /** + * @return string + */ + public static function getVersionString() + { + return 'PHPUnit 3.3.17 by Sebastian Bergmann.'; + } +} +?> diff --git a/tests/PHPUnit/Samples/BankAccount/BankAccount.php b/tests/PHPUnit/Samples/BankAccount/BankAccount.php new file mode 100755 index 00000000..02cab9ad --- /dev/null +++ b/tests/PHPUnit/Samples/BankAccount/BankAccount.php @@ -0,0 +1,121 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.3.0 + */ + +class BankAccountException extends RuntimeException {} + +/** + * A bank account. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.3.0 + */ +class BankAccount +{ + /** + * The bank account's balance. + * + * @var float + */ + protected $balance = 0; + + /** + * Returns the bank account's balance. + * + * @return float + */ + public function getBalance() + { + return $this->balance; + } + + /** + * Sets the bank account's balance. + * + * @param float $balance + * @throws BankAccountException + */ + protected function setBalance($balance) + { + if ($balance >= 0) { + $this->balance = $balance; + } else { + throw new BankAccountException; + } + } + + /** + * Deposits an amount of money to the bank account. + * + * @param float $balance + * @throws BankAccountException + */ + public function depositMoney($balance) + { + $this->setBalance($this->getBalance() + $balance); + + return $this->getBalance(); + } + + /** + * Withdraws an amount of money from the bank account. + * + * @param float $balance + * @throws BankAccountException + */ + public function withdrawMoney($balance) + { + $this->setBalance($this->getBalance() - $balance); + + return $this->getBalance(); + } +} +?> diff --git a/tests/PHPUnit/Samples/BankAccount/BankAccountTest.php b/tests/PHPUnit/Samples/BankAccount/BankAccountTest.php new file mode 100755 index 00000000..b6454ebd --- /dev/null +++ b/tests/PHPUnit/Samples/BankAccount/BankAccountTest.php @@ -0,0 +1,138 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.3.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; +require_once 'BankAccount.php'; + +/** + * Tests for the BankAccount class. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.3.0 + */ +class BankAccountTest extends PHPUnit_Framework_TestCase +{ + protected $ba; + + protected function setUp() + { + $this->ba = new BankAccount; + } + + /** + * @covers BankAccount::getBalance + * @group balanceIsInitiallyZero + * @group specification + */ + public function testBalanceIsInitiallyZero() + { + $this->assertEquals(0, $this->ba->getBalance()); + } + + /** + * @covers BankAccount::withdrawMoney + * @group balanceCannotBecomeNegative + * @group specification + */ + public function testBalanceCannotBecomeNegative() + { + try { + $this->ba->withdrawMoney(1); + } + + catch (BankAccountException $e) { + $this->assertEquals(0, $this->ba->getBalance()); + + return; + } + + $this->fail(); + } + + /** + * @covers BankAccount::depositMoney + * @group balanceCannotBecomeNegative + * @group specification + */ + public function testBalanceCannotBecomeNegative2() + { + try { + $this->ba->depositMoney(-1); + } + + catch (BankAccountException $e) { + $this->assertEquals(0, $this->ba->getBalance()); + + return; + } + + $this->fail(); + } + + /** + * @covers BankAccount::getBalance + * @covers BankAccount::depositMoney + * @covers BankAccount::withdrawMoney + * @group balanceCannotBecomeNegative + */ +/* + public function testDepositWithdrawMoney() + { + $this->assertEquals(0, $this->ba->getBalance()); + $this->ba->depositMoney(1); + $this->assertEquals(1, $this->ba->getBalance()); + $this->ba->withdrawMoney(1); + $this->assertEquals(0, $this->ba->getBalance()); + } +*/ +} +?> diff --git a/tests/PHPUnit/Samples/BankAccountDB/BankAccount.php b/tests/PHPUnit/Samples/BankAccountDB/BankAccount.php new file mode 100755 index 00000000..74c665ee --- /dev/null +++ b/tests/PHPUnit/Samples/BankAccountDB/BankAccount.php @@ -0,0 +1,210 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +class BankAccountException extends RuntimeException {} + +/** + * A bank account. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class BankAccount +{ + /** + * The bank account's balance. + * + * @var float + */ + protected $balance = 0; + + /** + * The bank account's number. + * + * @var float + */ + protected $accountNumber = 0; + + /** + * The PDO connection used to store and retrieve bank account information. + * + * @var PDO + */ + protected $pdo; + + public function __construct($accountNumber, PDO $pdo) + { + $this->accountNumber = $accountNumber; + $this->pdo = $pdo; + + $this->loadAccount(); + } + + /** + * Returns the bank account's balance. + * + * @return float + */ + public function getBalance() + { + return $this->balance; + } + + /** + * Sets the bank account's balance. + * + * @param float $balance + * @throws BankAccountException + */ + protected function setBalance($balance) + { + if ($balance >= 0) { + $this->balance = $balance; + $this->updateAccount(); + } else { + throw new BankAccountException; + } + } + + /** + * Returns the bank account's number. + * + * @return float + */ + public function getAccountNumber() + { + return $this->accountNumber; + } + + /** + * Deposits an amount of money to the bank account. + * + * @param float $balance + * @throws BankAccountException + */ + public function depositMoney($balance) + { + $this->setBalance($this->getBalance() + $balance); + + return $this->getBalance(); + } + + /** + * Withdraws an amount of money from the bank account. + * + * @param float $balance + * @throws BankAccountException + */ + public function withdrawMoney($balance) + { + $this->setBalance($this->getBalance() - $balance); + + return $this->getBalance(); + } + + /** + * Loads account information from the database. + */ + protected function loadAccount() + { + $query = "SELECT * FROM bank_account WHERE account_number = ?"; + + $statement = $this->pdo->prepare($query); + + $statement->execute(array($this->accountNumber)); + + if ($bankAccountInfo = $statement->fetch(PDO::FETCH_ASSOC)) + { + $this->balance = $bankAccountInfo['balance']; + } + else + { + $this->balance = 0; + $this->addAccount(); + } + } + + /** + * Saves account information to the database. + */ + protected function updateAccount() + { + $query = "UPDATE bank_account SET balance = ? WHERE account_number = ?"; + + $statement = $this->pdo->prepare($query); + $statement->execute(array($this->balance, $this->accountNumber)); + } + + /** + * Adds account information to the database. + */ + protected function addAccount() + { + $query = "INSERT INTO bank_account (balance, account_number) VALUES(?, ?)"; + + $statement = $this->pdo->prepare($query); + $statement->execute(array($this->balance, $this->accountNumber)); + } + + static public function createTable(PDO $pdo) + { + $query = " + CREATE TABLE bank_account ( + account_number VARCHAR(17) PRIMARY KEY, + balance DECIMAL(9,2) NOT NULL DEFAULT 0 + ); + "; + + $pdo->query($query); + } +} +?> diff --git a/tests/PHPUnit/Samples/BankAccountDB/BankAccountDBTest.php b/tests/PHPUnit/Samples/BankAccountDB/BankAccountDBTest.php new file mode 100755 index 00000000..56cb692c --- /dev/null +++ b/tests/PHPUnit/Samples/BankAccountDB/BankAccountDBTest.php @@ -0,0 +1,150 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Extensions/Database/TestCase.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php'; + +require_once 'BankAccount.php'; + +/** + * Tests for the BankAccount class. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class BankAccountDBTest extends PHPUnit_Extensions_Database_TestCase +{ + protected $pdo; + + public function __construct() + { + $this->pdo = new PDO('sqlite::memory:'); + BankAccount::createTable($this->pdo); + } + + /** + * Returns the test database connection. + * + * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection + */ + protected function getConnection() + { + return $this->createDefaultDBConnection($this->pdo, 'sqlite'); + } + + protected function getDataSet() + { + return $this->createFlatXMLDataSet(dirname(__FILE__).'/_files/bank-account-seed.xml'); + } + + public function testNewAccountBalanceIsInitiallyZero() + { + $bank_account = new BankAccount('12345678912345678', $this->pdo); + $this->assertEquals(0, $bank_account->getBalance()); + } + + public function testOldAccountInfoInitiallySet() + { + $bank_account = new BankAccount('15934903649620486', $this->pdo); + $this->assertEquals(100, $bank_account->getBalance()); + $this->assertEquals('15934903649620486', $bank_account->getAccountNumber()); + + $bank_account = new BankAccount('15936487230215067', $this->pdo); + $this->assertEquals(1216, $bank_account->getBalance()); + $this->assertEquals('15936487230215067', $bank_account->getAccountNumber()); + + $bank_account = new BankAccount('12348612357236185', $this->pdo); + $this->assertEquals(89, $bank_account->getBalance()); + $this->assertEquals('12348612357236185', $bank_account->getAccountNumber()); + } + + public function testAccountBalanceDeposits() + { + $bank_account = new BankAccount('15934903649620486', $this->pdo); + $bank_account->depositMoney(100); + + $bank_account = new BankAccount('15936487230215067', $this->pdo); + $bank_account->depositMoney(230); + + $bank_account = new BankAccount('12348612357236185', $this->pdo); + $bank_account->depositMoney(24); + + $xml_dataset = $this->createFlatXMLDataSet(dirname(__FILE__).'/_files/bank-account-after-deposits.xml'); + $this->assertDataSetsEqual($xml_dataset, $this->getConnection()->createDataSet()); + } + + public function testAccountBalanceWithdrawals() + { + $bank_account = new BankAccount('15934903649620486', $this->pdo); + $bank_account->withdrawMoney(100); + + $bank_account = new BankAccount('15936487230215067', $this->pdo); + $bank_account->withdrawMoney(230); + + $bank_account = new BankAccount('12348612357236185', $this->pdo); + $bank_account->withdrawMoney(24); + + $xml_dataset = $this->createFlatXMLDataSet(dirname(__FILE__).'/_files/bank-account-after-withdrawals.xml'); + $this->assertDataSetsEqual($xml_dataset, $this->getConnection()->createDataSet()); + } + + public function testNewAccountCreation() + { + $bank_account = new BankAccount('12345678912345678', $this->pdo); + + $xml_dataset = $this->createFlatXMLDataSet(dirname(__FILE__).'/_files/bank-account-after-new-account.xml'); + $this->assertDataSetsEqual($xml_dataset, $this->getConnection()->createDataSet()); + } + /* + */ +} +?> diff --git a/tests/PHPUnit/Samples/BankAccountDB/BankAccountDBTestMySQL.php b/tests/PHPUnit/Samples/BankAccountDB/BankAccountDBTestMySQL.php new file mode 100755 index 00000000..d3700c59 --- /dev/null +++ b/tests/PHPUnit/Samples/BankAccountDB/BankAccountDBTestMySQL.php @@ -0,0 +1,150 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Extensions/Database/TestCase.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php'; + +require_once 'BankAccount.php'; + +/** + * Tests for the BankAccount class. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class BankAccountDBTestMySQL extends PHPUnit_Extensions_Database_TestCase +{ + protected $pdo; + + public function __construct() + { + $this->pdo = new PDO('mysql:host=localhost;dbname=test', 'root', 'selkirk'); + BankAccount::createTable($this->pdo); + } + + /** + * Returns the test database connection. + * + * @return PHPUnit_Extensions_Database_DB_IDatabaseConnection + */ + protected function getConnection() + { + return $this->createDefaultDBConnection($this->pdo, 'test'); + } + + protected function getDataSet() + { + return $this->createFlatXMLDataSet(dirname(__FILE__).'/_files/bank-account-seed.xml'); + } + + public function testNewAccountBalanceIsInitiallyZero() + { + $bank_account = new BankAccount('12345678912345678', $this->pdo); + $this->assertEquals(0, $bank_account->getBalance()); + } + + public function testOldAccountInfoInitiallySet() + { + $bank_account = new BankAccount('15934903649620486', $this->pdo); + $this->assertEquals(100, $bank_account->getBalance()); + $this->assertEquals('15934903649620486', $bank_account->getAccountNumber()); + + $bank_account = new BankAccount('15936487230215067', $this->pdo); + $this->assertEquals(1216, $bank_account->getBalance()); + $this->assertEquals('15936487230215067', $bank_account->getAccountNumber()); + + $bank_account = new BankAccount('12348612357236185', $this->pdo); + $this->assertEquals(89, $bank_account->getBalance()); + $this->assertEquals('12348612357236185', $bank_account->getAccountNumber()); + } + + public function testAccountBalanceDeposits() + { + $bank_account = new BankAccount('15934903649620486', $this->pdo); + $bank_account->depositMoney(100); + + $bank_account = new BankAccount('15936487230215067', $this->pdo); + $bank_account->depositMoney(230); + + $bank_account = new BankAccount('12348612357236185', $this->pdo); + $bank_account->depositMoney(24); + + $xml_dataset = $this->createFlatXMLDataSet(dirname(__FILE__).'/_files/bank-account-after-deposits.xml'); + $this->assertDataSetsEqual($xml_dataset, $this->getConnection()->createDataSet()); + } + + public function testAccountBalanceWithdrawals() + { + $bank_account = new BankAccount('15934903649620486', $this->pdo); + $bank_account->withdrawMoney(100); + + $bank_account = new BankAccount('15936487230215067', $this->pdo); + $bank_account->withdrawMoney(230); + + $bank_account = new BankAccount('12348612357236185', $this->pdo); + $bank_account->withdrawMoney(24); + + $xml_dataset = $this->createFlatXMLDataSet(dirname(__FILE__).'/_files/bank-account-after-withdrawals.xml'); + $this->assertDataSetsEqual($xml_dataset, $this->getConnection()->createDataSet()); + } + + public function testNewAccountCreation() + { + $bank_account = new BankAccount('12345678912345678', $this->pdo); + + $xml_dataset = $this->createFlatXMLDataSet(dirname(__FILE__).'/_files/bank-account-after-new-account.xml'); + $this->assertDataSetsEqual($xml_dataset, $this->getConnection()->createDataSet()); + } + /* + */ +} +?> diff --git a/tests/PHPUnit/Samples/BankAccountDB/_files/bank-account-after-deposits.xml b/tests/PHPUnit/Samples/BankAccountDB/_files/bank-account-after-deposits.xml new file mode 100755 index 00000000..ab4f178c --- /dev/null +++ b/tests/PHPUnit/Samples/BankAccountDB/_files/bank-account-after-deposits.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/tests/PHPUnit/Samples/BankAccountDB/_files/bank-account-after-new-account.xml b/tests/PHPUnit/Samples/BankAccountDB/_files/bank-account-after-new-account.xml new file mode 100755 index 00000000..67517ab4 --- /dev/null +++ b/tests/PHPUnit/Samples/BankAccountDB/_files/bank-account-after-new-account.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/tests/PHPUnit/Samples/BankAccountDB/_files/bank-account-after-withdrawals.xml b/tests/PHPUnit/Samples/BankAccountDB/_files/bank-account-after-withdrawals.xml new file mode 100755 index 00000000..bc1c0b68 --- /dev/null +++ b/tests/PHPUnit/Samples/BankAccountDB/_files/bank-account-after-withdrawals.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/tests/PHPUnit/Samples/BankAccountDB/_files/bank-account-seed.xml b/tests/PHPUnit/Samples/BankAccountDB/_files/bank-account-seed.xml new file mode 100755 index 00000000..deb2eb98 --- /dev/null +++ b/tests/PHPUnit/Samples/BankAccountDB/_files/bank-account-seed.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/tests/PHPUnit/Samples/BowlingGame/BowlingGame.php b/tests/PHPUnit/Samples/BowlingGame/BowlingGame.php new file mode 100755 index 00000000..694d07cc --- /dev/null +++ b/tests/PHPUnit/Samples/BowlingGame/BowlingGame.php @@ -0,0 +1,107 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +class BowlingGame +{ + protected $rolls = array(); + + public function roll($pins) + { + $this->rolls[] = $pins; + } + + protected function isSpare($frameIndex) + { + return $this->sumOfPinsInFrame($frameIndex) == 10; + } + + protected function isStrike($frameIndex) + { + return $this->rolls[$frameIndex] == 10; + } + + protected function sumOfPinsInFrame($frameIndex) + { + return $this->rolls[$frameIndex] + + $this->rolls[$frameIndex + 1]; + } + + protected function spareBonus($frameIndex) + { + return $this->rolls[$frameIndex + 2]; + } + + protected function strikeBonus($frameIndex) + { + return $this->rolls[$frameIndex + 1] + + $this->rolls[$frameIndex + 2]; + } + + public function score() + { + $score = 0; + $frameIndex = 0; + + for ($frame = 0; $frame < 10; $frame++) { + if ($this->isStrike($frameIndex)) { + $score += 10 + $this->strikeBonus($frameIndex); + $frameIndex++; + } + + else if ($this->isSpare($frameIndex)) { + $score += 10 + $this->spareBonus($frameIndex); + $frameIndex += 2; + } + + else { + $score += $this->sumOfPinsInFrame($frameIndex); + $frameIndex += 2; + } + } + + return $score; + } +} diff --git a/tests/PHPUnit/Samples/BowlingGame/BowlingGameSpec.php b/tests/PHPUnit/Samples/BowlingGame/BowlingGameSpec.php new file mode 100755 index 00000000..416b7bdc --- /dev/null +++ b/tests/PHPUnit/Samples/BowlingGame/BowlingGameSpec.php @@ -0,0 +1,183 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Extensions/Story/TestCase.php'; +require_once 'BowlingGame.php'; + +class BowlingGameSpec extends PHPUnit_Extensions_Story_TestCase +{ + /** + * @scenario + */ + public function scoreForGutterGameIs0() + { + $this->given('New game') + ->then('Score should be', 0); + } + + /** + * @scenario + */ + public function scoreForAllOnesIs20() + { + $this->given('New game') + ->when('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->and('Player rolls', 1) + ->then('Score should be', 20); + } + + /** + * @scenario + */ + public function scoreForOneSpareAnd3Is16() + { + $this->given('New game') + ->when('Player rolls', 5) + ->and('Player rolls', 5) + ->and('Player rolls', 3) + ->then('Score should be', 16); + } + + /** + * @scenario + */ + public function scoreForOneStrikeAnd3And4Is24() + { + $this->given('New game') + ->when('Player rolls', 10) + ->and('Player rolls', 3) + ->and('Player rolls', 4) + ->then('Score should be', 24); + } + + /** + * @scenario + */ + public function scoreForPerfectGameIs300() + { + $this->given('New game') + ->when('Player rolls', 10) + ->and('Player rolls', 10) + ->and('Player rolls', 10) + ->and('Player rolls', 10) + ->and('Player rolls', 10) + ->and('Player rolls', 10) + ->and('Player rolls', 10) + ->and('Player rolls', 10) + ->and('Player rolls', 10) + ->and('Player rolls', 10) + ->and('Player rolls', 10) + ->and('Player rolls', 10) + ->then('Score should be', 300); + } + + public function runGiven(&$world, $action, $arguments) + { + switch($action) { + case 'New game': { + $world['game'] = new BowlingGame; + $world['rolls'] = 0; + } + break; + + default: { + return $this->notImplemented($action); + } + } + } + + public function runWhen(&$world, $action, $arguments) + { + switch($action) { + case 'Player rolls': { + $world['game']->roll($arguments[0]); + $world['rolls']++; + } + break; + + default: { + return $this->notImplemented($action); + } + } + } + + public function runThen(&$world, $action, $arguments) + { + switch($action) { + case 'Score should be': { + for ($i = $world['rolls']; $i < 20; $i++) { + $world['game']->roll(0); + } + + $this->assertEquals($arguments[0], $world['game']->score()); + } + break; + + default: { + return $this->notImplemented($action); + } + } + } +} + diff --git a/tests/PHPUnit/Samples/BowlingGame/BowlingGameTest.php b/tests/PHPUnit/Samples/BowlingGame/BowlingGameTest.php new file mode 100755 index 00000000..eb84baaa --- /dev/null +++ b/tests/PHPUnit/Samples/BowlingGame/BowlingGameTest.php @@ -0,0 +1,110 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'BowlingGame.php'; + +class BowlingGameTest extends PHPUnit_Framework_TestCase +{ + protected $game; + + protected function setUp() + { + $this->game = new BowlingGame; + } + + public function testScoreForGutterGameIs0() + { + $this->rollMany(20, 0); + $this->assertEquals(0, $this->game->score()); + } + + public function testScoreForAllOnesIs20() + { + $this->rollMany(20, 1); + $this->assertEquals(20, $this->game->score()); + } + + public function testScoreForOneSpareAnd3Is16() + { + $this->rollSpare(); + $this->game->roll(3); + $this->rollMany(17, 0); + $this->assertEquals(16, $this->game->score()); + } + + public function testScoreForOneStrikeAnd3And4Is24() + { + $this->rollStrike(); + $this->game->roll(3); + $this->game->roll(4); + $this->rollMany(17, 0); + $this->assertEquals(24, $this->game->score()); + } + + public function testScoreForPerfectGameIs300() + { + $this->rollMany(12, 10); + $this->assertEquals(300, $this->game->score()); + } + + protected function rollMany($n, $pins) + { + for ($i = 0; $i < $n; $i++) { + $this->game->roll($pins); + } + } + + protected function rollSpare() + { + $this->game->roll(5); + $this->game->roll(5); + } + + protected function rollStrike() + { + $this->game->roll(10); + } +} diff --git a/tests/PHPUnit/Samples/FailureTest.php b/tests/PHPUnit/Samples/FailureTest.php new file mode 100755 index 00000000..e10280b7 --- /dev/null +++ b/tests/PHPUnit/Samples/FailureTest.php @@ -0,0 +1,114 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; + +/** + * Tests that demonstrate failure reporting. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class FailureTest extends PHPUnit_Framework_TestCase +{ + public function testAssertArrayEqualsArray() + { + $this->assertEquals(array(1), array(2)); + } + + public function testAssertIntegerEqualsInteger() + { + $this->assertEquals(1, 2); + } + + public function testAssertObjectEqualsObject() + { + $a = new StdClass; + $a->foo = 'bar'; + + $b = new StdClass; + $b->bar = 'foo'; + + $this->assertEquals($a, $b); + } + + public function testAssertNullEqualsString() + { + $this->assertEquals(NULL, 'bar'); + } + + public function testAssertStringEqualsString() + { + $this->assertEquals('foo', 'bar'); + } + + public function testAssertTextEqualsText() + { + $this->assertEquals("foo\nbar\n", "foo\nbaz\n"); + } + + public function testAssertTextSameText() + { + $this->assertSame('foo', 'bar'); + } + + public function testAssertObjectSameObject() + { + $this->assertSame(new StdClass, new StdClass); + } + + public function testAssertObjectSameNull() + { + $this->assertSame(new StdClass, NULL); + } +} +?> diff --git a/tests/PHPUnit/Samples/Money/IMoney.php b/tests/PHPUnit/Samples/Money/IMoney.php new file mode 100755 index 00000000..bff711fc --- /dev/null +++ b/tests/PHPUnit/Samples/Money/IMoney.php @@ -0,0 +1,73 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.3.0 + */ + +require_once 'Money.php'; +require_once 'MoneyBag.php'; + +/** + * Money Interface. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.3.0 + */ +interface IMoney +{ + public function add(IMoney $m); + public function addMoney(Money $m); + public function addMoneyBag(MoneyBag $s); + public function isZero(); + public function multiply($factor); + public function negate(); + public function subtract(IMoney $m); + public function appendTo(MoneyBag $m); +} +?> diff --git a/tests/PHPUnit/Samples/Money/Money.php b/tests/PHPUnit/Samples/Money/Money.php new file mode 100755 index 00000000..eb85251a --- /dev/null +++ b/tests/PHPUnit/Samples/Money/Money.php @@ -0,0 +1,151 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.3.0 + */ + +require_once 'IMoney.php'; + +/** + * A Money. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.3.0 + */ +class Money implements IMoney +{ + protected $fAmount; + protected $fCurrency; + + public function __construct($amount, $currency) + { + $this->fAmount = $amount; + $this->fCurrency = $currency; + } + + public function add(IMoney $m) + { + return $m->addMoney($this); + } + + public function addMoney(Money $m) + { + if ($this->currency() == $m->currency()) { + return new Money($this->amount() + $m->amount(), $this->currency()); + } + + return MoneyBag::create($this, $m); + } + + public function addMoneyBag(MoneyBag $s) + { + return $s->addMoney($this); + } + + public function amount() + { + return $this->fAmount; + } + + public function currency() + { + return $this->fCurrency; + } + + public function equals($anObject) + { + if ($this->isZero() && + $anObject instanceof IMoney) { + return $anObject->isZero(); + } + + if ($anObject instanceof Money) { + return ($this->currency() == $anObject->currency() && + $this->amount() == $anObject->amount()); + } + + return FALSE; + } + + public function hashCode() + { + return crc32($this->fCurrency) + $this->fAmount; + } + + public function isZero() + { + return $this->amount() == 0; + } + + public function multiply($factor) + { + return new Money($this->amount() * $factor, $this->currency()); + } + + public function negate() + { + return new Money(-1 * $this->amount(), $this->currency()); + } + + public function subtract(IMoney $m) + { + return $this->add($m->negate()); + } + + public function toString() + { + return '[' . $this->amount() . ' ' . $this->currency() . ']'; + } + + public function appendTo(MoneyBag $m) + { + $m->appendMoney($this); + } +} +?> diff --git a/tests/PHPUnit/Samples/Money/MoneyBag.php b/tests/PHPUnit/Samples/Money/MoneyBag.php new file mode 100755 index 00000000..2dea8778 --- /dev/null +++ b/tests/PHPUnit/Samples/Money/MoneyBag.php @@ -0,0 +1,250 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.3.0 + */ + +require_once 'IMoney.php'; +require_once 'Money.php'; + +/** + * A MoneyBag. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.3.0 + */ +class MoneyBag implements IMoney +{ + protected $fMonies = array(); + + public static function create(IMoney $m1, IMoney $m2) + { + $result = new MoneyBag; + $m1->appendTo($result); + $m2->appendTo($result); + + return $result->simplify(); + } + + public function add(IMoney $m) + { + return $m->addMoneyBag($this); + } + + public function addMoney(Money $m) + { + return MoneyBag::create($m, $this); + } + + public function addMoneyBag(MoneyBag $s) + { + return MoneyBag::create($s, $this); + } + + public function appendBag(MoneyBag $aBag) + { + foreach ($aBag->monies() as $aMoney) { + $this->appendMoney($aMoney); + } + } + + public function monies() + { + return $this->fMonies; + } + + public function appendMoney(Money $aMoney) + { + if ($aMoney->isZero()) { + return; + } + + $old = $this->findMoney($aMoney->currency()); + + if ($old == NULL) { + $this->fMonies[] = $aMoney; + return; + } + + $keys = array_keys($this->fMonies); + $max = count($keys); + + for ($i = 0; $i < $max; $i++) { + if ($this->fMonies[$keys[$i]] === $old) { + unset($this->fMonies[$keys[$i]]); + break; + } + } + + $sum = $old->add($aMoney); + + if ($sum->isZero()) { + return; + } + + $this->fMonies[] = $sum; + } + + public function equals($anObject) + { + if ($this->isZero() && + $anObject instanceof IMoney) { + return $anObject->isZero(); + } + + if ($anObject instanceof MoneyBag) { + if (count($anObject->monies()) != count($this->fMonies)) { + return FALSE; + } + + foreach ($this->fMonies as $m) { + if (!$anObject->contains($m)) { + return FALSE; + } + } + + return TRUE; + } + + return FALSE; + } + + protected function findMoney($currency) + { + foreach ($this->fMonies as $m) { + if ($m->currency() == $currency) { + return $m; + } + } + + return NULL; + } + + protected function contains(Money $m) + { + $found = $this->findMoney($m->currency()); + + if ($found == NULL) { + return FALSE; + } + + return $found->amount() == $m->amount(); + } + + public function hashCode() + { + $hash = 0; + + foreach ($this->fMonies as $m) { + $hash ^= $m->hashCode(); + } + + return $hash; + } + + public function isZero() + { + return count($this->fMonies) == 0; + } + + public function multiply($factor) + { + $result = new MoneyBag; + + if ($factor != 0) { + foreach ($this->fMonies as $m) { + $result->appendMoney($m->multiply($factor)); + } + } + + return $result; + } + + public function negate() + { + $result = new MoneyBag; + + foreach ($this->fMonies as $m) { + $result->appendMoney($m->negate()); + } + + return $result; + } + + protected function simplify() + { + if (count($this->fMonies) == 1) { + return array_pop($this->fMonies); + } + + return $this; + } + + public function subtract(IMoney $m) + { + return $this->add($m->negate()); + } + + public function toString() + { + $buffer = '{'; + + foreach ($this->fMonies as $m) { + $buffer .= $m->toString(); + } + + return $buffer . '}'; + } + + public function appendTo(MoneyBag $m) + { + $m->appendBag($this); + } +} +?> diff --git a/tests/PHPUnit/Samples/Money/MoneyTest.php b/tests/PHPUnit/Samples/Money/MoneyTest.php new file mode 100755 index 00000000..040da5de --- /dev/null +++ b/tests/PHPUnit/Samples/Money/MoneyTest.php @@ -0,0 +1,248 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.3.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; + +require_once 'Money.php'; +require_once 'MoneyBag.php'; + +/** + * Tests for the Money and MoneyBag classes. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.3.0 + */ +class MoneyTest extends PHPUnit_Framework_TestCase +{ + protected $f12EUR; + protected $f14EUR; + protected $f7USD; + protected $f21USD; + + protected $fMB1; + protected $fMB2; + + protected function setUp() + { + $this->f12EUR = new Money(12, 'EUR'); + $this->f14EUR = new Money(14, 'EUR'); + $this->f7USD = new Money( 7, 'USD'); + $this->f21USD = new Money(21, 'USD'); + + $this->fMB1 = MoneyBag::create($this->f12EUR, $this->f7USD); + $this->fMB2 = MoneyBag::create($this->f14EUR, $this->f21USD); + } + + public function testBagMultiply() + { + // {[12 EUR][7 USD]} *2 == {[24 EUR][14 USD]} + $expected = MoneyBag::create(new Money(24, 'EUR'), new Money(14, 'USD')); + + $this->assertTrue($expected->equals($this->fMB1->multiply(2))); + $this->assertTrue($this->fMB1->equals($this->fMB1->multiply(1))); + $this->assertTrue($this->fMB1->multiply(0)->isZero()); + } + + public function testBagNegate() + { + // {[12 EUR][7 USD]} negate == {[-12 EUR][-7 USD]} + $expected = MoneyBag::create(new Money(-12, 'EUR'), new Money(-7, 'USD')); + $this->assertTrue($expected->equals($this->fMB1->negate())); + } + + public function testBagSimpleAdd() + { + // {[12 EUR][7 USD]} + [14 EUR] == {[26 EUR][7 USD]} + $expected = MoneyBag::create(new Money(26, 'EUR'), new Money(7, 'USD')); + $this->assertTrue($expected->equals($this->fMB1->add($this->f14EUR))); + } + + public function testBagSubtract() + { + // {[12 EUR][7 USD]} - {[14 EUR][21 USD] == {[-2 EUR][-14 USD]} + $expected = MoneyBag::create(new Money(-2, 'EUR'), new Money(-14, 'USD')); + $this->assertTrue($expected->equals($this->fMB1->subtract($this->fMB2))); + } + + public function testBagSumAdd() + { + // {[12 EUR][7 USD]} + {[14 EUR][21 USD]} == {[26 EUR][28 USD]} + $expected = MoneyBag::create(new Money(26, 'EUR'), new Money(28, 'USD')); + $this->assertTrue($expected->equals($this->fMB1->add($this->fMB2))); + } + + public function testIsZero() + { + //$this->assertTrue($this->fMB1->subtract($this->fMB1)->isZero()); + $this->assertTrue(MoneyBag::create(new Money (0, 'EUR'), new Money (0, 'USD'))->isZero()); + } + + public function testMixedSimpleAdd() + { + // [12 EUR] + [7 USD] == {[12 EUR][7 USD]} + $expected = MoneyBag::create($this->f12EUR, $this->f7USD); + $this->assertTrue($expected->equals($this->f12EUR->add($this->f7USD))); + } + + public function testBagNotEquals() + { + $bag1 = MoneyBag::create($this->f12EUR, $this->f7USD); + $bag2 = new Money(12, 'CHF'); + $bag2->add($this->f7USD); + $this->assertFalse($bag1->equals($bag2)); + } + + public function testMoneyBagEquals() + { + $this->assertTrue(!$this->fMB1->equals(NULL)); + + $this->assertTrue($this->fMB1->equals($this->fMB1)); + $equal = MoneyBag::create(new Money(12, 'EUR'), new Money(7, 'USD')); + $this->assertTrue($this->fMB1->equals($equal)); + $this->assertTrue(!$this->fMB1->equals($this->f12EUR)); + $this->assertTrue(!$this->f12EUR->equals($this->fMB1)); + $this->assertTrue(!$this->fMB1->equals($this->fMB2)); + } + + public function testMoneyBagHash() + { + $equal = MoneyBag::create(new Money(12, 'EUR'), new Money(7, 'USD')); + $this->assertEquals($this->fMB1->hashCode(), $equal->hashCode()); + } + + public function testMoneyEquals() + { + $this->assertTrue(!$this->f12EUR->equals(NULL)); + $equalMoney = new Money(12, 'EUR'); + $this->assertTrue($this->f12EUR->equals($this->f12EUR)); + $this->assertTrue($this->f12EUR->equals($equalMoney)); + $this->assertEquals($this->f12EUR->hashCode(), $equalMoney->hashCode()); + $this->assertFalse($this->f12EUR->equals($this->f14EUR)); + } + + public function testMoneyHash() + { + $this->assertNotNull($this->f12EUR); + $equal= new Money(12, 'EUR'); + $this->assertEquals($this->f12EUR->hashCode(), $equal->hashCode()); + } + + public function testSimplify() + { + $money = MoneyBag::create(new Money(26, 'EUR'), new Money(28, 'EUR')); + $this->assertTrue($money->equals(new Money(54, 'EUR'))); + } + + public function testNormalize2() + { + // {[12 EUR][7 USD]} - [12 EUR] == [7 USD] + $expected = new Money(7, 'USD'); + $this->assertTrue($expected->equals($this->fMB1->subtract($this->f12EUR))); + } + + public function testNormalize3() + { + // {[12 EUR][7 USD]} - {[12 EUR][3 USD]} == [4 USD] + $ms1 = MoneyBag::create(new Money(12, 'EUR'), new Money(3, 'USD')); + $expected = new Money(4, 'USD'); + $this->assertTrue($expected->equals($this->fMB1->subtract($ms1))); + } + + public function testNormalize4() + { + // [12 EUR] - {[12 EUR][3 USD]} == [-3 USD] + $ms1 = MoneyBag::create(new Money(12, 'EUR'), new Money(3, 'USD')); + $expected = new Money(-3, 'USD'); + $this->assertTrue($expected->equals($this->f12EUR->subtract($ms1))); + } + + public function testPrint() + { + $this->assertEquals('[12 EUR]', $this->f12EUR->toString()); + } + + public function testSimpleAdd() + { + // [12 EUR] + [14 EUR] == [26 EUR] + $expected = new Money(26, 'EUR'); + $this->assertTrue($expected->equals($this->f12EUR->add($this->f14EUR))); + } + + public function testSimpleBagAdd() + { + // [14 EUR] + {[12 EUR][7 USD]} == {[26 EUR][7 USD]} + $expected = MoneyBag::create(new Money(26, 'EUR'), new Money(7, 'USD')); + $this->assertTrue($expected->equals($this->f14EUR->add($this->fMB1))); + } + + public function testSimpleMultiply() + { + // [14 EUR] *2 == [28 EUR] + $expected = new Money(28, 'EUR'); + $this->assertTrue($expected->equals($this->f14EUR->multiply(2))); + } + + public function testSimpleNegate() + { + // [14 EUR] negate == [-14 EUR] + $expected = new Money(-14, 'EUR'); + $this->assertTrue($expected->equals($this->f14EUR->negate())); + } + + public function testSimpleSubtract() + { + // [14 EUR] - [12 EUR] == [2 EUR] + $expected = new Money(2, 'EUR'); + $this->assertTrue($expected->equals($this->f14EUR->subtract($this->f12EUR))); + } +} +?> diff --git a/tests/PHPUnit/Tests/AllTests.php b/tests/PHPUnit/Tests/AllTests.php new file mode 100755 index 00000000..b9c421b1 --- /dev/null +++ b/tests/PHPUnit/Tests/AllTests.php @@ -0,0 +1,91 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +error_reporting(E_ALL | E_STRICT); + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__); + +require_once 'PHPUnit/Framework/TestSuite.php'; +require_once 'PHPUnit/Extensions/PhptTestSuite.php'; + +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Framework' . DIRECTORY_SEPARATOR . 'AllTests.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Extensions' . DIRECTORY_SEPARATOR . 'AllTests.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Runner' . DIRECTORY_SEPARATOR . 'AllTests.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Util' . DIRECTORY_SEPARATOR . 'AllTests.php'; + +PHPUnit_Util_Filter::$filterPHPUnit = FALSE; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class AllTests +{ + public static function suite() + { + $suite = new PHPUnit_Framework_TestSuite('PHPUnit'); + + $suite->addTest(Framework_AllTests::suite()); + $suite->addTest(Extensions_AllTests::suite()); + $suite->addTest(Runner_AllTests::suite()); + $suite->addTest(Util_AllTests::suite()); + $suite->addTest(new PHPUnit_Extensions_PhptTestSuite(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Regression')); + $suite->addTest(new PHPUnit_Extensions_PhptTestSuite(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'TextUI')); + + return $suite; + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/AllTests.php b/tests/PHPUnit/Tests/Extensions/AllTests.php new file mode 100755 index 00000000..13e4b507 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/AllTests.php @@ -0,0 +1,88 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__); + +require_once 'PHPUnit/Framework/TestSuite.php'; + +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'OutputTestCaseTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'PerformanceTestCaseTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'RepeatedTestTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'SeleniumTestCaseTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Database' . DIRECTORY_SEPARATOR . 'AllTests.php'; + +PHPUnit_Util_Filter::$filterPHPUnit = FALSE; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class Extensions_AllTests +{ + public static function suite() + { + $suite = new PHPUnit_Framework_TestSuite('PHPUnit_Extensions'); + + $suite->addTestSuite('Extensions_OutputTestCaseTest'); + $suite->addTestSuite('Extensions_PerformanceTestCaseTest'); + $suite->addTestSuite('Extensions_RepeatedTestTest'); + $suite->addTestSuite('Extensions_SeleniumTestCaseTest'); + $suite->addTest(Extensions_Database_AllTests::suite()); + + return $suite; + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/Database/AllTests.php b/tests/PHPUnit/Tests/Extensions/Database/AllTests.php new file mode 100755 index 00000000..5dc4dc85 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/AllTests.php @@ -0,0 +1,84 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +error_reporting(E_ALL | E_STRICT); + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__); + +require_once 'PHPUnit/Framework/TestSuite.php'; + +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'DataSet' . DIRECTORY_SEPARATOR . 'AllTests.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Operation' . DIRECTORY_SEPARATOR . 'AllTests.php'; + +PHPUnit_Util_Filter::$filterPHPUnit = FALSE; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class Extensions_Database_AllTests +{ + public static function suite() + { + $suite = new PHPUnit_Framework_TestSuite('PHPUnit_Extensions_Database'); + + $suite->addTest(Extensions_Database_Operation_AllTests::suite()); + $suite->addTest(Extensions_Database_DataSet_AllTests::suite()); + + return $suite; + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/Database/DataSet/AllTests.php b/tests/PHPUnit/Tests/Extensions/Database/DataSet/AllTests.php new file mode 100755 index 00000000..b03fdb0e --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/DataSet/AllTests.php @@ -0,0 +1,96 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__); + +require_once 'PHPUnit/Framework/TestSuite.php'; + +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'CompositeDataSetTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'CsvDataSetTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'FilterTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'PersistorTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'QueryDataSetTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'QueryTableTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ReplacementDataSetTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ReplacementTableTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'XmlDataSetsTest.php'; + +PHPUnit_Util_Filter::$filterPHPUnit = FALSE; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class Extensions_Database_DataSet_AllTests +{ + public static function suite() + { + $suite = new PHPUnit_Framework_TestSuite('PHPUnit_Extensions_Database_DataSet'); + + $suite->addTestSuite('Extensions_Database_DataSet_CompositeDataSetTest'); + $suite->addTestSuite('Extensions_Database_DataSet_CsvDataSetTest'); + $suite->addTestSuite('Extensions_Database_DataSet_FilterTest'); + $suite->addTestSuite('Extensions_Database_DataSet_PersistorTest'); + $suite->addTestSuite('Extensions_Database_DataSet_QueryDataSetTest'); + $suite->addTestSuite('Extensions_Database_DataSet_QueryTableTest'); + $suite->addTestSuite('Extensions_Database_DataSet_ReplacementDataSetTest'); + $suite->addTestSuite('Extensions_Database_DataSet_ReplacementTableTest'); + $suite->addTestSuite('Extensions_Database_DataSet_XmlDataSetsTest'); + + return $suite; + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/Database/DataSet/CompositeDataSetTest.php b/tests/PHPUnit/Tests/Extensions/Database/DataSet/CompositeDataSetTest.php new file mode 100755 index 00000000..a24ce7a0 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/DataSet/CompositeDataSetTest.php @@ -0,0 +1,174 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultDataSet.php'; +require_once 'PHPUnit/Extensions/Database/TestCase.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTable.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/CompositeDataSet.php'; + +/** + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ +class Extensions_Database_DataSet_CompositeDataSetTest extends PHPUnit_Framework_TestCase +{ + protected $expectedDataSet1; + protected $expectedDataSet2; + protected $expectedDataSet3; + + public function setUp() + { + $table1MetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table1', array('table1_id', 'column1', 'column2', 'column3', 'column4') + ); + $table2MetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table2', array('table2_id', 'column5', 'column6', 'column7', 'column8') + ); + + $table3MetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table3', array('table3_id', 'column9', 'column10', 'column11', 'column12') + ); + + $table1 = new PHPUnit_Extensions_Database_DataSet_DefaultTable($table1MetaData); + $table2 = new PHPUnit_Extensions_Database_DataSet_DefaultTable($table2MetaData); + $table3 = new PHPUnit_Extensions_Database_DataSet_DefaultTable($table3MetaData); + + $table1->addRow(array( + 'table1_id' => 1, + 'column1' => 'tgfahgasdf', + 'column2' => 200, + 'column3' => 34.64, + 'column4' => 'yghkf;a hahfg8ja h;' + )); + $table1->addRow(array( + 'table1_id' => 2, + 'column1' => 'hk;afg', + 'column2' => 654, + 'column3' => 46.54, + 'column4' => '24rwehhads' + )); + $table1->addRow(array( + 'table1_id' => 3, + 'column1' => 'ha;gyt', + 'column2' => 462, + 'column3' => 1654.4, + 'column4' => 'asfgklg' + )); + + $table2->addRow(array( + 'table2_id' => 1, + 'column5' => 'fhah', + 'column6' => 456, + 'column7' => 46.5, + 'column8' => 'fsdb, ghfdas' + )); + $table2->addRow(array( + 'table2_id' => 2, + 'column5' => 'asdhfoih', + 'column6' => 654, + 'column7' => 'blah', + 'column8' => '43asd "fhgj" sfadh' + )); + $table2->addRow(array( + 'table2_id' => 3, + 'column5' => 'ajsdlkfguitah', + 'column6' => 654, + 'column7' => 'blah', + 'column8' => 'thesethasdl +asdflkjsadf asdfsadfhl "adsf, halsdf" sadfhlasdf' + )); + + $table3->addRow(array( + 'table3_id' => 1, + 'column9' => 'sfgsda', + 'column10' => 16, + 'column11' => 45.57, + 'column12' => 'sdfh .ds,ajfas asdf h' + )); + $table3->addRow(array( + 'table3_id' => 2, + 'column9' => 'afdstgb', + 'column10' => 41, + 'column11' => 46.645, + 'column12' => '87yhasdf sadf yah;/a ' + )); + $table3->addRow(array( + 'table3_id' => 3, + 'column9' => 'gldsf', + 'column10' => 46, + 'column11' => 123.456, + 'column12' => '0y8hosnd a/df7y olgbjs da' + )); + + $this->expectedDataSet1 = new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(array($table1, $table2)); + $this->expectedDataSet2 = new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(array($table3)); + $this->expectedDataSet3 = new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(array($table1, $table2, $table3)); + } + + public function testCompositeDataSet() + { + $actual = new PHPUnit_Extensions_Database_DataSet_CompositeDataSet(array($this->expectedDataSet1, $this->expectedDataSet2)); + + PHPUnit_Extensions_Database_TestCase::assertDataSetsEqual($this->expectedDataSet3, $actual); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testDuplicateTables() + { + new PHPUnit_Extensions_Database_DataSet_CompositeDataSet(array($this->expectedDataSet1, $this->expectedDataSet1)); + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/Database/DataSet/CsvDataSetTest.php b/tests/PHPUnit/Tests/Extensions/Database/DataSet/CsvDataSetTest.php new file mode 100755 index 00000000..d2b44ca5 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/DataSet/CsvDataSetTest.php @@ -0,0 +1,134 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultDataSet.php'; +require_once 'PHPUnit/Extensions/Database/TestCase.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTable.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/CsvDataSet.php'; + +/** + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ +class Extensions_Database_DataSet_CsvDataSetTest extends PHPUnit_Framework_TestCase +{ + protected $expectedDataSet; + + public function testCSVDataSet() + { + $table1MetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table1', array('table1_id', 'column1', 'column2', 'column3', 'column4') + ); + $table2MetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table2', array('table2_id', 'column5', 'column6', 'column7', 'column8') + ); + + $table1 = new PHPUnit_Extensions_Database_DataSet_DefaultTable($table1MetaData); + $table2 = new PHPUnit_Extensions_Database_DataSet_DefaultTable($table2MetaData); + + $table1->addRow(array( + 'table1_id' => 1, + 'column1' => 'tgfahgasdf', + 'column2' => 200, + 'column3' => 34.64, + 'column4' => 'yghkf;a hahfg8ja h;' + )); + $table1->addRow(array( + 'table1_id' => 2, + 'column1' => 'hk;afg', + 'column2' => 654, + 'column3' => 46.54, + 'column4' => '24rwehhads' + )); + $table1->addRow(array( + 'table1_id' => 3, + 'column1' => 'ha;gyt', + 'column2' => 462, + 'column3' => 1654.4, + 'column4' => 'asfgklg' + )); + + $table2->addRow(array( + 'table2_id' => 1, + 'column5' => 'fhah', + 'column6' => 456, + 'column7' => 46.5, + 'column8' => 'fsdb, ghfdas' + )); + $table2->addRow(array( + 'table2_id' => 2, + 'column5' => 'asdhfoih', + 'column6' => 654, + 'column7' => 'blah', + 'column8' => '43asd "fhgj" sfadh' + )); + $table2->addRow(array( + 'table2_id' => 3, + 'column5' => 'ajsdlkfguitah', + 'column6' => 654, + 'column7' => 'blah', + 'column8' => 'thesethasdl +asdflkjsadf asdfsadfhl "adsf, halsdf" sadfhlasdf' + )); + + $expectedDataSet = new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(array($table1, $table2)); + + $csvDataSet = new PHPUnit_Extensions_Database_DataSet_CsvDataSet(); + $csvDataSet->addTable('table1', dirname(__FILE__).'/../_files/CsvDataSets/table1.csv'); + $csvDataSet->addTable('table2', dirname(__FILE__).'/../_files/CsvDataSets/table2.csv'); + + PHPUnit_Extensions_Database_TestCase::assertDataSetsEqual($expectedDataSet, $csvDataSet); + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/Database/DataSet/FilterTest.php b/tests/PHPUnit/Tests/Extensions/Database/DataSet/FilterTest.php new file mode 100755 index 00000000..e8b8ce64 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/DataSet/FilterTest.php @@ -0,0 +1,89 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DataSetFilter.php'; +require_once 'PHPUnit/Extensions/Database/Constraint/DataSetIsEqual.php'; + +/** + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ +class Extensions_Database_DataSet_FilterTest extends PHPUnit_Framework_TestCase +{ + protected $expectedDataSet; + + public function setUp() + { + $this->expectedDataSet = new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet( + dirname(__FILE__).'/../_files/XmlDataSets/FilteredTestFixture.xml' + ); + } + + public function testFilteredDataSet() + { + $constraint = new PHPUnit_Extensions_Database_Constraint_DataSetIsEqual($this->expectedDataSet); + $dataSet = new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet( + dirname(__FILE__).'/../_files/XmlDataSets/FilteredTestComparison.xml' + ); + + $filteredDataSet = new PHPUnit_Extensions_Database_DataSet_DataSetFilter($dataSet, array( + 'table1' => array('table1_id'), + 'table2' => '*', + 'table3' => array('table3_id') + )); + + self::assertThat($filteredDataSet, $constraint); + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/Database/DataSet/PersistorTest.php b/tests/PHPUnit/Tests/Extensions/Database/DataSet/PersistorTest.php new file mode 100755 index 00000000..cca843cf --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/DataSet/PersistorTest.php @@ -0,0 +1,116 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/XmlDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTable.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php'; + +/** + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ +class Extensions_Database_DataSet_PersistorTest extends PHPUnit_Framework_TestCase +{ + public function testFlatXml() + { + $dataSetFile = dirname(__FILE__).'/../_files/XmlDataSets/FlatXmlWriter.xml'; + $filename = dirname(__FILE__).'/'.uniqid().'.xml'; + $dataSet = new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet($dataSetFile); + + PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet::write($dataSet, $filename); + $this->assertXmlFileEqualsXmlFile($dataSetFile, $filename); + unlink($filename); + } + + public function testXml() + { + $dataSetFile = dirname(__FILE__).'/../_files/XmlDataSets/XmlWriter.xml'; + $filename = dirname(__FILE__).'/'.uniqid().'.xml'; + $dataSet = new PHPUnit_Extensions_Database_DataSet_XmlDataSet($dataSetFile); + + PHPUnit_Extensions_Database_DataSet_XmlDataSet::write($dataSet, $filename); + $this->assertXmlFileEqualsXmlFile($dataSetFile, $filename); + unlink($filename); + } + + public function testEntitiesFlatXml() + { + $metaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('table1', array('col1', 'col2'), array('col1')); + $table = new PHPUnit_Extensions_Database_DataSet_DefaultTable($metaData); + $table->addRow(array('col1' => 1, 'col2' => 'test')); + $dataSet = new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(array($table)); + + $expectedFile = dirname(__FILE__).'/../_files/XmlDataSets/FlatXmlWriterEntities.xml'; + $filename = dirname(__FILE__).'/'.uniqid().'.xml'; + PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet::write($dataSet, $filename); + $this->assertXmlFileEqualsXmlFile($expectedFile, $filename); + unlink($filename); + } + + public function testEntitiesXml() + { + $metaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('table1', array('col1', 'col2'), array('col1')); + $table = new PHPUnit_Extensions_Database_DataSet_DefaultTable($metaData); + $table->addRow(array('col1' => 1, 'col2' => 'test')); + $dataSet = new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(array($table)); + + $expectedFile = dirname(__FILE__).'/../_files/XmlDataSets/XmlWriterEntities.xml'; + $filename = dirname(__FILE__).'/'.uniqid().'.xml'; + PHPUnit_Extensions_Database_DataSet_XmlDataSet::write($dataSet, $filename); + $this->assertXmlFileEqualsXmlFile($expectedFile, $filename); + unlink($filename); + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/Database/DataSet/QueryDataSetTest.php b/tests/PHPUnit/Tests/Extensions/Database/DataSet/QueryDataSetTest.php new file mode 100755 index 00000000..9d337b24 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/DataSet/QueryDataSetTest.php @@ -0,0 +1,144 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Extensions/Database/TestCase.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/QueryDataSet.php'; +require_once dirname(__FILE__). '/../_files/DatabaseTestUtility.php'; +//require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTable.php'; +//require_once 'PHPUnit/Extensions/Database/DB/DefaultDatabaseConnection.php'; + +/** + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ +class Extensions_Database_DataSet_QueryDataSetTest extends PHPUnit_Extensions_Database_TestCase +{ + /** + * @var PHPUnit_Extensions_Database_DataSet_QueryDataSet + */ + protected $dataSet; + + protected $pdo; + + /** + * @return PHPUnit_Extensions_Database_DB_DefaultDatabaseConnection + */ + protected function getConnection() + { + return $this->createDefaultDBConnection($this->pdo, 'test'); + } + + protected function getDataSet() + { + return $this->createFlatXMLDataSet(dirname(__FILE__).'/../_files/XmlDataSets/QueryDataSetTest.xml'); + } + + public function setUp() + { + $this->pdo = DBUnitTestUtility::getSQLiteMemoryDB(); + parent::setUp(); + $this->dataSet = new PHPUnit_Extensions_Database_DataSet_QueryDataSet($this->getConnection()); + $this->dataSet->addTable('table1'); + $this->dataSet->addTable('query1', ' + SELECT + t1.column1 tc1, t2.column5 tc2 + FROM + table1 t1 + JOIN table2 t2 ON t1.table1_id = t2.table2_id + '); + } + + public function testGetTable() + { + $expectedTable1 = $this->getConnection()->createDataSet(array('table1'))->getTable('table1'); + + $expectedTable2 = new PHPUnit_Extensions_Database_DataSet_DefaultTable( + new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('query1', array('tc1', 'tc2')) + ); + + $expectedTable2->addRow(array('tc1' => 'bar', 'tc2' => 'blah')); + + $this->assertTablesEqual($expectedTable1, $this->dataSet->getTable('table1')); + $this->assertTablesEqual($expectedTable2, $this->dataSet->getTable('query1')); + } + + public function testGetTableNames() + { + $this->assertEquals(array('table1', 'query1'), $this->dataSet->getTableNames()); + } + + public function testCreateIterator() + { + $expectedTable1 = $this->getConnection()->createDataSet(array('table1'))->getTable('table1'); + + $expectedTable2 = new PHPUnit_Extensions_Database_DataSet_DefaultTable( + new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('query1', array('tc1', 'tc2')) + ); + + $expectedTable2->addRow(array('tc1' => 'bar', 'tc2' => 'blah')); + + foreach ($this->dataSet as $i => $table) { + /* @var $table PHPUnit_Extensions_Database_DataSet_ITable */ + switch ($table->getTableMetaData()->getTableName()) { + case 'table1': + $this->assertTablesEqual($expectedTable1, $table); + break; + case 'query1': + $this->assertTablesEqual($expectedTable2, $table); + break; + default: + $this->fail('Proper keys not present from the iterator'); + } + } + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/Database/DataSet/QueryTableTest.php b/tests/PHPUnit/Tests/Extensions/Database/DataSet/QueryTableTest.php new file mode 100755 index 00000000..8d56239f --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/DataSet/QueryTableTest.php @@ -0,0 +1,144 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/QueryTable.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTable.php'; +require_once 'PHPUnit/Extensions/Database/DB/DefaultDatabaseConnection.php'; + +/** + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ +class Extensions_Database_DataSet_QueryTableTest extends PHPUnit_Framework_TestCase +{ + /** + * @var PHPUnit_Extensions_Database_DataSet_QueryTable + */ + protected $table; + + public function setUp() + { + $query = " + SELECT + 'value1' as col1, + 'value2' as col2, + 'value3' as col3 + UNION SELECT + 'value4' as col1, + 'value5' as col2, + 'value6' as col3 + "; + $this->table = new PHPUnit_Extensions_Database_DataSet_QueryTable( + 'table1', + $query, + new PHPUnit_Extensions_Database_DB_DefaultDatabaseConnection(new PDO('sqlite::memory:'), 'test') + ); + } + + public static function providerTestGetValue() + { + return array( + array(0, 'col1', 'value1'), + array(0, 'col2', 'value2'), + array(0, 'col3', 'value3'), + array(1, 'col1', 'value4'), + array(1, 'col2', 'value5'), + array(1, 'col3', 'value6'), + ); + } + + public function testGetTableMetaData() + { + $metaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('table1', array('col1', 'col2', 'col3')); + + $this->assertEquals($metaData, $this->table->getTableMetaData()); + } + + public function testGetRowCount() + { + $this->assertEquals(2, $this->table->getRowCount()); + } + + /** + * @dataProvider providerTestGetValue + */ + public function testGetValue($row, $column, $value) + { + $this->assertEquals($value, $this->table->getValue($row, $column)); + } + + public function testGetRow() + { + $this->assertEquals(array('col1' => 'value1', 'col2' => 'value2', 'col3' => 'value3'), $this->table->getRow(0)); + } + + public function testAssertEquals() + { + $expected_table = new PHPUnit_Extensions_Database_DataSet_DefaultTable(new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('table1', array('col1', 'col2', 'col3'))); + $expected_table->addRow(array('col1' => 'value1', 'col2' => 'value2', 'col3' => 'value3')); + $expected_table->addRow(array('col1' => 'value4', 'col2' => 'value5', 'col3' => 'value6')); + $this->assertTrue($this->table->assertEquals($expected_table)); + } + + public function testAssertEqualsFails() + { + $this->setExpectedException('Exception', 'Expected row count of 2, has a row count of 3'); + + $expected_table = new PHPUnit_Extensions_Database_DataSet_DefaultTable(new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('table1', array('col1', 'col2', 'col3'))); + $expected_table->addRow(array('col1' => 'value1', 'col2' => 'value2', 'col3' => 'value3')); + $expected_table->addRow(array('col1' => 'value4', 'col2' => 'value5', 'col3' => 'value6')); + $expected_table->addRow(array('col1' => 'value7', 'col2' => 'value8', 'col3' => 'value9')); + $this->table->assertEquals($expected_table); + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/Database/DataSet/ReplacementDataSetTest.php b/tests/PHPUnit/Tests/Extensions/Database/DataSet/ReplacementDataSetTest.php new file mode 100755 index 00000000..76024131 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/DataSet/ReplacementDataSetTest.php @@ -0,0 +1,330 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; +require_once 'PHPUnit/Extensions/Database/TestCase.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/ReplacementDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTable.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php'; + +/** + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ +class Extensions_Database_DataSet_ReplacementDataSetTest extends PHPUnit_Framework_TestCase +{ + /** + * @var PHPUnit_Extensions_Database_DataSet_DefaultDataSet + */ + protected $startingDataSet; + + public function setUp() + { + $table1MetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table1', array('table1_id', 'column1', 'column2', 'column3', 'column4') + ); + $table2MetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table2', array('table2_id', 'column5', 'column6', 'column7', 'column8') + ); + + $table1 = new PHPUnit_Extensions_Database_DataSet_DefaultTable($table1MetaData); + $table2 = new PHPUnit_Extensions_Database_DataSet_DefaultTable($table2MetaData); + + $table1->addRow(array( + 'table1_id' => 1, + 'column1' => 'My name is %%%name%%%', + 'column2' => 200, + 'column3' => 34.64, + 'column4' => 'yghkf;a hahfg8ja h;' + )); + $table1->addRow(array( + 'table1_id' => 2, + 'column1' => 'hk;afg', + 'column2' => 654, + 'column3' => 46.54, + 'column4' => '24rwehhads' + )); + $table1->addRow(array( + 'table1_id' => 3, + 'column1' => 'ha;gyt', + 'column2' => 462, + 'column3' => 1654.4, + 'column4' => '[NULL]' + )); + + $table2->addRow(array( + 'table2_id' => 1, + 'column5' => 'fhah', + 'column6' => 456, + 'column7' => 46.5, + 'column8' => 'My name is %%%name%%%' + )); + $table2->addRow(array( + 'table2_id' => 2, + 'column5' => 'asdhfoih', + 'column6' => 654, + 'column7' => '[NULL]', + 'column8' => '43asdfhgj' + )); + $table2->addRow(array( + 'table2_id' => 3, + 'column5' => 'ajsdlkfguitah', + 'column6' => 654, + 'column7' => '[NULL]', + 'column8' => '[NULL] not really' + )); + + $this->startingDataSet = new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(array($table1, $table2)); + } + + public function testNoReplacement() + { + PHPUnit_Extensions_Database_TestCase::assertDataSetsEqual( + $this->startingDataSet, + new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet($this->startingDataSet) + ); + } + + public function testFullReplacement() + { + $table1MetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table1', array('table1_id', 'column1', 'column2', 'column3', 'column4') + ); + $table2MetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table2', array('table2_id', 'column5', 'column6', 'column7', 'column8') + ); + + $table1 = new PHPUnit_Extensions_Database_DataSet_DefaultTable($table1MetaData); + $table2 = new PHPUnit_Extensions_Database_DataSet_DefaultTable($table2MetaData); + + $table1->addRow(array( + 'table1_id' => 1, + 'column1' => 'My name is %%%name%%%', + 'column2' => 200, + 'column3' => 34.64, + 'column4' => 'yghkf;a hahfg8ja h;' + )); + $table1->addRow(array( + 'table1_id' => 2, + 'column1' => 'hk;afg', + 'column2' => 654, + 'column3' => 46.54, + 'column4' => '24rwehhads' + )); + $table1->addRow(array( + 'table1_id' => 3, + 'column1' => 'ha;gyt', + 'column2' => 462, + 'column3' => 1654.4, + 'column4' => NULL + )); + + $table2->addRow(array( + 'table2_id' => 1, + 'column5' => 'fhah', + 'column6' => 456, + 'column7' => 46.5, + 'column8' => 'My name is %%%name%%%' + )); + $table2->addRow(array( + 'table2_id' => 2, + 'column5' => 'asdhfoih', + 'column6' => 654, + 'column7' => NULL, + 'column8' => '43asdfhgj' + )); + $table2->addRow(array( + 'table2_id' => 3, + 'column5' => 'ajsdlkfguitah', + 'column6' => 654, + 'column7' => NULL, + 'column8' => '[NULL] not really' + )); + + $expected = new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(array($table1, $table2)); + $actual = new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet($this->startingDataSet); + $actual->addFullReplacement('[NULL]', NULL); + + PHPUnit_Extensions_Database_TestCase::assertDataSetsEqual($expected, $actual); + } + + public function testSubStrReplacement() + { + $table1MetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table1', array('table1_id', 'column1', 'column2', 'column3', 'column4') + ); + $table2MetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table2', array('table2_id', 'column5', 'column6', 'column7', 'column8') + ); + + $table1 = new PHPUnit_Extensions_Database_DataSet_DefaultTable($table1MetaData); + $table2 = new PHPUnit_Extensions_Database_DataSet_DefaultTable($table2MetaData); + + $table1->addRow(array( + 'table1_id' => 1, + 'column1' => 'My name is Mike Lively', + 'column2' => 200, + 'column3' => 34.64, + 'column4' => 'yghkf;a hahfg8ja h;' + )); + $table1->addRow(array( + 'table1_id' => 2, + 'column1' => 'hk;afg', + 'column2' => 654, + 'column3' => 46.54, + 'column4' => '24rwehhads' + )); + $table1->addRow(array( + 'table1_id' => 3, + 'column1' => 'ha;gyt', + 'column2' => 462, + 'column3' => 1654.4, + 'column4' => '[NULL]' + )); + + $table2->addRow(array( + 'table2_id' => 1, + 'column5' => 'fhah', + 'column6' => 456, + 'column7' => 46.5, + 'column8' => 'My name is Mike Lively' + )); + $table2->addRow(array( + 'table2_id' => 2, + 'column5' => 'asdhfoih', + 'column6' => 654, + 'column7' => '[NULL]', + 'column8' => '43asdfhgj' + )); + $table2->addRow(array( + 'table2_id' => 3, + 'column5' => 'ajsdlkfguitah', + 'column6' => 654, + 'column7' => '[NULL]', + 'column8' => '[NULL] not really' + )); + + $expected = new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(array($table1, $table2)); + $actual = new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet($this->startingDataSet); + $actual->addSubStrReplacement('%%%name%%%', 'Mike Lively'); + + PHPUnit_Extensions_Database_TestCase::assertDataSetsEqual($expected, $actual); + } + + public function testConstructorReplacements() + { + $table1MetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table1', array('table1_id', 'column1', 'column2', 'column3', 'column4') + ); + $table2MetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table2', array('table2_id', 'column5', 'column6', 'column7', 'column8') + ); + + $table1 = new PHPUnit_Extensions_Database_DataSet_DefaultTable($table1MetaData); + $table2 = new PHPUnit_Extensions_Database_DataSet_DefaultTable($table2MetaData); + + $table1->addRow(array( + 'table1_id' => 1, + 'column1' => 'My name is Mike Lively', + 'column2' => 200, + 'column3' => 34.64, + 'column4' => 'yghkf;a hahfg8ja h;' + )); + $table1->addRow(array( + 'table1_id' => 2, + 'column1' => 'hk;afg', + 'column2' => 654, + 'column3' => 46.54, + 'column4' => '24rwehhads' + )); + $table1->addRow(array( + 'table1_id' => 3, + 'column1' => 'ha;gyt', + 'column2' => 462, + 'column3' => 1654.4, + 'column4' => NULL + )); + + $table2->addRow(array( + 'table2_id' => 1, + 'column5' => 'fhah', + 'column6' => 456, + 'column7' => 46.5, + 'column8' => 'My name is Mike Lively' + )); + $table2->addRow(array( + 'table2_id' => 2, + 'column5' => 'asdhfoih', + 'column6' => 654, + 'column7' => NULL, + 'column8' => '43asdfhgj' + )); + $table2->addRow(array( + 'table2_id' => 3, + 'column5' => 'ajsdlkfguitah', + 'column6' => 654, + 'column7' => NULL, + 'column8' => '[NULL] not really' + )); + + $expected = new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(array($table1, $table2)); + $actual = new PHPUnit_Extensions_Database_DataSet_ReplacementDataSet( + $this->startingDataSet, + array('[NULL]' => NULL), + array('%%%name%%%' => 'Mike Lively') + ); + + PHPUnit_Extensions_Database_TestCase::assertDataSetsEqual($expected, $actual); + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/Database/DataSet/ReplacementTableTest.php b/tests/PHPUnit/Tests/Extensions/Database/DataSet/ReplacementTableTest.php new file mode 100755 index 00000000..13b0f28f --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/DataSet/ReplacementTableTest.php @@ -0,0 +1,265 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/ReplacementTable.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTable.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php'; +require_once 'PHPUnit/Extensions/Database/TestCase.php'; + +/** + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ +class Extensions_Database_DataSet_ReplacementTableTest extends PHPUnit_Framework_TestCase +{ + /** + * @var PHPUnit_Extensions_Database_DataSet_DefaultTable + */ + protected $startingTable; + + public function setUp() + { + $tableMetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table1', array('table1_id', 'column1', 'column2', 'column3', 'column4') + ); + + $table = new PHPUnit_Extensions_Database_DataSet_DefaultTable($tableMetaData); + + $table->addRow(array( + 'table1_id' => 1, + 'column1' => 'My name is %%%name%%%', + 'column2' => 200, + 'column3' => 34.64, + 'column4' => 'yghkf;a hahfg8ja h;' + )); + $table->addRow(array( + 'table1_id' => 2, + 'column1' => 'hk;afg', + 'column2' => 654, + 'column3' => 46.54, + 'column4' => '24rwehhads' + )); + $table->addRow(array( + 'table1_id' => 3, + 'column1' => 'ha;gyt', + 'column2' => 462, + 'column3' => '[NULL] not really', + 'column4' => '[NULL]' + )); + + $this->startingTable = $table; + } + + public function testNoReplacement() + { + PHPUnit_Extensions_Database_TestCase::assertTablesEqual( + $this->startingTable, + new PHPUnit_Extensions_Database_DataSet_ReplacementTable($this->startingTable) + ); + } + + public function testFullReplacement() + { + $tableMetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table1', array('table1_id', 'column1', 'column2', 'column3', 'column4') + ); + + $table = new PHPUnit_Extensions_Database_DataSet_DefaultTable($tableMetaData); + + $table->addRow(array( + 'table1_id' => 1, + 'column1' => 'My name is %%%name%%%', + 'column2' => 200, + 'column3' => 34.64, + 'column4' => 'yghkf;a hahfg8ja h;' + )); + $table->addRow(array( + 'table1_id' => 2, + 'column1' => 'hk;afg', + 'column2' => 654, + 'column3' => 46.54, + 'column4' => '24rwehhads' + )); + $table->addRow(array( + 'table1_id' => 3, + 'column1' => 'ha;gyt', + 'column2' => 462, + 'column3' => '[NULL] not really', + 'column4' => NULL + )); + + $actual = new PHPUnit_Extensions_Database_DataSet_ReplacementTable($this->startingTable); + $actual->addFullReplacement('[NULL]', NULL); + + PHPUnit_Extensions_Database_TestCase::assertTablesEqual($table, $actual); + } + + public function testSubStrReplacement() + { + $tableMetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table1', array('table1_id', 'column1', 'column2', 'column3', 'column4') + ); + + $table = new PHPUnit_Extensions_Database_DataSet_DefaultTable($tableMetaData); + + $table->addRow(array( + 'table1_id' => 1, + 'column1' => 'My name is Mike Lively', + 'column2' => 200, + 'column3' => 34.64, + 'column4' => 'yghkf;a hahfg8ja h;' + )); + $table->addRow(array( + 'table1_id' => 2, + 'column1' => 'hk;afg', + 'column2' => 654, + 'column3' => 46.54, + 'column4' => '24rwehhads' + )); + $table->addRow(array( + 'table1_id' => 3, + 'column1' => 'ha;gyt', + 'column2' => 462, + 'column3' => '[NULL] not really', + 'column4' => '[NULL]' + )); + + $actual = new PHPUnit_Extensions_Database_DataSet_ReplacementTable($this->startingTable); + $actual->addSubStrReplacement('%%%name%%%', 'Mike Lively'); + + PHPUnit_Extensions_Database_TestCase::assertTablesEqual($table, $actual); + } + + public function testConstructorReplacements() + { + $tableMetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table1', array('table1_id', 'column1', 'column2', 'column3', 'column4') + ); + + $table = new PHPUnit_Extensions_Database_DataSet_DefaultTable($tableMetaData); + + $table->addRow(array( + 'table1_id' => 1, + 'column1' => 'My name is Mike Lively', + 'column2' => 200, + 'column3' => 34.64, + 'column4' => 'yghkf;a hahfg8ja h;' + )); + $table->addRow(array( + 'table1_id' => 2, + 'column1' => 'hk;afg', + 'column2' => 654, + 'column3' => 46.54, + 'column4' => '24rwehhads' + )); + $table->addRow(array( + 'table1_id' => 3, + 'column1' => 'ha;gyt', + 'column2' => 462, + 'column3' => '[NULL] not really', + 'column4' => NULL + )); + + $actual = new PHPUnit_Extensions_Database_DataSet_ReplacementTable( + $this->startingTable, + array('[NULL]' => NULL), + array('%%%name%%%' => 'Mike Lively') + ); + + PHPUnit_Extensions_Database_TestCase::assertTablesEqual($table, $actual); + } + + public function testGetRow() + { + $actual = new PHPUnit_Extensions_Database_DataSet_ReplacementTable( + $this->startingTable, + array('[NULL]' => NULL), + array('%%%name%%%' => 'Mike Lively') + ); + + $this->assertEquals( + array( + 'table1_id' => 1, + 'column1' => 'My name is Mike Lively', + 'column2' => 200, + 'column3' => 34.64, + 'column4' => 'yghkf;a hahfg8ja h;' + ), + $actual->getRow(0) + ); + + $this->assertEquals( + array( + 'table1_id' => 3, + 'column1' => 'ha;gyt', + 'column2' => 462, + 'column3' => '[NULL] not really', + 'column4' => NULL + ), + $actual->getRow(2) + ); + } + + public function testGetValue() + { + $actual = new PHPUnit_Extensions_Database_DataSet_ReplacementTable( + $this->startingTable, + array('[NULL]' => NULL), + array('%%%name%%%' => 'Mike Lively') + ); + + $this->assertNull($actual->getValue(2, 'column4')); + $this->assertEquals('My name is Mike Lively', $actual->getValue(0, 'column1')); + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/Database/DataSet/XmlDataSetsTest.php b/tests/PHPUnit/Tests/Extensions/Database/DataSet/XmlDataSetsTest.php new file mode 100755 index 00000000..a0db3d11 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/DataSet/XmlDataSetsTest.php @@ -0,0 +1,144 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTable.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/XmlDataSet.php'; +require_once 'PHPUnit/Extensions/Database/Constraint/DataSetIsEqual.php'; + +/** + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ +class Extensions_Database_DataSet_XmlDataSetsTest extends PHPUnit_Framework_TestCase +{ + protected $expectedDataSet; + + public function setUp() + { + $table1MetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table1', array('table1_id', 'column1', 'column2', 'column3', 'column4') + ); + $table2MetaData = new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData( + 'table2', array('table2_id', 'column5', 'column6', 'column7', 'column8') + ); + + $table1 = new PHPUnit_Extensions_Database_DataSet_DefaultTable($table1MetaData); + $table2 = new PHPUnit_Extensions_Database_DataSet_DefaultTable($table2MetaData); + + $table1->addRow(array( + 'table1_id' => 1, + 'column1' => 'tgfahgasdf', + 'column2' => 200, + 'column3' => 34.64, + 'column4' => 'yghkf;a hahfg8ja h;' + )); + $table1->addRow(array( + 'table1_id' => 2, + 'column1' => 'hk;afg', + 'column2' => 654, + 'column3' => 46.54, + 'column4' => '24rwehhads' + )); + $table1->addRow(array( + 'table1_id' => 3, + 'column1' => 'ha;gyt', + 'column2' => 462, + 'column3' => 1654.4, + 'column4' => 'asfgklg' + )); + + $table2->addRow(array( + 'table2_id' => 1, + 'column5' => 'fhah', + 'column6' => 456, + 'column7' => 46.5, + 'column8' => 'fsdbghfdas' + )); + $table2->addRow(array( + 'table2_id' => 2, + 'column5' => 'asdhfoih', + 'column6' => 654, + 'column7' => NULL, + 'column8' => '43asdfhgj' + )); + $table2->addRow(array( + 'table2_id' => 3, + 'column5' => 'ajsdlkfguitah', + 'column6' => 654, + 'column7' => NULL, + 'column8' => NULL + )); + + $this->expectedDataSet = new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(array($table1, $table2)); + } + + public function testFlatXmlDataSet() + { + $constraint = new PHPUnit_Extensions_Database_Constraint_DataSetIsEqual($this->expectedDataSet); + $xmlFlatDataSet = new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/FlatXmlDataSet.xml'); + + self::assertThat($xmlFlatDataSet, $constraint); + } + + public function testXmlDataSet() + { + $constraint = new PHPUnit_Extensions_Database_Constraint_DataSetIsEqual($this->expectedDataSet); + $xmlDataSet = new PHPUnit_Extensions_Database_DataSet_XmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/XmlDataSet.xml'); + + self::assertThat($xmlDataSet, $constraint); + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/Database/Operation/AllTests.php b/tests/PHPUnit/Tests/Extensions/Database/Operation/AllTests.php new file mode 100755 index 00000000..c139883d --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/Operation/AllTests.php @@ -0,0 +1,82 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__); + +require_once 'PHPUnit/Framework/TestSuite.php'; + +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'OperationsTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'RowBasedTest.php'; + +PHPUnit_Util_Filter::$filterPHPUnit = FALSE; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class Extensions_Database_Operation_AllTests +{ + public static function suite() + { + $suite = new PHPUnit_Framework_TestSuite('PHPUnit_Extensions_Database_Operation'); + + $suite->addTestSuite('Extensions_Database_Operation_OperationsTest'); + $suite->addTestSuite('Extensions_Database_Operation_RowBasedTest'); + + return $suite; + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/Database/Operation/OperationsTest.php b/tests/PHPUnit/Tests/Extensions/Database/Operation/OperationsTest.php new file mode 100755 index 00000000..d12a0530 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/Operation/OperationsTest.php @@ -0,0 +1,195 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Extensions/Database/TestCase.php'; +require_once 'PHPUnit/Extensions/Database/DB/DefaultDatabaseConnection.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTable.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php'; + +require_once 'PHPUnit/Extensions/Database/Operation/Delete.php'; +require_once 'PHPUnit/Extensions/Database/Operation/DeleteAll.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Insert.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Update.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Truncate.php'; +require_once 'PHPUnit/Extensions/Database/Operation/Replace.php'; + +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'DatabaseTestUtility.php'; + +/** + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ +class Extensions_Database_Operation_OperationsTest extends PHPUnit_Extensions_Database_TestCase +{ + protected function setUp() + { + if (!extension_loaded('pdo_sqlite')) { + $this->markTestSkipped('PDO/SQLite is required to run this test.'); + } + + parent::setUp(); + } + + public function getConnection() + { + return new PHPUnit_Extensions_Database_DB_DefaultDatabaseConnection(DBUnitTestUtility::getSQLiteMemoryDB(), 'sqlite'); + } + + public function getDataSet() + { + return new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/OperationsTestFixture.xml'); + } + + public function testDelete() + { + $deleteOperation = new PHPUnit_Extensions_Database_Operation_Delete(); + + $deleteOperation->execute($this->getConnection(), new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/DeleteOperationTest.xml')); + + $this->assertDataSetsEqual(new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/DeleteOperationResult.xml'), $this->getConnection()->createDataSet()); + } + + public function testDeleteAll() + { + $deleteAllOperation = new PHPUnit_Extensions_Database_Operation_DeleteAll(); + + $deleteAllOperation->execute($this->getConnection(), new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/DeleteAllOperationTest.xml')); + + $expectedDataSet = new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(array( + new PHPUnit_Extensions_Database_DataSet_DefaultTable( + new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('table1', + array('table1_id', 'column1', 'column2', 'column3', 'column4')) + ), + new PHPUnit_Extensions_Database_DataSet_DefaultTable( + new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('table2', + array('table2_id', 'column5', 'column6', 'column7', 'column8')) + ), + new PHPUnit_Extensions_Database_DataSet_DefaultTable( + new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('table3', + array('table3_id', 'column9', 'column10', 'column11', 'column12')) + ), + )); + + $this->assertDataSetsEqual($expectedDataSet, $this->getConnection()->createDataSet()); + } + + public function testTruncate() + { + $truncateOperation = new PHPUnit_Extensions_Database_Operation_Truncate(); + + $truncateOperation->execute($this->getConnection(), new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/DeleteAllOperationTest.xml')); + + $expectedDataSet = new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(array( + new PHPUnit_Extensions_Database_DataSet_DefaultTable( + new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('table1', + array('table1_id', 'column1', 'column2', 'column3', 'column4')) + ), + new PHPUnit_Extensions_Database_DataSet_DefaultTable( + new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('table2', + array('table2_id', 'column5', 'column6', 'column7', 'column8')) + ), + new PHPUnit_Extensions_Database_DataSet_DefaultTable( + new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('table3', + array('table3_id', 'column9', 'column10', 'column11', 'column12')) + ), + )); + + $this->assertDataSetsEqual($expectedDataSet, $this->getConnection()->createDataSet()); + } + + public function testInsert() + { + $insertOperation = new PHPUnit_Extensions_Database_Operation_Insert(); + + $insertOperation->execute($this->getConnection(), new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/InsertOperationTest.xml')); + + $this->assertDataSetsEqual(new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/InsertOperationResult.xml'), $this->getConnection()->createDataSet()); + } + + public function testUpdate() + { + $updateOperation = new PHPUnit_Extensions_Database_Operation_Update(); + + $updateOperation->execute($this->getConnection(), new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/UpdateOperationTest.xml')); + + $this->assertDataSetsEqual(new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/UpdateOperationResult.xml'), $this->getConnection()->createDataSet()); + } + + public function testReplace() + { + $replaceOperation = new PHPUnit_Extensions_Database_Operation_Replace(); + + $replaceOperation->execute($this->getConnection(), new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/ReplaceOperationTest.xml')); + + $this->assertDataSetsEqual(new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/ReplaceOperationResult.xml'), $this->getConnection()->createDataSet()); + } + + public function testInsertEmptyTable() + { + $insertOperation = new PHPUnit_Extensions_Database_Operation_Insert(); + + $insertOperation->execute($this->getConnection(), new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/EmptyTableInsertTest.xml')); + + $this->assertDataSetsEqual(new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/EmptyTableInsertResult.xml'), $this->getConnection()->createDataSet()); + } + public function testInsertAllEmptyTables() + { + $insertOperation = new PHPUnit_Extensions_Database_Operation_Insert(); + + $insertOperation->execute($this->getConnection(), new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/AllEmptyTableInsertTest.xml')); + + $this->assertDataSetsEqual(new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/AllEmptyTableInsertResult.xml'), $this->getConnection()->createDataSet()); + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/Database/Operation/RowBasedTest.php b/tests/PHPUnit/Tests/Extensions/Database/Operation/RowBasedTest.php new file mode 100755 index 00000000..b9da65d5 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/Operation/RowBasedTest.php @@ -0,0 +1,187 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Extensions/Database/TestCase.php'; +require_once 'PHPUnit/Extensions/Database/DB/DefaultDatabaseConnection.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultDataSet.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTable.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/DefaultTableMetaData.php'; +require_once 'PHPUnit/Extensions/Database/DataSet/FlatXmlDataSet.php'; +require_once 'PHPUnit/Extensions/Database/Operation/RowBased.php'; + +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'DatabaseTestUtility.php'; + + +/** + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ +class Extensions_Database_Operation_RowBasedTest extends PHPUnit_Extensions_Database_TestCase +{ + protected function setUp() + { + if (!extension_loaded('pdo_sqlite')) { + $this->markTestSkipped('PDO/SQLite is required to run this test.'); + } + + parent::setUp(); + } + + public function getConnection() + { + return new PHPUnit_Extensions_Database_DB_DefaultDatabaseConnection(DBUnitTestUtility::getSQLiteMemoryDB(), 'sqlite'); + } + + public function getDataSet() + { + $tables = array( + new PHPUnit_Extensions_Database_DataSet_DefaultTable( + new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('table1', + array('table1_id', 'column1', 'column2', 'column3', 'column4')) + ), + new PHPUnit_Extensions_Database_DataSet_DefaultTable( + new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('table2', + array('table2_id', 'column5', 'column6', 'column7', 'column8')) + ), + new PHPUnit_Extensions_Database_DataSet_DefaultTable( + new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('table3', + array('table3_id', 'column9', 'column10', 'column11', 'column12')) + ), + ); + + return new PHPUnit_Extensions_Database_DataSet_DefaultDataSet($tables); + } + + public function testExcecute() + { + $connection = $this->getConnection(); + /* @var $connection PHPUnit_Extensions_Database_DB_DefaultDatabaseConnection */ + $table1 = new PHPUnit_Extensions_Database_DataSet_DefaultTable( + new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('table1', array('table1_id', 'column1', 'column2', 'column3', 'column4')) + ); + + $table1->addRow(array( + 'table1_id' => 1, + 'column1' => 'foo', + 'column2' => 42, + 'column3' => 4.2, + 'column4' => 'bar' + )); + + $table1->addRow(array( + 'table1_id' => 2, + 'column1' => 'qwerty', + 'column2' => 23, + 'column3' => 2.3, + 'column4' => 'dvorak' + )); + + $table2 = new PHPUnit_Extensions_Database_DataSet_DefaultTable( + new PHPUnit_Extensions_Database_DataSet_DefaultTableMetaData('table2', array('table2_id', 'column5', 'column6', 'column7', 'column8')) + ); + + $table2->addRow(array( + 'table2_id' => 1, + 'column5' => 'fdyhkn', + 'column6' => 64, + 'column7' => 4568.64, + 'column8' => 'hkladfg' + )); + + $dataSet = new PHPUnit_Extensions_Database_DataSet_DefaultDataSet(array($table1, $table2)); + + $mockOperation = $this->getMock('PHPUnit_Extensions_Database_Operation_RowBased', + array('buildOperationQuery', 'buildOperationArguments')); + + /* @var $mockOperation PHPUnit_Framework_MockObject_MockObject */ + $mockOperation->expects($this->at(0)) + ->method('buildOperationQuery') + ->with($connection->createDataSet()->getTableMetaData('table1'), $table1) + ->will( + $this->returnValue('INSERT INTO table1 (table1_id, column1, column2, column3, column4) VALUES (?, ?, ?, ?, ?)') + ); + + $mockOperation->expects($this->at(1)) + ->method('buildOperationArguments') + ->with($connection->createDataSet()->getTableMetaData('table1'), $table1, 0) + ->will( + $this->returnValue(array(1, 'foo', 42, 4.2, 'bar')) + ); + + $mockOperation->expects($this->at(2)) + ->method('buildOperationArguments') + ->with($connection->createDataSet()->getTableMetaData('table1'), $table1, 1) + ->will( + $this->returnValue(array(2, 'qwerty', 23, 2.3, 'dvorak')) + ); + + $mockOperation->expects($this->at(3)) + ->method('buildOperationQuery') + ->with($connection->createDataSet()->getTableMetaData('table2'), $table2) + ->will( + $this->returnValue('INSERT INTO table2 (table2_id, column5, column6, column7, column8) VALUES (?, ?, ?, ?, ?)') + ); + + $mockOperation->expects($this->at(4)) + ->method('buildOperationArguments') + ->with($connection->createDataSet()->getTableMetaData('table2'), $table2, 0) + ->will( + $this->returnValue(array(1, 'fdyhkn', 64, 4568.64, 'hkladfg')) + ); + + /* @var $mockOperation PHPUnit_Extensions_Database_Operation_RowBased */ + $mockOperation->execute($connection, $dataSet); + + $this->assertDataSetsEqual(new PHPUnit_Extensions_Database_DataSet_FlatXmlDataSet(dirname(__FILE__).'/../_files/XmlDataSets/RowBasedExecute.xml'), $connection->createDataSet(array('table1', 'table2'))); + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/CsvDataSets/table1.csv b/tests/PHPUnit/Tests/Extensions/Database/_files/CsvDataSets/table1.csv new file mode 100755 index 00000000..345520d8 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/CsvDataSets/table1.csv @@ -0,0 +1,4 @@ +table1_id,column1,column2,column3,column4 +1,tgfahgasdf,200,34.64,"yghkf;a hahfg8ja h;" +2,hk;afg,654,46.54,24rwehhads +3,ha;gyt,462,1654.4,asfgklg \ No newline at end of file diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/CsvDataSets/table2.csv b/tests/PHPUnit/Tests/Extensions/Database/_files/CsvDataSets/table2.csv new file mode 100755 index 00000000..3f1142c2 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/CsvDataSets/table2.csv @@ -0,0 +1,5 @@ +table2_id,column5,column6,column7,column8 +1,fhah,456,46.5,"fsdb, ghfdas" +2,asdhfoih,654,blah,"43asd ""fhgj"" sfadh" +3,ajsdlkfguitah,654,blah,"thesethasdl +asdflkjsadf asdfsadfhl ""adsf, halsdf"" sadfhlasdf" \ No newline at end of file diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/DatabaseTestUtility.php b/tests/PHPUnit/Tests/Extensions/Database/_files/DatabaseTestUtility.php new file mode 100755 index 00000000..ca65cf75 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/DatabaseTestUtility.php @@ -0,0 +1,116 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 4.0.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * + * @category Testing + * @package PHPUnit + * @author Mike Lively + * @copyright 2009 Mike Lively + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 4.0.0 + */ +class DBUnitTestUtility +{ + public static function getSQLiteMemoryDB() + { + static $connection; + + if (empty($connection)) + { + $connection = new PDO('sqlite::memory:'); + self::setUpDatabase($connection); + } + + return $connection; + } + + protected static function setUpDatabase(PDO $connection) + { + $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + + $table1 = " + CREATE TABLE IF NOT EXISTS table1 ( + table1_id INTEGER PRIMARY KEY AUTOINCREMENT, + column1 VARCHAR(20), + column2 INT(10), + column3 DECIMAL(6,2), + column4 TEXT + ) + "; + + $table2 = " + CREATE TABLE IF NOT EXISTS table2 ( + table2_id INTEGER PRIMARY KEY AUTOINCREMENT, + column5 VARCHAR(20), + column6 INT(10), + column7 DECIMAL(6,2), + column8 TEXT + ) + "; + + $table3 = " + CREATE TABLE IF NOT EXISTS table3 ( + table3_id INTEGER PRIMARY KEY AUTOINCREMENT, + column9 VARCHAR(20), + column10 INT(10), + column11 DECIMAL(6,2), + column12 TEXT + ) + "; + + $connection->exec($table1); + $connection->exec($table2); + $connection->exec($table3); + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/AllEmptyTableInsertResult.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/AllEmptyTableInsertResult.xml new file mode 100755 index 00000000..7e402144 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/AllEmptyTableInsertResult.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/AllEmptyTableInsertTest.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/AllEmptyTableInsertTest.xml new file mode 100755 index 00000000..dda12a07 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/AllEmptyTableInsertTest.xml @@ -0,0 +1,4 @@ + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/DeleteAllOperationTest.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/DeleteAllOperationTest.xml new file mode 100755 index 00000000..d82980d7 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/DeleteAllOperationTest.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/DeleteOperationResult.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/DeleteOperationResult.xml new file mode 100755 index 00000000..d7e31bce --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/DeleteOperationResult.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/DeleteOperationTest.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/DeleteOperationTest.xml new file mode 100755 index 00000000..d1e0b984 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/DeleteOperationTest.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/EmptyTableInsertResult.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/EmptyTableInsertResult.xml new file mode 100755 index 00000000..38f3b03e --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/EmptyTableInsertResult.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/EmptyTableInsertTest.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/EmptyTableInsertTest.xml new file mode 100755 index 00000000..5bcbdb75 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/EmptyTableInsertTest.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/FilteredTestComparison.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/FilteredTestComparison.xml new file mode 100755 index 00000000..7e402144 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/FilteredTestComparison.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/FilteredTestFixture.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/FilteredTestFixture.xml new file mode 100755 index 00000000..7087c76d --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/FilteredTestFixture.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/FlatXmlDataSet.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/FlatXmlDataSet.xml new file mode 100755 index 00000000..c180dce2 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/FlatXmlDataSet.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/FlatXmlWriter.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/FlatXmlWriter.xml new file mode 100755 index 00000000..faf98acb --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/FlatXmlWriter.xml @@ -0,0 +1,32 @@ + + + + + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/InsertOperationResult.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/InsertOperationResult.xml new file mode 100755 index 00000000..8c6edacb --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/InsertOperationResult.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/InsertOperationTest.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/InsertOperationTest.xml new file mode 100755 index 00000000..38af84ca --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/InsertOperationTest.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/OperationsTestFixture.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/OperationsTestFixture.xml new file mode 100755 index 00000000..7e402144 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/OperationsTestFixture.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/QueryDataSetTest.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/QueryDataSetTest.xml new file mode 100755 index 00000000..43fb8719 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/QueryDataSetTest.xml @@ -0,0 +1,31 @@ + + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/ReplaceOperationResult.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/ReplaceOperationResult.xml new file mode 100755 index 00000000..d5754d46 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/ReplaceOperationResult.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/ReplaceOperationTest.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/ReplaceOperationTest.xml new file mode 100755 index 00000000..27c5bdbc --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/ReplaceOperationTest.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/RowBasedExecute.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/RowBasedExecute.xml new file mode 100755 index 00000000..1ff47080 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/RowBasedExecute.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/UpdateOperationResult.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/UpdateOperationResult.xml new file mode 100755 index 00000000..e00a9277 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/UpdateOperationResult.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/UpdateOperationTest.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/UpdateOperationTest.xml new file mode 100755 index 00000000..f3eee917 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/UpdateOperationTest.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/XmlDataSet.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/XmlDataSet.xml new file mode 100755 index 00000000..df57efd8 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/XmlDataSet.xml @@ -0,0 +1,65 @@ + + + + table1_id + column1 + column2 + column3 + column4 + + 1 + tgfahgasdf + 200 + 34.64 + yghkf;a hahfg8ja h; + + + 2 + hk;afg + 654 + 46.54 + 24rwehhads + + + 3 + ha;gyt + 462 + 1654.4 + asfgklg + +
+ + table2_id + column5 + column6 + column7 + column8 + + 1 + fhah + 456 + 46.5 + fsdbghfdas + + + 2 + asdhfoih + 654 + + 43asdfhgj + + + 3 + ajsdlkfguitah + 654 + + + +
+ + + + + + +
diff --git a/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/XmlWriter.xml b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/XmlWriter.xml new file mode 100755 index 00000000..57ef5995 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/Database/_files/XmlDataSets/XmlWriter.xml @@ -0,0 +1,28 @@ + + + + col1 + col2 + col3 + + val1 + val2 + val3 + + + + + val4 + + + val5 + val6 + val7 + +
+ + col1 + col2 + col3 +
+
diff --git a/tests/PHPUnit/Tests/Extensions/OutputTestCaseTest.php b/tests/PHPUnit/Tests/Extensions/OutputTestCaseTest.php new file mode 100755 index 00000000..5b511b82 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/OutputTestCaseTest.php @@ -0,0 +1,101 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; + +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'OutputTestCase.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class Extensions_OutputTestCaseTest extends PHPUnit_Framework_TestCase +{ + public function testExpectOutputStringFooActualFoo() + { + $test = new OutputTestCase('testExpectOutputStringFooActualFoo'); + $result = $test->run(); + + $this->assertEquals(1, count($result)); + $this->assertTrue($result->wasSuccessful()); + } + + public function testExpectOutputStringFooActualBar() + { + $test = new OutputTestCase('testExpectOutputStringFooActualBar'); + $result = $test->run(); + + $this->assertEquals(1, count($result)); + $this->assertFalse($result->wasSuccessful()); + } + + public function testExpectOutputRegexFooActualFoo() + { + $test = new OutputTestCase('testExpectOutputRegexFooActualFoo'); + $result = $test->run(); + + $this->assertEquals(1, count($result)); + $this->assertTrue($result->wasSuccessful()); + } + + public function testExpectOutputRegexFooActualBar() + { + $test = new OutputTestCase('testExpectOutputRegexFooActualBar'); + $result = $test->run(); + + $this->assertEquals(1, count($result)); + $this->assertFalse($result->wasSuccessful()); + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/PerformanceTestCaseTest.php b/tests/PHPUnit/Tests/Extensions/PerformanceTestCaseTest.php new file mode 100755 index 00000000..2b8707cf --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/PerformanceTestCaseTest.php @@ -0,0 +1,85 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework/AssertionFailedError.php'; +require_once 'PHPUnit/Framework/TestCase.php'; +require_once 'PHPUnit/Framework/TestResult.php'; + +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'SleepTest.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class Extensions_PerformanceTestCaseTest extends PHPUnit_Framework_TestCase +{ + public function testDoesNotExceedMaxRunningTime() + { + $test = new SleepTest('testSleepTwoSeconds'); + $test->setMaxRunningTime(3); + + $result = $test->run(); + $this->assertEquals(0, $result->failureCount()); + } + + public function testExceedsMaxRunningTime() + { + $test = new SleepTest('testSleepTwoSeconds'); + $test->setMaxRunningTime(1); + + $result = $test->run(); + $this->assertEquals(1, $result->failureCount()); + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/RepeatedTestTest.php b/tests/PHPUnit/Tests/Extensions/RepeatedTestTest.php new file mode 100755 index 00000000..d2cc3340 --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/RepeatedTestTest.php @@ -0,0 +1,118 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; +require_once 'PHPUnit/Framework/TestResult.php'; +require_once 'PHPUnit/Framework/TestSuite.php'; +require_once 'PHPUnit/Extensions/RepeatedTest.php'; + +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'Success.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class Extensions_RepeatedTestTest extends PHPUnit_Framework_TestCase +{ + protected $suite; + + public function __construct() + { + $this->suite = new PHPUnit_Framework_TestSuite; + + $this->suite->addTest(new Success); + $this->suite->addTest(new Success); + } + + public function testRepeatedOnce() + { + $test = new PHPUnit_Extensions_RepeatedTest($this->suite, 1); + $this->assertEquals(2, count($test)); + + $result = $test->run(); + $this->assertEquals(2, count($result)); + } + + public function testRepeatedMoreThanOnce() + { + $test = new PHPUnit_Extensions_RepeatedTest($this->suite, 3); + $this->assertEquals(6, count($test)); + + $result = $test->run(); + $this->assertEquals(6, count($result)); + } + + public function testRepeatedZero() + { + $test = new PHPUnit_Extensions_RepeatedTest($this->suite, 0); + $this->assertEquals(0, count($test)); + + $result = $test->run(); + $this->assertEquals(0, count($result)); + } + + public function testRepeatedNegative() + { + try { + $test = new PHPUnit_Extensions_RepeatedTest($this->suite, -1); + } + + catch (Exception $e) { + return; + } + + $this->fail('Should throw an Exception'); + } +} +?> diff --git a/tests/PHPUnit/Tests/Extensions/SeleniumTestCaseTest.php b/tests/PHPUnit/Tests/Extensions/SeleniumTestCaseTest.php new file mode 100755 index 00000000..51fe12fe --- /dev/null +++ b/tests/PHPUnit/Tests/Extensions/SeleniumTestCaseTest.php @@ -0,0 +1,659 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @author Shin Ohno + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Extensions/SeleniumTestCase.php'; + +/** + * Tests for PHPUnit_Extensions_SeleniumTestCase. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @author Shin Ohno + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class Extensions_SeleniumTestCaseTest extends PHPUnit_Extensions_SeleniumTestCase +{ + protected $url; + + public function setUp() + { + if (!isset($GLOBALS['PHPUNIT_TESTSUITE_EXTENSION_SELENIUM_ENABLED']) || + !$GLOBALS['PHPUNIT_TESTSUITE_EXTENSION_SELENIUM_ENABLED']) { + $this->markTestSkipped( + 'The Selenium tests are disabled.' + ); + } + + $this->url = sprintf( + 'http://%s:%d/selenium-server/tests/', + $GLOBALS['PHPUNIT_TESTSUITE_EXTENSION_SELENIUM_HOST'], + $GLOBALS['PHPUNIT_TESTSUITE_EXTENSION_SELENIUM_PORT'] + ); + + $this->setHost($GLOBALS['PHPUNIT_TESTSUITE_EXTENSION_SELENIUM_HOST']); + $this->setPort((int)$GLOBALS['PHPUNIT_TESTSUITE_EXTENSION_SELENIUM_PORT']); + $this->setBrowser($GLOBALS['PHPUNIT_TESTSUITE_EXTENSION_SELENIUM_BROWSER']); + $this->setBrowserUrl($this->url); + } + + public function testOpen() + { + $this->open($this->url . 'html/test_open.html'); + $this->assertEndsWith('html/test_open.html', $this->getLocation()); + $this->assertEquals('This is a test of the open command.', $this->getBodyText()); + + $this->open($this->url . 'html/test_page.slow.html'); + $this->assertEndsWith('html/test_page.slow.html', $this->getLocation()); + $this->assertEquals('Slow Loading Page', $this->getTitle()); + } + + public function testClick() + { + $this->open($this->url . 'html/test_click_page1.html'); + $this->assertEquals('Click here for next page', $this->getText('link')); + $this->click('link'); + $this->waitForPageToLoad(500); + $this->assertEquals('Click Page Target', $this->getTitle()); + $this->click('previousPage'); + $this->waitForPageToLoad(500); + $this->assertEquals('Click Page 1', $this->getTitle()); + + $this->click('linkWithEnclosedImage'); + $this->waitForPageToLoad(500); + $this->assertEquals('Click Page Target', $this->getTitle()); + $this->click('previousPage'); + $this->waitForPageToLoad(500); + + $this->click('enclosedImage'); + $this->waitForPageToLoad(500); + $this->assertEquals('Click Page Target', $this->getTitle()); + $this->click('previousPage'); + $this->waitForPageToLoad(500); + + $this->click('linkToAnchorOnThisPage'); + $this->assertEquals('Click Page 1', $this->getTitle()); + $this->click('linkWithOnclickReturnsFalse'); + $this->assertEquals('Click Page 1', $this->getTitle()); + + } + + public function testClickJavaScriptHref() + { + $this->open($this->url . 'html/test_click_javascript_page.html'); + $this->click('link'); + $this->assertTrue($this->isAlertPresent()); + $this->assertEquals('link clicked: foo', $this->getAlert()); + + $this->click('linkWithMultipleJavascriptStatements'); + $this->assertEquals('alert1', $this->getAlert()); + $this->assertEquals('alert2', $this->getAlert()); + $this->assertEquals('alert3', $this->getAlert()); + + $this->click('linkWithJavascriptVoidHref'); + $this->assertEquals('onclick', $this->getAlert()); + $this->assertEquals('Click Page 1', $this->getTitle()); + + $this->click('linkWithOnclickReturnsFalse'); + $this->assertEquals('Click Page 1', $this->getTitle()); + + $this->click('enclosedImage'); + $this->assertEquals('enclosedImage clicked', $this->getAlert()); + } + + public function testType() + { + $this->open($this->url . 'html/test_type_page1.html'); + $this->type('username', 'TestUser'); + $this->assertEquals('TestUser', $this->getValue('username')); + $this->type('password', 'testUserPassword'); + $this->assertEquals('testUserPassword', $this->getValue('password')); + + $this->click('submitButton'); + $this->waitForPageToLoad(500); + $this->assertRegExp('/Welcome, TestUser!/', $this->getText('//h2')); + } + + public function testSelect() + { + $this->open($this->url . 'html/test_select.html'); + $this->assertEquals('Second Option', $this->getSelectedLabel('theSelect')); + $this->assertEquals('option2', $this->getSelectedValue('theSelect')); + + $this->select('theSelect', 'index=4'); + $this->assertEquals('Fifth Option', $this->getSelectedLabel('theSelect')); + $this->assertEquals('o4', $this->getSelectedId('theSelect')); + + $this->select('theSelect', 'Third Option'); + $this->assertEquals('Third Option', $this->getSelectedLabel('theSelect')); + + $this->select('theSelect', 'label=Fourth Option'); + $this->assertEquals('Fourth Option', $this->getSelectedLabel('theSelect')); + + $this->select('theSelect', 'value=option6'); + $this->assertEquals('Sixth Option', $this->getSelectedLabel('theSelect')); + + $this->select('theSelect', 'value='); + $this->assertEquals('Empty Value Option', $this->getSelectedLabel('theSelect')); + + $this->select('theSelect', 'id=o4'); + $this->assertEquals('Fourth Option', $this->getSelectedLabel('theSelect')); + + $this->select('theSelect', ''); + $this->assertEquals('', $this->getSelectedLabel('theSelect')); + + } + + public function testMultiSelect() + { + $this->open($this->url . 'html/test_multiselect.html'); + $this->assertEquals('Second Option', $this->getSelectedLabel('theSelect')); + + $this->select('theSelect', 'index=4'); + $this->assertEquals('Fifth Option', $this->getSelectedLabel('theSelect')); + + $this->addSelection('theSelect', 'Third Option'); + $this->addSelection('theSelect', 'value='); + $this->assertTrue(in_array('Third Option', $this->getSelectedLabels('theSelect'))); + $this->assertTrue(in_array('Fifth Option', $this->getSelectedLabels('theSelect'))); + $this->assertTrue(in_array('Empty Value Option', $this->getSelectedLabels('theSelect'))); + $this->assertEquals(3, count($this->getSelectedLabels('theSelect'))); + + $this->removeSelection('theSelect', 'id=o7'); + $this->assertFalse(in_array('Empty Value Option', $this->getSelectedLabels('theSelect'))); + $this->assertEquals(2, count($this->getSelectedLabels('theSelect'))); + + $this->removeSelection('theSelect', 'label=Fifth Option'); + $this->assertFalse(in_array('Fifth Option', $this->getSelectedLabels('theSelect'))); + $this->assertEquals(1, count($this->getSelectedLabels('theSelect'))); + + $this->addSelection('theSelect', ''); + $this->assertEquals(2, count($this->getSelectedLabels('theSelect'))); + } + + public function testSubmit() + { + $this->open($this->url . 'html/test_submit.html'); + $this->submit('searchForm'); + $this->assertTrue($this->isAlertPresent()); + $this->assertEquals('onsubmit called', $this->getAlert()); + + $this->check('okayToSubmit'); + $this->submit('searchForm'); + $this->assertEquals('onsubmit called', $this->getAlert()); + $this->assertEquals('form submitted', $this->getAlert()); + } + + public function testCheckUncheck() + { + $this->open($this->url . 'html/test_check_uncheck.html'); + $this->assertEquals('on', $this->getValue('base-spud')); + $this->assertNotEquals('on', $this->getValue('base-rice')); + $this->assertEquals('on', $this->getValue('option-cheese')); + $this->assertNotEquals('on', $this->getValue('option-onions')); + + $this->check('base-rice'); + $this->assertNotEquals('on', $this->getValue('base-spud')); + $this->assertEquals('on', $this->getValue('base-rice')); + $this->uncheck('option-cheese'); + $this->assertEquals('off', $this->getValue('option-cheese')); + $this->check('option-onions'); + $this->assertNotEquals('off', $this->getValue('option-onions')); + + $this->assertNotEquals('on', $this->getValue('option-chilli')); + $this->check('option-chilli'); + $this->assertEquals('on', $this->getValue('option-chilli')); + $this->uncheck('option index=3'); + $this->assertNotEquals('on', $this->getValue('option-chilli')); + } + + public function testSelectWindow() + { + $this->open($this->url . 'html/test_select_window.html'); + $this->click('popupPage'); + $this->waitForPopUp('myPopupWindow', 1000); + $this->selectWindow('myPopupWindow'); + $this->assertEndsWith('html/test_select_window_popup.html', $this->getLocation()); + $this->assertEquals('Select Window Popup', $this->getTitle()); + $this->close(); + $this->selectWindow('null'); + + $this->assertEndsWith('html/test_select_window.html', $this->getLocation()); + $this->click('popupPage'); + $this->waitForPopUp('myNewWindow', 1000); + $this->selectWindow('myNewWindow'); + $this->assertEndsWith('html/test_select_window_popup.html', $this->getLocation()); + $this->close(); + $this->selectWindow('null'); + + $this->click('popupAnonymous'); + $this->waitForPopUp('anonymouspopup', 1000); + $this->selectWindow('anonymouspopup'); + $this->assertEndsWith('html/test_select_window_popup.html', $this->getLocation()); + $this->click('closePage'); + } + + public function testJavaScriptParameters() + { + $this->open($this->url . 'html/test_store_value.html'); + $this->type('theText', "javascript{[1,2,3,4,5].join(':')}"); + $this->assertEquals('1:2:3:4:5', $this->getValue('theText')); + + $this->type('theText', 'javascript{10 * 5}'); + $this->assertEquals('50', $this->getValue('theText')); + } + + public function testWait() + { + $this->open($this->url . 'html/test_reload_onchange_page.html'); + $this->select('theSelect', 'Second Option'); + $this->waitForPageToLoad(5000); + $this->assertEquals('Slow Loading Page', $this->getTitle()); + $this->goBack(); + $this->waitForPageToLoad(5000); + + $this->type('theTextbox', 'new value'); + $this->fireEvent('theTextbox', 'blur'); + $this->waitForPageToLoad(5000); + $this->assertEquals('Slow Loading Page', $this->getTitle()); + + $this->goBack(); + $this->waitForPageToLoad(5000); + + $this->click('theSubmit'); + $this->waitForPageToLoad(5000); + $this->assertEquals('Slow Loading Page', $this->getTitle()); + + $this->click('slowPage_reload'); + $this->waitForPageToLoad(5000); + $this->assertEquals('Slow Loading Page', $this->getTitle()); + } + + public function testWaitInPopupWindow() + { + $this->open($this->url . 'html/test_select_window.html'); + $this->click('popupPage'); + $this->waitForPopUp('myPopupWindow', 500); + $this->selectWindow('myPopupWindow'); + $this->assertEquals('Select Window Popup', $this->getTitle()); + + $this->setTimeout(2000); + $this->click('link=Click to load new page'); + // XXX NEED TO CHECK + $this->waitForPageToLoad(2000); + $this->assertEquals('Reload Page', $this->getTitle()); + + $this->setTimeout(30000); + $this->click('link=Click here'); + // XXX NEED TO CHECK + $this->waitForPageToLoad(30000); + $this->assertEquals('Slow Loading Page', $this->getTitle()); + + $this->close(); + $this->selectWindow('null'); + } + + public function testLocators() + { + $this->open($this->url . 'html/test_locators.html'); + $this->assertEquals('this is the first element', $this->getText('id=id1')); + $this->assertFalse($this->isElementPresent('id=name1')); + $this->assertFalse($this->isElementPresent('id=id4')); + $this->assertEquals('a1', $this->getAttribute('id=id1@class')); + + $this->assertEquals('this is the second element', $this->getText('name=name1')); + $this->assertFalse($this->isElementPresent('name=id1')); + $this->assertFalse($this->isElementPresent('name=notAName')); + $this->assertEquals('a2', $this->getAttribute('name=name1@class')); + + $this->assertEquals('this is the first element', $this->getText('identifier=id1')); + $this->assertFalse($this->isElementPresent('identifier=id4')); + $this->assertEquals('a1', $this->getAttribute('identifier=id1@class')); + $this->assertEquals('this is the second element', $this->getText('identifier=name1')); + $this->assertEquals('a2', $this->getAttribute('identifier=name1@class')); + + $this->assertEquals('this is the second element', $this->getText('dom=document.links[1]')); + $this->assertEquals('a2', $this->getAttribute('dom=document.links[1]@class')); + $this->assertFalse($this->isElementPresent('dom=document.links[9]')); + $this->assertFalse($this->isElementPresent('dom=foo')); + } + + public function testImplicitLocators() + { + $this->open($this->url . 'html/test_locators.html'); + $this->assertEquals('this is the first element', $this->getText('id1')); + $this->assertEquals('a1', $this->getAttribute('id1@class')); + + $this->assertEquals('this is the second element', $this->getText('name1')); + $this->assertEquals('a2', $this->getAttribute('name1@class')); + + $this->assertEquals('this is the second element', $this->getText('document.links[1]')); + $this->assertEquals('a2', $this->getAttribute('document.links[1]@class')); + + $this->assertEquals('this is the second element', $this->getText('//body/a[2]')); + } + + public function testXPathLocators() + { + $this->open($this->url . 'html/test_locators.html'); + $this->assertEquals('this is the first element', $this->getText('xpath=//a')); + $this->assertEquals('this is the second element', $this->getText("xpath=//a[@class='a2']")); + $this->assertEquals('this is the second element', $this->getText("xpath=//*[@class='a2']")); + $this->assertEquals('this is the second element', $this->getText('xpath=//a[2]')); + $this->assertFalse($this->isElementPresent("xpath=//a[@href='foo']")); + + $this->assertEquals('a1', $this->getAttribute("xpath=//a[contains(@href, '#id1')]/@class")); + $this->assertTrue($this->isElementPresent("//a[text()='this is the second element']")); + + $this->assertEquals('this is the first element', $this->getText('xpath=//a')); + $this->assertEquals('a1', $this->getAttribute("//a[contains(@href, '#id1')]/@class")); + + $this->assertEquals('theCellText', $this->getText("xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td")); + + $this->click("//input[@name='name2' and @value='yes']"); + } + + public function testGoBack() + { + $this->open($this->url . 'html/test_click_page1.html'); + $this->assertEquals('Click Page 1', $this->getTitle()); + + $this->click('link'); + $this->waitForPageToLoad(500); + $this->assertEquals('Click Page Target', $this->getTitle()); + + $this->goBack(); + $this->waitForPageToLoad(500); + $this->assertEquals('Click Page 1', $this->getTitle()); + } + + public function testRefresh() + { + $this->open($this->url . 'html/test_page.slow.html'); + $this->assertEndsWith('html/test_page.slow.html', $this->getLocation()); + $this->assertEquals('Slow Loading Page', $this->getTitle()); + + $this->click('changeSpan'); + $this->assertEquals('Changed the text', $this->getText('theSpan')); + $this->refresh(); + $this->waitForPageToLoad(500); + $this->assertNotEquals('Changed the text', $this->getText('theSpan')); + + $this->click('changeSpan'); + $this->assertEquals('Changed the text', $this->getText('theSpan')); + $this->click('slowRefresh'); + } + + public function testLinkEvents() + { + $this->open($this->url . 'html/test_form_events.html'); + $this->assertEquals('', $this->getValue('eventlog')); + $this->click('theLink'); + $this->assertEquals('{focus(theLink)} {click(theLink)}', $this->getValue('eventlog')); + $this->assertEquals('link clicked', $this->getAlert()); + $this->click('theButton'); + } + + public function testButtonEvents() + { + $this->open($this->url . 'html/test_form_events.html'); + $this->assertEquals('', $this->getValue('eventlog')); + $this->click('theButton'); + $this->assertEquals('{focus(theButton)} {click(theButton)}', $this->getValue('eventlog')); + $this->type('eventlog', ''); + + $this->click('theSubmit'); + $this->assertEquals('{focus(theSubmit)} {click(theSubmit)} {submit}', $this->getValue('eventlog')); + + } + + public function testSelectEvents() + { + $this->open($this->url . 'html/test_form_events.html'); + $this->assertEquals('', $this->getValue('theSelect')); + $this->assertEquals('', $this->getValue('eventlog')); + + $this->select('theSelect', 'First Option'); + $this->assertEquals('option1', $this->getValue('theSelect')); + $this->assertEquals('{focus(theSelect)} {change(theSelect)}', $this->getValue('eventlog')); + + $this->type('eventlog', ''); + $this->select('theSelect', 'First Option'); + $this->assertEquals('option1', $this->getValue('theSelect')); + $this->assertEquals('{focus(theSelect)}', $this->getValue('eventlog')); + + $this->type('eventlog', ''); + $this->select('theSelect', 'Empty Option'); + $this->assertEquals('', $this->getValue('theSelect')); + $this->assertEquals('{focus(theSelect)} {change(theSelect)}', $this->getValue('eventlog')); + + } + + public function testRadioEvents() + { + $this->open($this->url . 'html/test_form_events.html'); + $this->assertEquals('off', $this->getValue('theRadio1')); + $this->assertEquals('off', $this->getValue('theRadio2')); + $this->assertEquals('', $this->getValue('eventlog')); + + $this->click('theRadio1'); + $this->assertEquals('on', $this->getValue('theRadio1')); + $this->assertEquals('off', $this->getValue('theRadio2')); + $this->assertEquals('{focus(theRadio1)} {click(theRadio1)} {change(theRadio1)}', $this->getValue('eventlog')); + + $this->type('eventlog', ''); + $this->click('theRadio2'); + $this->assertEquals('off', $this->getValue('theRadio1')); + $this->assertEquals('on', $this->getValue('theRadio2')); + $this->assertEquals('{focus(theRadio2)} {click(theRadio2)} {change(theRadio2)}', $this->getValue('eventlog')); + + + $this->type('eventlog', ''); + $this->click('theRadio2'); + $this->assertEquals('off', $this->getValue('theRadio1')); + $this->assertEquals('on', $this->getValue('theRadio2')); + $this->assertEquals('{focus(theRadio2)} {click(theRadio2)}', $this->getValue('eventlog')); + } + + public function testCheckboxEvents() + { + $this->open($this->url . 'html/test_form_events.html'); + $this->assertEquals('off', $this->getValue('theCheckbox')); + $this->assertEquals('', $this->getValue('eventlog')); + + $this->click('theCheckbox'); + $this->assertEquals('on', $this->getValue('theCheckbox')); + $this->assertEquals('{focus(theCheckbox)} {click(theCheckbox)} {change(theCheckbox)}', $this->getValue('eventlog')); + + $this->type('eventlog', ''); + $this->click('theCheckbox'); + $this->assertEquals('off', $this->getValue('theCheckbox')); + $this->assertEquals('{focus(theCheckbox)} {click(theCheckbox)} {change(theCheckbox)}', $this->getValue('eventlog')); + } + + public function testTextEvents() + { + $this->open($this->url . 'html/test_form_events.html'); + $this->assertEquals('', $this->getValue('theTextbox')); + $this->assertEquals('', $this->getValue('eventlog')); + + $this->type('theTextbox', 'first value'); + $this->assertEquals('first value', $this->getValue('theTextbox')); + $this->assertEquals('{focus(theTextbox)} {select(theTextbox)} {change(theTextbox)}', $this->getValue('eventlog')); + + $this->type('eventlog', ''); + $this->type('theTextbox', 'changed value'); + $this->assertEquals('changed value', $this->getValue('theTextbox')); + $this->assertEquals('{focus(theTextbox)} {select(theTextbox)} {change(theTextbox)}', $this->getValue('eventlog')); + } + + public function testFireEvents() + { + $this->open($this->url .'html/test_form_events.html'); + $this->assertEquals('', $this->getValue('eventlog')); + $this->fireEvent('theTextbox', 'focus'); + $this->assertEquals('{focus(theTextbox)}', $this->getValue('eventlog')); + + $this->type('eventlog', ''); + $this->fireEvent('theSelect', 'change'); + $this->fireEvent('theSelect', 'blur'); + $this->assertEquals('{change(theSelect)} {blur(theSelect)}', $this->getValue('eventlog')); + + $this->type('theTextbox', 'changed value'); + } + + public function testMouseEvents() + { + $this->open($this->url . 'html/test_form_events.html'); + $this->mouseOver('theTextbox'); + $this->mouseOver('theButton'); + $this->mouseDown('theTextbox'); + $this->mouseDown('theButton'); + $this->assertEquals('{mouseover(theTextbox)} {mouseover(theButton)} {mousedown(theTextbox)} {mousedown(theButton)}', $this->getValue('eventlog')); + } + + public function testKeyEvents() + { + $this->open($this->url . 'html/test_form_events.html'); + $this->keyPress('theTextbox', '119'); + $this->keyPress('theTextbox', '115'); + $this->keyUp('theTextbox', '44'); + $this->keyDown('theTextbox', '98'); + $this->assertEquals('{keypress(theTextbox - 119)} {keypress(theTextbox - 115)} {keyup(theTextbox - 44)} {keydown(theTextbox - 98)}', $this->getValue('eventlog')); + } + + public function testFocusOnBlur() + { + $this->open($this->url . 'html/test_focus_on_blur.html'); + $this->type('testInput', 'test'); + $this->fireEvent('testInput', 'blur'); + $this->assertEquals('Bad value', $this->getAlert()); + $this->type('testInput', 'somethingelse'); + } + + public function testAlerts() + { + $this->open($this->url . 'html/test_verify_alert.html'); + $this->assertFalse($this->isAlertPresent()); + + $this->click('oneAlert'); + $this->assertTrue($this->isAlertPresent()); + $this->assertEquals('Store Below 494 degrees K!', $this->getAlert()); + + $this->click('twoAlerts'); + $this->assertEquals('Store Below 220 degrees C!', $this->getAlert()); + $this->assertEquals('Store Below 429 degrees F!', $this->getAlert()); + $this->click('alertAndLeave'); + $this->waitForPageToLoad(500); + $this->assertEquals("I'm Melting! I'm Melting!", $this->getAlert()); + } + + public function testConfirmations() + { + $this->open($this->url . 'html/test_confirm.html'); + $this->chooseCancelOnNextConfirmation(); + $this->click('confirmAndLeave'); + $this->assertTrue($this->isConfirmationPresent()); + $this->assertEquals('You are about to go to a dummy page.', $this->getConfirmation()); + $this->assertEquals('Test Confirm', $this->getTitle()); + + $this->click('confirmAndLeave'); + $this->waitForPageToLoad(500); + $this->assertEquals('You are about to go to a dummy page.', $this->getConfirmation()); + $this->assertEquals('Dummy Page', $this->getTitle()); + } + + public function testPrompt() + { + $this->open($this->url . 'html/test_prompt.html'); + $this->assertFalse($this->isPromptPresent()); + + $this->click('promptAndLeave'); + $this->assertTrue($this->isPromptPresent()); + $this->assertEquals("Type 'yes' and click OK", $this->getPrompt()); + $this->assertEquals('Test Prompt', $this->getTitle()); + $this->answerOnNextPrompt('yes'); + $this->click('promptAndLeave'); + + $this->waitForPageToLoad(500); + $this->assertEquals("Type 'yes' and click OK", $this->getPrompt()); + $this->assertEquals('Dummy Page', $this->getTitle()); + } + + public function testVisibility() + { + $this->open($this->url . 'html/test_visibility.html'); + $this->assertTrue($this->isVisible('visibleParagraph')); + $this->assertFalse($this->isVisible('hiddenParagraph')); + $this->assertFalse($this->isVisible('suppressedParagraph')); + $this->assertFalse($this->isVisible('classSuppressedParagraph')); + $this->assertFalse($this->isVisible('jsClassSuppressedParagraph')); + $this->assertFalse($this->isVisible('hiddenSubElement')); + $this->assertTrue($this->isVisible('visibleSubElement')); + $this->assertFalse($this->isVisible('suppressedSubElement')); + $this->assertFalse($this->isVisible('jsHiddenParagraph')); + } + + public function testEditable() + { + $this->open($this->url . 'html/test_editable.html'); + $this->assertTrue($this->isEditable('normal_text')); + $this->assertTrue($this->isEditable('normal_select')); + $this->assertFalse($this->isEditable('disabled_text')); + $this->assertFalse($this->isEditable('disabled_select')); + } + + protected function assertEndsWith($substring, $actual) + { + $this->assertRegExp('/' . preg_quote($substring, '/') . '$/', $actual); + } +} +?> diff --git a/tests/PHPUnit/Tests/Framework/AllTests.php b/tests/PHPUnit/Tests/Framework/AllTests.php new file mode 100755 index 00000000..2d2fddc9 --- /dev/null +++ b/tests/PHPUnit/Tests/Framework/AllTests.php @@ -0,0 +1,96 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__); + +require_once 'PHPUnit/Framework/TestSuite.php'; + +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'AssertTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ComparisonFailureTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ConstraintTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'MockObjectTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'SuiteTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'TestCaseTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'TestFailureTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'TestImplementorTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'TestListenerTest.php'; + +PHPUnit_Util_Filter::$filterPHPUnit = FALSE; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class Framework_AllTests +{ + public static function suite() + { + $suite = new PHPUnit_Framework_TestSuite('PHPUnit_Framework'); + + $suite->addTestSuite('Framework_AssertTest'); + $suite->addTestSuite('Framework_ComparisonFailureTest'); + $suite->addTestSuite('Framework_ConstraintTest'); + $suite->addTestSuite('Framework_MockObjectTest'); + $suite->addTestSuite('Framework_SuiteTest'); + $suite->addTestSuite('Framework_TestCaseTest'); + $suite->addTestSuite('Framework_TestFailureTest'); + $suite->addTestSuite('Framework_TestImplementorTest'); + $suite->addTestSuite('Framework_TestListenerTest'); + + return $suite; + } +} +?> diff --git a/tests/PHPUnit/Tests/Framework/AssertTest.php b/tests/PHPUnit/Tests/Framework/AssertTest.php new file mode 100755 index 00000000..4c92bd30 --- /dev/null +++ b/tests/PHPUnit/Tests/Framework/AssertTest.php @@ -0,0 +1,3161 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; + +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'ClassWithNonPublicAttributes.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'SampleClass.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'Struct.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'TestIterator.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'WasRun.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class Framework_AssertTest extends PHPUnit_Framework_TestCase +{ + protected $filesDirectory; + + protected function setUp() + { + $this->filesDirectory = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR; + + if (isset($this->html)) { return; } + $this->html = file_get_contents( + $this->filesDirectory . 'SelectorAssertionsFixture.html' + ); + } + + public function testFail() + { + try { + $this->fail(); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertSplObjectStorageContainsObject() + { + $a = new stdClass; + $b = new stdClass; + $c = new SplObjectStorage; + $c->attach($a); + + $this->assertContains($a, $c); + + try { + $this->assertContains($b, $c); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + /** + * @covers PHPUnit_Framework_Assert::assertContains + */ + public function testAssertArrayContainsObject() + { + $a = new stdClass; + $b = new stdClass; + + $this->assertContains($a, array($a)); + + try { + $this->assertContains($a, array($b)); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertArrayContainsString() + { + $this->assertContains('foo', array('foo')); + + try { + $this->assertContains('foo', array('bar')); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertArrayHasIntegerKey() + { + $this->assertArrayHasKey(0, array('foo')); + + try { + $this->assertArrayHasKey(1, array('foo')); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertArrayNotHasIntegerKey() + { + $this->assertArrayNotHasKey(1, array('foo')); + + try { + $this->assertArrayNotHasKey(0, array('foo')); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertArrayHasStringKey() + { + $this->assertArrayHasKey('foo', array('foo' => 'bar')); + + try { + $this->assertArrayHasKey('bar', array('foo' => 'bar')); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertArrayNotHasStringKey() + { + $this->assertArrayNotHasKey('bar', array('foo' => 'bar')); + + try { + $this->assertArrayNotHasKey('foo', array('foo' => 'bar')); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertIteratorContainsObject() + { + $foo = new stdClass; + + $this->assertContains($foo, new TestIterator(array($foo))); + + try { + $this->assertContains($foo, new TestIterator(array(new stdClass))); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertIteratorContainsString() + { + $this->assertContains('foo', new TestIterator(array('foo'))); + + try { + $this->assertContains('foo', new TestIterator(array('bar'))); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertStringContainsString() + { + $this->assertContains('foo', 'foobar'); + + try { + $this->assertContains('foo', 'bar'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertSplObjectStorageNotContainsObject() + { + $a = new stdClass; + $b = new stdClass; + $c = new SplObjectStorage; + $c->attach($a); + + $this->assertNotContains($b, $c); + + try { + $this->assertNotContains($a, $c); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + /** + * @covers PHPUnit_Framework_Assert::assertNotContains + */ + public function testAssertArrayNotContainsObject() + { + $a = new stdClass; + $b = new stdClass; + + $this->assertNotContains($a, array($b)); + + try { + $this->assertNotContains($a, array($a)); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertArrayNotContainsString() + { + $this->assertNotContains('foo', array('bar')); + + try { + $this->assertNotContains('foo', array('foo')); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertStringNotContainsString() + { + $this->assertNotContains('foo', 'bar'); + + try { + $this->assertNotContains('foo', 'foo'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertArrayContainsOnlyIntegers() + { + $this->assertContainsOnly('integer', array(1, 2, 3)); + + try { + $this->assertContainsOnly('integer', array("1", 2, 3)); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertArrayNotContainsOnlyIntegers() + { + $this->assertNotContainsOnly('integer', array("1", 2, 3)); + + try { + $this->assertNotContainsOnly('integer', array(1, 2, 3)); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertArrayContainsOnlyStdClass() + { + $this->assertContainsOnly('StdClass', array(new StdClass)); + + try { + $this->assertContainsOnly('StdClass', array('StdClass')); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertArrayNotContainsOnlyStdClass() + { + $this->assertNotContainsOnly('StdClass', array('StdClass')); + + try { + $this->assertNotContainsOnly('StdClass', array(new StdClass)); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsArray() + { + $this->assertEquals(array('a', 'b' => array(1, 2)), array('a', 'b' => array(1, 2))); + + try { + $this->assertEquals(array('a', 'b' => array(1, 2)), array('a', 'b' => array(2, 1))); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotEqualsArray() + { + $this->assertNotEquals(array('a', 'b' => array(1, 2)), array('a', 'b' => array(2, 1))); + + try { + $this->assertNotEquals(array('a', 'b' => array(1, 2)), array('a', 'b' => array(1, 2))); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsFloat() + { + $this->assertEquals(2.3, 2.3); + + try { + $this->assertEquals(2.3, 4.2); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotEqualsFloat() + { + $this->assertNotEquals(2.3, 4.2); + + try { + $this->assertNotEquals(2.3, 2.3); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsFloatDelta() + { + $this->assertEquals(2.3, 2.5, '', 0.5); + + try { + $this->assertEquals(2.3, 4.2, '', 0.5); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotEqualsFloatDelta() + { + $this->assertNotEquals(2.3, 4.2, '', 0.5); + + try { + $this->assertNotEquals(2.3, 2.5, '', 0.5); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsArrayFloatDelta() + { + $this->assertEquals(array(2.3), array(2.5), '', 0.5); + + try { + $this->assertEquals(array(2.3), array(4.2), '', 0.5); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotEqualsArrayFloatDelta() + { + $this->assertNotEquals(array(2.3), array(4.2), '', 0.5); + + try { + $this->assertNotEquals(array(2.3), array(2.5), '', 0.5); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsStructFloatDelta() + { + $this->assertEquals(new Struct(2.3), new Struct(2.5), '', 0.5); + + try { + $this->assertEquals(new Struct(2.3), new Struct(4.2), '', 0.5); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotEqualsStructFloatDelta() + { + $this->assertNotEquals(new Struct(2.3), new Struct(4.2), '', 0.5); + + try { + $this->assertNotEquals(new Struct(2.3), new Struct(2.5), '', 0.5); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsArrayStructFloatDelta() + { + $this->assertEquals(array(new Struct(2.3)), array(new Struct(2.5)), '', 0.5); + + try { + $this->assertEquals(array(new Struct(2.3)), array(new Struct(4.2)), '', 0.5); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotEqualsArrayStructFloatDelta() + { + $this->assertNotEquals(array(new Struct(2.3)), array(new Struct(4.2)), '', 0.5); + + try { + $this->assertNotEquals(array(new Struct(2.3)), array(new Struct(2.5)), '', 0.5); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsArrayOfArrayFloatDelta() + { + $this->assertEquals(array(array(2.3)), array(array(2.5)), '', 0.5); + + try { + $this->assertEquals(array(array(2.3)), array(array(4.2)), '', 0.5); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotEqualsArrayOfArrayFloatDelta() + { + $this->assertNotEquals(array(array(2.3)), array(array(4.2)), '', 0.5); + + try { + $this->assertNotEquals(array(array(2.3)), array(array(2.5)), '', 0.5); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsInteger() + { + $this->assertEquals(23, 23); + + try { + $this->assertEquals(23, 42); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotEqualsInteger() + { + $this->assertNotEquals(23, 42); + + try { + $this->assertNotEquals(23, 23); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsObject() + { + $a = new SampleClass( 4, 8, 15); + $b = new SampleClass(16, 23, 42); + + $this->assertEquals($a, $a); + + try { + $this->assertEquals($a, $b); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotEqualsObject() + { + $a = new SampleClass( 4, 8, 15); + $b = new SampleClass(16, 23, 42); + + $this->assertNotEquals($a, $b); + + try { + $this->assertNotEquals($a, $a); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsSplObjectStorage() + { + $a = new SampleClass( 4, 8, 15); + $b = new SampleClass(16, 23, 42); + + $c = new SplObjectStorage; + $c->attach($a); + + $d = new SplObjectStorage; + $d->attach($b); + + $this->assertEquals($c, $c); + + try { + $this->assertEquals($c, $d); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + /** + * @covers PHPUnit_Framework_Assert::assertNotEquals + */ + public function testAssertNotEqualsSplObjectStorage() + { + $a = new SampleClass( 4, 8, 15); + $b = new SampleClass(16, 23, 42); + + $c = new SplObjectStorage; + $c->attach($a); + + $d = new SplObjectStorage; + $d->attach($b); + + $this->assertNotEquals($c, $d); + + try { + $this->assertNotEquals($c, $c); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + /** + * @covers PHPUnit_Framework_Assert::assertEquals + */ + public function testAssertEqualsString() + { + $this->assertEquals('ab', 'ab'); + + try { + $this->assertEquals('ab', 'ba'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotEqualsString() + { + $this->assertNotEquals('ab', 'ba'); + + try { + $this->assertNotEquals('ab', 'ab'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertXmlFileEqualsXmlFile() + { + $this->assertXmlFileEqualsXmlFile( + dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'foo.xml', + dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'foo.xml' + ); + + try { + $this->assertXmlFileEqualsXmlFile( + dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'foo.xml', + dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'bar.xml' + ); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertXmlFileNotEqualsXmlFile() + { + $this->assertXmlFileNotEqualsXmlFile( + dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'foo.xml', + dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'bar.xml' + ); + + try { + $this->assertXmlFileNotEqualsXmlFile( + dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'foo.xml', + dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'foo.xml' + ); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertXmlStringEqualsXmlString() + { + $this->assertXmlStringEqualsXmlString('', ''); + + try { + $this->assertXmlStringEqualsXmlString('', ''); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertXmlStringNotEqualsXmlString() + { + $this->assertXmlStringNotEqualsXmlString('', ''); + + try { + $this->assertXmlStringNotEqualsXmlString('', ''); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsDOMDocument() + { + $expected = new DOMDocument; + $expected->preserveWhiteSpace = FALSE; + $expected->loadXML(''); + + $actual = new DOMDocument; + $actual->preserveWhiteSpace = FALSE; + $actual->loadXML(''); + + $this->assertEquals($expected, $actual); + + try { + $this->assertNotEquals($expected, $actual); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsDOMDocument2() + { + $expected = new DOMDocument; + $expected->preserveWhiteSpace = FALSE; + $expected->loadXML(''); + + $actual = new DOMDocument; + $actual->preserveWhiteSpace = FALSE; + $actual->loadXML(''); + + $this->assertNotEquals($expected, $actual); + + try { + $this->assertEquals($expected, $actual); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsDOMDocument3() + { + $expected = new DOMDocument; + $expected->preserveWhiteSpace = FALSE; + $expected->loadXML(''); + + $actual = new DOMDocument; + $actual->preserveWhiteSpace = FALSE; + $actual->loadXML(''); + + $this->assertEquals($expected, $actual); + + try { + $this->assertNotEquals($expected, $actual); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsDOMDocument4() + { + $expected = new DOMDocument; + $expected->preserveWhiteSpace = FALSE; + $expected->loadXML(''); + + $actual = new DOMDocument; + $actual->preserveWhiteSpace = FALSE; + $actual->loadXML(''); + + $this->assertEquals($expected, $actual); + + try { + $this->assertNotEquals($expected, $actual); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsDOMDocument5() + { + $expected = new DOMDocument; + $expected->preserveWhiteSpace = FALSE; + $expected->loadXML(''); + + $actual = new DOMDocument; + $actual->preserveWhiteSpace = FALSE; + $actual->loadXML(''); + + $this->assertNotEquals($expected, $actual); + + try { + $this->assertEquals($expected, $actual); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsDOMDocument6() + { + $expected = new DOMDocument; + $expected->preserveWhiteSpace = FALSE; + $expected->loadXML(' bar '); + + $actual = new DOMDocument; + $actual->preserveWhiteSpace = FALSE; + $actual->loadXML(''); + + $this->assertNotEquals($expected, $actual); + + try { + $this->assertEquals($expected, $actual); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsDOMDocument7() + { + $expected = new DOMDocument; + $expected->preserveWhiteSpace = FALSE; + $expected->loadXML(''); + + $actual = new DOMDocument; + $actual->preserveWhiteSpace = FALSE; + $actual->loadXML(''); + + $this->assertNotEquals($expected, $actual); + + try { + $this->assertEquals($expected, $actual); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsDOMDocument8() + { + $expected = new DOMDocument; + $expected->preserveWhiteSpace = FALSE; + $expected->loadXML("\n \n"); + + $actual = new DOMDocument; + $actual->preserveWhiteSpace = FALSE; + $actual->loadXML(''); + + $this->assertEquals($expected, $actual); + + try { + $this->assertNotEquals($expected, $actual); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertEqualsDOMDocument9() + { + $expected = new DOMDocument; + $expected->preserveWhiteSpace = FALSE; + $expected->loadXML(' bar '); + + $actual = new DOMDocument; + $actual->preserveWhiteSpace = FALSE; + $actual->loadXML(' bir '); + + $this->assertNotEquals($expected, $actual); + + try { + $this->assertEquals($expected, $actual); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testXMLStructureIsSame() + { + $expected = new DOMDocument; + $expected->load($this->filesDirectory . 'structureExpected.xml'); + + $actual = new DOMDocument; + $actual->load($this->filesDirectory . 'structureExpected.xml'); + + $this->assertEqualXMLStructure( + $expected->firstChild, $actual->firstChild, TRUE + ); + } + + /** + * @expectedException PHPUnit_Framework_ExpectationFailedException + */ + public function testXMLStructureWrongNumberOfAttributes() + { + $expected = new DOMDocument; + $expected->load($this->filesDirectory . 'structureExpected.xml'); + + $actual = new DOMDocument; + $actual->load($this->filesDirectory . 'structureWrongNumberOfAttributes.xml'); + + $this->assertEqualXMLStructure( + $expected->firstChild, $actual->firstChild, TRUE + ); + } + + /** + * @expectedException PHPUnit_Framework_ExpectationFailedException + */ + public function testXMLStructureWrongNumberOfNodes() + { + $expected = new DOMDocument; + $expected->load($this->filesDirectory . 'structureExpected.xml'); + + $actual = new DOMDocument; + $actual->load($this->filesDirectory . 'structureWrongNumberOfNodes.xml'); + + $this->assertEqualXMLStructure( + $expected->firstChild, $actual->firstChild, TRUE + ); + } + + public function testXMLStructureIsSameButDataIsNot() + { + $expected = new DOMDocument; + $expected->load($this->filesDirectory . 'structureExpected.xml'); + + $actual = new DOMDocument; + $actual->load($this->filesDirectory . 'structureIsSameButDataIsNot.xml'); + + $this->assertEqualXMLStructure( + $expected->firstChild, $actual->firstChild, TRUE + ); + } + + public function testXMLStructureAttributesAreSameButValuesAreNot() + { + $expected = new DOMDocument; + $expected->load($this->filesDirectory . 'structureExpected.xml'); + + $actual = new DOMDocument; + $actual->load($this->filesDirectory . 'structureAttributesAreSameButValuesAreNot.xml'); + + $this->assertEqualXMLStructure( + $expected->firstChild, $actual->firstChild, TRUE + ); + } + + public function testXMLStructureIgnoreTextNodes() + { + $expected = new DOMDocument; + $expected->load($this->filesDirectory . 'structureExpected.xml'); + + $actual = new DOMDocument; + $actual->load($this->filesDirectory . 'structureIgnoreTextNodes.xml'); + + $this->assertEqualXMLStructure( + $expected->firstChild, $actual->firstChild, TRUE + ); + } + + public function testAssertStringEqualsNumeric() + { + $this->assertEquals('0', 0); + + try { + $this->assertEquals('0', 1); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertStringEqualsNumeric2() + { + $this->assertNotEquals('A', 0); + } + + public function testAssertFileExists() + { + $this->assertFileExists(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'AllTests.php'); + + try { + $this->assertFileExists(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'NotExisting'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertFileNotExists() + { + $this->assertFileNotExists(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'NotExisting'); + + try { + $this->assertFileNotExists(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'AllTests.php'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertObjectHasAttribute() + { + $o = new WasRun('runTest'); + + $this->assertObjectHasAttribute('wasRun', $o); + + try { + $this->assertObjectHasAttribute('foo', $o); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertObjectNotHasAttribute() + { + $o = new WasRun('runTest'); + + $this->assertObjectNotHasAttribute('foo', $o); + + try { + $this->assertObjectNotHasAttribute('wasRun', $o); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNull() + { + $this->assertNull(NULL); + + try { + $this->assertNull(new stdClass); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotNull() + { + $this->assertNotNull(new stdClass); + + try { + $this->assertNotNull(NULL); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertTrue() + { + $this->assertTrue(TRUE); + + try { + $this->assertTrue(FALSE); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertFalse() + { + $this->assertFalse(FALSE); + + try { + $this->assertFalse(TRUE); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertRegExp() + { + $this->assertRegExp('/foo/', 'foobar'); + + try { + $this->assertRegExp('/foo/', 'bar'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotRegExp() + { + $this->assertNotRegExp('/foo/', 'bar'); + + try { + $this->assertNotRegExp('/foo/', 'foobar'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertSame() + { + $o = new stdClass; + + $this->assertSame($o, $o); + + try { + $this->assertSame( + new stdClass, + new stdClass + ); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertSame2() + { + $this->assertSame(TRUE, TRUE); + $this->assertSame(FALSE, FALSE); + + try { + $this->assertSame(TRUE, FALSE); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotSame() + { + $this->assertNotSame( + new stdClass, + NULL + ); + + $this->assertNotSame( + NULL, + new stdClass + ); + + $this->assertNotSame( + new stdClass, + new stdClass + ); + + $o = new stdClass; + + try { + $this->assertNotSame($o, $o); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotSame2() + { + $this->assertNotSame(TRUE, FALSE); + $this->assertNotSame(FALSE, TRUE); + + try { + $this->assertNotSame(TRUE, TRUE); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotSameFailsNull() + { + try { + $this->assertNotSame(NULL, NULL); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertTypeArray() + { + $this->assertType('array', array()); + + try { + $this->assertType('array', 'string'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotTypeArray() + { + $this->assertNotType('array', 'string'); + + try { + $this->assertNotType('array', array()); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertTypeBool() + { + $this->assertType('bool', TRUE); + + try { + $this->assertType('bool', 'string'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotTypeBool() + { + $this->assertNotType('bool', 'string'); + + try { + $this->assertNotType('bool', TRUE); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertTypeClass() + { + $this->assertType('stdClass', new stdClass); + + try { + $this->assertType('stdClass', new Exception); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotTypeClass() + { + $this->assertNotType('stdClass', new Exception); + + try { + $this->assertNotType('stdClass', new stdClass); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertTypeFloat() + { + $this->assertType('float', 22.04); + + try { + $this->assertType('integer', 'string'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotTypeFloat() + { + $this->assertNotType('float', 'string'); + + try { + $this->assertNotType('float', 22.04); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertTypeInteger() + { + $this->assertType('integer', 2204); + + try { + $this->assertType('integer', 'string'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotTypeInteger() + { + $this->assertNotType('integer', 'string'); + + try { + $this->assertNotType('integer', 2204); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertTypeNull() + { + $this->assertType('null', NULL); + + try { + $this->assertType('null', 'string'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotTypeNull() + { + $this->assertNotType('null', 'string'); + + try { + $this->assertNotType('null', NULL); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertTypeObject() + { + $this->assertType('object', new stdClass); + + try { + $this->assertType('object', 'string'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotTypeObject() + { + $this->assertNotType('object', 'string'); + + try { + $this->assertNotType('object', new stdClass); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertTypeString() + { + $this->assertType('string', 'string'); + + try { + $this->assertType('string', 2204); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertNotTypeString() + { + $this->assertNotType('string', 2204); + + try { + $this->assertNotType('string', 'string'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testGreaterThan() + { + $this->assertGreaterThan(1, 2); + + try { + $this->assertGreaterThan(2, 1); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAttributeGreaterThan() + { + $this->assertAttributeGreaterThan( + 1, 'bar', new ClassWithNonPublicAttributes + ); + + try { + $this->assertAttributeGreaterThan( + 1, 'foo', new ClassWithNonPublicAttributes + ); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testGreaterThanOrEqual() + { + $this->assertGreaterThanOrEqual(1, 2); + + try { + $this->assertGreaterThanOrEqual(2, 1); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAttributeGreaterThanOrEqual() + { + $this->assertAttributeGreaterThanOrEqual( + 1, 'bar', new ClassWithNonPublicAttributes + ); + + try { + $this->assertAttributeGreaterThanOrEqual( + 2, 'foo', new ClassWithNonPublicAttributes + ); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testLessThan() + { + $this->assertLessThan(2, 1); + + try { + $this->assertLessThan(1, 2); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAttributeLessThan() + { + $this->assertAttributeLessThan( + 2, 'foo', new ClassWithNonPublicAttributes + ); + + try { + $this->assertAttributeLessThan( + 1, 'bar', new ClassWithNonPublicAttributes + ); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testLessThanOrEqual() + { + $this->assertLessThanOrEqual(2, 1); + + try { + $this->assertLessThanOrEqual(1, 2); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAttributeLessThanOrEqual() + { + $this->assertAttributeLessThanOrEqual( + 2, 'foo', new ClassWithNonPublicAttributes + ); + + try { + $this->assertAttributeLessThanOrEqual( + 1, 'bar', new ClassWithNonPublicAttributes + ); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testGetObjectAttribute() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertEquals('foo', $this->readAttribute($obj, 'publicAttribute')); + $this->assertEquals('bar', $this->readAttribute($obj, 'protectedAttribute')); + $this->assertEquals('baz', $this->readAttribute($obj, 'privateAttribute')); + $this->assertEquals('bar', $this->readAttribute($obj, 'protectedParentAttribute')); + $this->assertEquals('bar', $this->readAttribute($obj, 'privateParentAttribute')); + } + + public function testGetStaticAttribute() + { + $this->assertEquals('foo', $this->readAttribute('ClassWithNonPublicAttributes', 'publicStaticAttribute')); + $this->assertEquals('bar', $this->readAttribute('ClassWithNonPublicAttributes', 'protectedStaticAttribute')); + $this->assertEquals('baz', $this->readAttribute('ClassWithNonPublicAttributes', 'privateStaticAttribute')); + $this->assertEquals('foo', $this->readAttribute('ClassWithNonPublicAttributes', 'protectedStaticParentAttribute')); + $this->assertEquals('foo', $this->readAttribute('ClassWithNonPublicAttributes', 'privateStaticParentAttribute')); + } + + public function testAssertPublicAttributeContains() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertAttributeContains('foo', 'publicArray', $obj); + + try { + $this->assertAttributeContains('bar', 'publicArray', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertPublicAttributeContainsOnly() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertAttributeContainsOnly('string', 'publicArray', $obj); + + try { + $this->assertAttributeContainsOnly('integer', 'publicArray', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertPublicAttributeNotContains() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertAttributeNotContains('bar', 'publicArray', $obj); + + try { + $this->assertAttributeNotContains('foo', 'publicArray', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertPublicAttributeNotContainsOnly() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertAttributeNotContainsOnly('integer', 'publicArray', $obj); + + try { + $this->assertAttributeNotContainsOnly('string', 'publicArray', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertProtectedAttributeContains() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertAttributeContains('bar', 'protectedArray', $obj); + + try { + $this->assertAttributeContains('foo', 'protectedArray', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertProtectedAttributeNotContains() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertAttributeNotContains('foo', 'protectedArray', $obj); + + try { + $this->assertAttributeNotContains('bar', 'protectedArray', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertPrivateAttributeContains() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertAttributeContains('baz', 'privateArray', $obj); + + try { + $this->assertAttributeContains('foo', 'privateArray', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertPrivateAttributeNotContains() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertAttributeNotContains('foo', 'privateArray', $obj); + + try { + $this->assertAttributeNotContains('baz', 'privateArray', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertPublicAttributeEquals() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertAttributeEquals('foo', 'publicAttribute', $obj); + + try { + $this->assertAttributeEquals('bar', 'publicAttribute', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertPublicAttributeNotEquals() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertAttributeNotEquals('bar', 'publicAttribute', $obj); + + try { + $this->assertAttributeNotEquals('foo', 'publicAttribute', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertPublicAttributeSame() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertAttributeSame('foo', 'publicAttribute', $obj); + + try { + $this->assertAttributeSame('bar', 'publicAttribute', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertPublicAttributeNotSame() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertAttributeNotSame('bar', 'publicAttribute', $obj); + + try { + $this->assertAttributeNotSame('foo', 'publicAttribute', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertProtectedAttributeEquals() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertAttributeEquals('bar', 'protectedAttribute', $obj); + + try { + $this->assertAttributeEquals('foo', 'protectedAttribute', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertProtectedAttributeNotEquals() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertAttributeNotEquals('foo', 'protectedAttribute', $obj); + + try { + $this->assertAttributeNotEquals('bar', 'protectedAttribute', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertPrivateAttributeEquals() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertAttributeEquals('baz', 'privateAttribute', $obj); + + try { + $this->assertAttributeEquals('foo', 'privateAttribute', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertPrivateAttributeNotEquals() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertAttributeNotEquals('foo', 'privateAttribute', $obj); + + try { + $this->assertAttributeNotEquals('baz', 'privateAttribute', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertPublicStaticAttributeEquals() + { + $this->assertAttributeEquals('foo', 'publicStaticAttribute', 'ClassWithNonPublicAttributes'); + + try { + $this->assertAttributeEquals('bar', 'publicStaticAttribute', 'ClassWithNonPublicAttributes'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertPublicStaticAttributeNotEquals() + { + $this->assertAttributeNotEquals('bar', 'publicStaticAttribute', 'ClassWithNonPublicAttributes'); + + try { + $this->assertAttributeNotEquals('foo', 'publicStaticAttribute', 'ClassWithNonPublicAttributes'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertProtectedStaticAttributeEquals() + { + $this->assertAttributeEquals('bar', 'protectedStaticAttribute', 'ClassWithNonPublicAttributes'); + + try { + $this->assertAttributeEquals('foo', 'protectedStaticAttribute', 'ClassWithNonPublicAttributes'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertProtectedStaticAttributeNotEquals() + { + $this->assertAttributeNotEquals('foo', 'protectedStaticAttribute', 'ClassWithNonPublicAttributes'); + + try { + $this->assertAttributeNotEquals('bar', 'protectedStaticAttribute', 'ClassWithNonPublicAttributes'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertPrivateStaticAttributeEquals() + { + $this->assertAttributeEquals('baz', 'privateStaticAttribute', 'ClassWithNonPublicAttributes'); + + try { + $this->assertAttributeEquals('foo', 'privateStaticAttribute', 'ClassWithNonPublicAttributes'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertPrivateStaticAttributeNotEquals() + { + $this->assertAttributeNotEquals('foo', 'privateStaticAttribute', 'ClassWithNonPublicAttributes'); + + try { + $this->assertAttributeNotEquals('baz', 'privateStaticAttribute', 'ClassWithNonPublicAttributes'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testClassHasPublicAttribute() + { + $this->assertClassHasAttribute('publicAttribute', 'ClassWithNonPublicAttributes'); + + try { + $this->assertClassHasAttribute('attribute', 'ClassWithNonPublicAttributes'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testClassNotHasPublicAttribute() + { + $this->assertClassNotHasAttribute('attribute', 'ClassWithNonPublicAttributes'); + + try { + $this->assertClassNotHasAttribute('publicAttribute', 'ClassWithNonPublicAttributes'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testClassHasPublicStaticAttribute() + { + $this->assertClassHasStaticAttribute('publicStaticAttribute', 'ClassWithNonPublicAttributes'); + + try { + $this->assertClassHasStaticAttribute('attribute', 'ClassWithNonPublicAttributes'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testClassNotHasPublicStaticAttribute() + { + $this->assertClassNotHasStaticAttribute('attribute', 'ClassWithNonPublicAttributes'); + + try { + $this->assertClassNotHasStaticAttribute('publicStaticAttribute', 'ClassWithNonPublicAttributes'); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testObjectHasPublicAttribute() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertObjectHasAttribute('publicAttribute', $obj); + + try { + $this->assertObjectHasAttribute('attribute', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testObjectNotHasPublicAttribute() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertObjectNotHasAttribute('attribute', $obj); + + try { + $this->assertObjectNotHasAttribute('publicAttribute', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testObjectHasOnTheFlyAttribute() + { + $obj = new StdClass; + $obj->foo = 'bar'; + + $this->assertObjectHasAttribute('foo', $obj); + + try { + $this->assertObjectHasAttribute('bar', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testObjectNotHasOnTheFlyAttribute() + { + $obj = new StdClass; + $obj->foo = 'bar'; + + $this->assertObjectNotHasAttribute('bar', $obj); + + try { + $this->assertObjectNotHasAttribute('foo', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testObjectHasProtectedAttribute() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertObjectHasAttribute('protectedAttribute', $obj); + + try { + $this->assertObjectHasAttribute('attribute', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testObjectNotHasProtectedAttribute() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertObjectNotHasAttribute('attribute', $obj); + + try { + $this->assertObjectNotHasAttribute('protectedAttribute', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testObjectHasPrivateAttribute() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertObjectHasAttribute('privateAttribute', $obj); + + try { + $this->assertObjectHasAttribute('attribute', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testObjectNotHasPrivateAttribute() + { + $obj = new ClassWithNonPublicAttributes; + + $this->assertObjectNotHasAttribute('attribute', $obj); + + try { + $this->assertObjectNotHasAttribute('privateAttribute', $obj); + } + + catch (PHPUnit_Framework_AssertionFailedError $e) { + return; + } + + $this->fail(); + } + + public function testAssertThatAttributeEquals() + { + $this->assertThat( + new ClassWithNonPublicAttributes, + $this->attribute( + $this->equalTo('foo'), + 'publicAttribute' + ) + ); + } + + public function testAssertThatAttributeEqualTo() + { + $this->assertThat( + new ClassWithNonPublicAttributes, + $this->attributeEqualTo('publicAttribute', 'foo') + ); + } + + public function testAssertThatAnything() + { + $this->assertThat('anything', $this->anything()); + } + + public function testAssertThatAnythingAndAnything() + { + $this->assertThat( + 'anything', + $this->logicalAnd( + $this->anything(), $this->anything() + ) + ); + } + + public function testAssertThatAnythingOrAnything() + { + $this->assertThat( + 'anything', + $this->logicalOr( + $this->anything(), $this->anything() + ) + ); + } + + public function testAssertThatAnythingXorNotAnything() + { + $this->assertThat( + 'anything', + $this->logicalXor( + $this->anything(), + $this->logicalNot($this->anything()) + ) + ); + } + + public function testAssertThatContains() + { + $this->assertThat(array('foo'), $this->contains('foo')); + } + + public function testAssertThatStringContains() + { + $this->assertThat('barfoobar', $this->stringContains('foo')); + } + + public function testAssertThatContainsOnly() + { + $this->assertThat(array('foo'), $this->containsOnly('string')); + } + + public function testAssertThatArrayHasKey() + { + $this->assertThat(array('foo' => 'bar'), $this->arrayHasKey('foo')); + } + + public function testAssertThatClassHasAttribute() + { + $this->assertThat( + new ClassWithNonPublicAttributes, + $this->classHasAttribute('publicAttribute') + ); + } + + public function testAssertThatClassHasStaticAttribute() + { + $this->assertThat( + new ClassWithNonPublicAttributes, + $this->classHasStaticAttribute('publicStaticAttribute') + ); + } + + public function testAssertThatObjectHasAttribute() + { + $this->assertThat( + new ClassWithNonPublicAttributes, + $this->objectHasAttribute('publicAttribute') + ); + } + + public function testAssertThatEqualTo() + { + $this->assertThat('foo', $this->equalTo('foo')); + } + + public function testAssertThatIdenticalTo() + { + $value = new StdClass; + $constraint = $this->identicalTo($value); + + $this->assertThat($value, $constraint); + } + + public function testAssertThatIsInstanceOf() + { + $this->assertThat(new StdClass, $this->isInstanceOf('StdClass')); + } + + public function testAssertThatIsType() + { + $this->assertThat('string', $this->isType('string')); + } + + public function testAssertThatFileExists() + { + $this->assertThat( + dirname(__FILE__) . DIRECTORY_SEPARATOR . 'AllTests.php', + $this->fileExists() + ); + } + + public function testAssertThatGreaterThan() + { + $this->assertThat(2, $this->greaterThan(1)); + } + + public function testAssertThatGreaterThanOrEqual() + { + $this->assertThat(2, $this->greaterThanOrEqual(1)); + } + + public function testAssertThatLessThan() + { + $this->assertThat(1, $this->lessThan(2)); + } + + public function testAssertThatLessThanOrEqual() + { + $this->assertThat(1, $this->lessThanOrEqual(2)); + } + + public function testAssertThatMatchesRegularExpression() + { + $this->assertThat('foobar', $this->matchesRegularExpression('/foo/')); + } + + public function testAssertTagTypeTrue() + { + $matcher = array('tag' => 'html'); + $this->assertTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertTagTypeFalse() + { + $matcher = array('tag' => 'code'); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagIdTrue() + { + $matcher = array('id' => 'test_text'); + $this->assertTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertTagIdFalse() + { + $matcher = array('id' => 'test_text_doesnt_exist'); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagStringContentTrue() + { + $matcher = array('id' => 'test_text', + 'content' => 'My test tag content'); + $this->assertTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertTagStringContentFalse() + { + $matcher = array('id' => 'test_text', + 'content' => 'My non existent tag content'); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagRegexpContentTrue() + { + $matcher = array('id' => 'test_text', + 'content' => 'regexp:/test tag/'); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagRegexpModifierContentTrue() + { + $matcher = array('id' => 'test_text', + 'content' => 'regexp:/TEST TAG/i'); + $this->assertTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertTagRegexpContentFalse() + { + $matcher = array('id' => 'test_text', + 'content' => 'regexp:/asdf/'); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagAttributesTrueA() + { + $matcher = array('tag' => 'span', + 'attributes' => array('class' => 'test_class')); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagAttributesTrueB() + { + $matcher = array('tag' => 'div', + 'attributes' => array('id' => 'test_child_id')); + $this->assertTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertTagAttributesFalse() + { + $matcher = array('tag' => 'span', + 'attributes' => array('class' => 'test_missing_class')); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagAttributesRegexpTrueA() + { + $matcher = array('tag' => 'span', + 'attributes' => array('class' => 'regexp:/.+_class/')); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagAttributesRegexpTrueB() + { + $matcher = array('tag' => 'div', + 'attributes' => array('id' => 'regexp:/.+_child_.+/')); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagAttributesRegexpModifierTrue() + { + $matcher = array('tag' => 'div', + 'attributes' => array('id' => 'regexp:/.+_CHILD_.+/i')); + $this->assertTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertTagAttributesRegexpModifierFalse() + { + $matcher = array('tag' => 'div', + 'attributes' => array('id' => 'regexp:/.+_CHILD_.+/')); + $this->assertTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertTagAttributesRegexpFalse() + { + $matcher = array('tag' => 'span', + 'attributes' => array('class' => 'regexp:/.+_missing_.+/')); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagAttributesMultiPartClassTrueA() + { + $matcher = array('tag' => 'div', + 'id' => 'test_multi_class', + 'attributes' => array('class' => 'multi class')); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagAttributesMultiPartClassTrueB() + { + $matcher = array('tag' => 'div', + 'id' => 'test_multi_class', + 'attributes' => array('class' => 'multi')); + $this->assertTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertTagAttributesMultiPartClassFalse() + { + $matcher = array('tag' => 'div', + 'id' => 'test_multi_class', + 'attributes' => array('class' => 'mul')); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagParentTrue() + { + $matcher = array('tag' => 'head', + 'parent' => array('tag' => 'html')); + $this->assertTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertTagParentFalse() + { + $matcher = array('tag' => 'head', + 'parent' => array('tag' => 'div')); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagChildTrue() + { + $matcher = array('tag' => 'html', + 'child' => array('tag' => 'head')); + $this->assertTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertTagChildFalse() + { + $matcher = array('tag' => 'html', + 'child' => array('tag' => 'div')); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagAncestorTrue() + { + $matcher = array('tag' => 'div', + 'ancestor' => array('tag' => 'html')); + $this->assertTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertTagAncestorFalse() + { + $matcher = array('tag' => 'html', + 'ancestor' => array('tag' => 'div')); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagDescendantTrue() + { + $matcher = array('tag' => 'html', + 'descendant' => array('tag' => 'div')); + $this->assertTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertTagDescendantFalse() + { + $matcher = array('tag' => 'div', + 'descendant' => array('tag' => 'html')); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagChildrenCountTrue() + { + $matcher = array('tag' => 'ul', + 'children' => array('count' => 3)); + $this->assertTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertTagChildrenCountFalse() + { + $matcher = array('tag' => 'ul', + 'children' => array('count' => 5)); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagChildrenLessThanTrue() + { + $matcher = array('tag' => 'ul', + 'children' => array('less_than' => 10)); + $this->assertTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertTagChildrenLessThanFalse() + { + $matcher = array('tag' => 'ul', + 'children' => array('less_than' => 2)); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagChildrenGreaterThanTrue() + { + $matcher = array('tag' => 'ul', + 'children' => array('greater_than' => 2)); + $this->assertTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertTagChildrenGreaterThanFalse() + { + $matcher = array('tag' => 'ul', + 'children' => array('greater_than' => 10)); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagChildrenOnlyTrue() + { + $matcher = array('tag' => 'ul', + 'children' => array('only' => array('tag' =>'li'))); + $this->assertTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertTagChildrenOnlyFalse() + { + $matcher = array('tag' => 'ul', + 'children' => array('only' => array('tag' =>'div'))); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagTypeIdTrueA() + { + $matcher = array('tag' => 'ul', 'id' => 'my_ul'); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagTypeIdTrueB() + { + $matcher = array('id' => 'my_ul', 'tag' => 'ul'); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagTypeIdTrueC() + { + $matcher = array('tag' => 'input', 'id' => 'input_test_id'); + $this->assertTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertTagTypeIdFalse() + { + $matcher = array('tag' => 'div', 'id' => 'my_ul'); + $this->assertTag($matcher, $this->html); + } + + public function testAssertTagContentAttributes() + { + $matcher = array('tag' => 'div', + 'content' => 'Test Id Text', + 'attributes' => array('id' => 'test_id', + 'class' => 'my_test_class')); + $this->assertTag($matcher, $this->html); + } + + public function testAssertParentContentAttributes() + { + $matcher = array('tag' => 'div', + 'content' => 'Test Id Text', + 'attributes' => array('id' => 'test_id', + 'class' => 'my_test_class'), + 'parent' => array('tag' => 'body')); + $this->assertTag($matcher, $this->html); + } + + public function testAssertChildContentAttributes() + { + $matcher = array('tag' => 'div', + 'content' => 'Test Id Text', + 'attributes' => array('id' => 'test_id', + 'class' => 'my_test_class'), + 'child' => array('tag' => 'div', + 'attributes' => array('id' => 'test_child_id'))); + $this->assertTag($matcher, $this->html); + } + + public function testAssertChildSubChildren() + { + $matcher = array('id' => 'test_id', + 'child' => array('id' => 'test_child_id', + 'child' => array('id' => 'test_subchild_id'))); + $this->assertTag($matcher, $this->html); + } + + public function testAssertAncestorContentAttributes() + { + $matcher = array('id' => 'test_subchild_id', + 'content' => 'My Subchild', + 'attributes' => array('id' => 'test_subchild_id'), + 'ancestor' => array('tag' => 'div', + 'attributes' => array('id' => 'test_id'))); + $this->assertTag($matcher, $this->html); + } + + public function testAssertDescendantContentAttributes() + { + $matcher = array('id' => 'test_id', + 'content' => 'Test Id Text', + 'attributes' => array('id' => 'test_id'), + 'descendant' => array('tag' => 'span', + 'attributes' => array('id' => 'test_subchild_id'))); + $this->assertTag($matcher, $this->html); + } + + public function testAssertChildrenContentAttributes() + { + $matcher = array('id' => 'test_children', + 'content' => 'My Children', + 'attributes' => array('class' => 'children'), + + 'children' => array('less_than' => '25', + 'greater_than' => '2', + 'only' => array('tag' => 'div', + 'attributes' => array('class' => 'my_child')) + )); + $this->assertTag($matcher, $this->html); + } + + public function testAssertNotTagTypeIdFalse() + { + $matcher = array('tag' => 'div', 'id' => 'my_ul'); + $this->assertNotTag($matcher, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertNotTagContentAttributes() + { + $matcher = array('tag' => 'div', + 'content' => 'Test Id Text', + 'attributes' => array('id' => 'test_id', + 'class' => 'my_test_class')); + $this->assertNotTag($matcher, $this->html); + } + + public function testAssertSelectCountPresentTrue() + { + $selector = 'div#test_id'; + $count = TRUE; + $this->assertSelectCount($selector, $count, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertSelectCountPresentFalse() + { + $selector = 'div#non_existent'; + $count = TRUE; + + $this->assertSelectCount($selector, $count, $this->html); + } + + public function testAssertSelectCountNotPresentTrue() + { + $selector = 'div#non_existent'; + $count = FALSE; + + $this->assertSelectCount($selector, $count, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertSelectNotPresentFalse() + { + $selector = 'div#test_id'; + $count = FALSE; + + $this->assertSelectCount($selector, $count, $this->html); + } + + public function testAssertSelectCountChildTrue() + { + $selector = '#my_ul > li'; + $count = 3; + + $this->assertSelectCount($selector, $count, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertSelectCountChildFalse() + { + $selector = '#my_ul > li'; + $count = 4; + + $this->assertSelectCount($selector, $count, $this->html); + } + + public function testAssertSelectCountDescendantTrue() + { + $selector = '#my_ul li'; + $count = 3; + + $this->assertSelectCount($selector, $count, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertSelectCountDescendantFalse() + { + $selector = '#my_ul li'; + $count = 4; + + $this->assertSelectCount($selector, $count, $this->html); + } + + public function testAssertSelectCountGreaterThanTrue() + { + $selector = '#my_ul > li'; + $range = array('>' => 2); + + $this->assertSelectCount($selector, $range, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertSelectCountGreaterThanFalse() + { + $selector = '#my_ul > li'; + $range = array('>' => 3); + + $this->assertSelectCount($selector, $range, $this->html); + } + + public function testAssertSelectCountGreaterThanEqualToTrue() + { + $selector = '#my_ul > li'; + $range = array('>=' => 3); + + $this->assertSelectCount($selector, $range, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertSelectCountGreaterThanEqualToFalse() + { + $selector = '#my_ul > li'; + $range = array('>=' => 4); + + $this->assertSelectCount($selector, $range, $this->html); + } + + public function testAssertSelectCountLessThanTrue() + { + $selector = '#my_ul > li'; + $range = array('<' => 4); + + $this->assertSelectCount($selector, $range, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertSelectCountLessThanFalse() + { + $selector = '#my_ul > li'; + $range = array('<' => 3); + + $this->assertSelectCount($selector, $range, $this->html); + } + + public function testAssertSelectCountLessThanEqualToTrue() + { + $selector = '#my_ul > li'; + $range = array('<=' => 3); + + $this->assertSelectCount($selector, $range, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertSelectCountLessThanEqualToFalse() + { + $selector = '#my_ul > li'; + $range = array('<=' => 2); + + $this->assertSelectCount($selector, $range, $this->html); + } + + public function testAssertSelectCountRangeTrue() + { + $selector = '#my_ul > li'; + $range = array('>' => 2, '<' => 4); + + $this->assertSelectCount($selector, $range, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertSelectCountRangeFalse() + { + $selector = '#my_ul > li'; + $range = array('>' => 1, '<' => 3); + + $this->assertSelectCount($selector, $range, $this->html); + } + + public function testAssertSelectEqualsContentPresentTrue() + { + $selector = 'span.test_class'; + $content = 'Test Class Text'; + + $this->assertSelectEquals($selector, $content, TRUE, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertSelectEqualsContentPresentFalse() + { + $selector = 'span.test_class'; + $content = 'Test Nonexistent'; + + $this->assertSelectEquals($selector, $content, TRUE, $this->html); + } + + public function testAssertSelectEqualsContentNotPresentTrue() + { + $selector = 'span.test_class'; + $content = 'Test Nonexistent'; + + $this->assertSelectEquals($selector, $content, FALSE, $this->html); + } + + /** + * @expectedException PHPUnit_Framework_AssertionFailedError + */ + public function testAssertSelectEqualsContentNotPresentFalse() + { + $selector = 'span.test_class'; + $content = 'Test Class Text'; + + $this->assertSelectEquals($selector, $content, FALSE, $this->html); + } + + public function testAssertSelectRegExpContentPresentTrue() + { + $selector = 'span.test_class'; + $regexp = '/Test.*Text/'; + + $this->assertSelectRegExp($selector, $regexp, TRUE, $this->html); + } + + public function testAssertSelectRegExpContentPresentFalse() + { + $selector = 'span.test_class'; + $regexp = '/Nonexistant/'; + + $this->assertSelectRegExp($selector, $regexp, FALSE, $this->html); + } + + public function testMarkTestIncomplete() + { + try { + $this->markTestIncomplete('incomplete'); + } + + catch (PHPUnit_Framework_IncompleteTestError $e) { + $this->assertEquals('incomplete', $e->getMessage()); + + return; + } + + $this->fail(); + } + + public function testMarkTestSkipped() + { + try { + $this->markTestSkipped('skipped'); + } + + catch (PHPUnit_Framework_SkippedTestError $e) { + $this->assertEquals('skipped', $e->getMessage()); + + return; + } + + $this->fail(); + } +} +?> diff --git a/tests/PHPUnit/Tests/Framework/ComparisonFailureTest.php b/tests/PHPUnit/Tests/Framework/ComparisonFailureTest.php new file mode 100755 index 00000000..7b3a9afc --- /dev/null +++ b/tests/PHPUnit/Tests/Framework/ComparisonFailureTest.php @@ -0,0 +1,144 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework/ComparisonFailure.php'; +require_once 'PHPUnit/Framework/TestCase.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class Framework_ComparisonFailureTest extends PHPUnit_Framework_TestCase +{ + public function testComparisonErrorMessage() + { + $failure = PHPUnit_Framework_ComparisonFailure::diffEqual('a', 'b', 'c'); + + $this->assertEquals( + "c expected string \n difference \n got string ", + $failure->toString() + ); + } + + public function testComparisonErrorStartSame() + { + $failure = PHPUnit_Framework_ComparisonFailure::diffEqual('ba', 'bc'); + + $this->assertEquals( + "expected string \ndifference < x>\ngot string ", + $failure->toString() + ); + } + + public function testComparisonErrorEndSame() + { + $failure = PHPUnit_Framework_ComparisonFailure::diffEqual('ab', 'cb'); + + $this->assertEquals( + "expected string \ndifference \ngot string ", + $failure->toString() + ); + } + + public function testComparisonErrorStartAndEndSame() + { + $failure = PHPUnit_Framework_ComparisonFailure::diffEqual('abc', 'adc'); + + $this->assertEquals( + "expected string \ndifference < x>\ngot string ", + $failure->toString() + ); + } + + public function testComparisonErrorStartSameComplete() + { + $failure = PHPUnit_Framework_ComparisonFailure::diffEqual('ab', 'abc'); + + $this->assertEquals( + "expected string \ndifference < ?>\ngot string ", + $failure->toString() + ); + } + + public function testComparisonErrorEndSameComplete() + { + $failure = PHPUnit_Framework_ComparisonFailure::diffEqual('bc', 'abc'); + + $this->assertEquals( + "expected string \ndifference \ngot string ", + $failure->toString() + ); + } + + public function testComparisonErrorOverlapingMatches() + { + $failure = PHPUnit_Framework_ComparisonFailure::diffEqual('abc', 'abbc'); + + $this->assertEquals( + "expected string \ndifference < x?>\ngot string ", + $failure->toString() + ); + } + + public function testComparisonErrorOverlapingMatches2() + { + $failure = PHPUnit_Framework_ComparisonFailure::diffEqual('abcdde', 'abcde'); + + $this->assertEquals( + "expected string \ndifference < x?>\ngot string ", + $failure->toString() + ); + } +} +?> diff --git a/tests/PHPUnit/Tests/Framework/ConstraintTest.php b/tests/PHPUnit/Tests/Framework/ConstraintTest.php new file mode 100755 index 00000000..eaf82a0c --- /dev/null +++ b/tests/PHPUnit/Tests/Framework/ConstraintTest.php @@ -0,0 +1,1253 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; + +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'ClassWithNonPublicAttributes.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class Framework_ConstraintTest extends PHPUnit_Framework_TestCase +{ + public function testConstraintArrayHasKey() + { + $constraint = new PHPUnit_Framework_Constraint_ArrayHasKey(0); + + $this->assertFalse($constraint->evaluate(array())); + $this->assertEquals('has the key ', $constraint->toString()); + + try { + $constraint->fail(array(), ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that an array has the key .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintArrayHasKey2() + { + $constraint = new PHPUnit_Framework_Constraint_ArrayHasKey(0); + + try { + $constraint->fail(array(), 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that an array has the key .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintArrayNotHasKey() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_ArrayHasKey(0) + ); + + $this->assertTrue($constraint->evaluate(array())); + $this->assertEquals('does not have the key ', $constraint->toString()); + + try { + $constraint->fail(array(0), '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that an array does not have the key .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintArrayNotHasKey2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_ArrayHasKey(0) + ); + + try { + $constraint->fail(array(0), 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that an array does not have the key .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintFileExists() + { + $constraint = new PHPUnit_Framework_Constraint_FileExists; + + $this->assertFalse($constraint->evaluate('foo')); + $this->assertEquals('file exists', $constraint->toString()); + + try { + $constraint->fail('foo', ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + 'Failed asserting that file "foo" exists.', + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintFileExists2() + { + $constraint = new PHPUnit_Framework_Constraint_FileExists; + + try { + $constraint->fail('foo', 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that file \"foo\" exists.", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintFileNotExists() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_FileExists + ); + + $this->assertTrue($constraint->evaluate('foo')); + $this->assertEquals('file does not exist', $constraint->toString()); + + try { + $constraint->fail('foo', '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + 'Failed asserting that file "foo" does not exist.', + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintFileNotExists2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_FileExists + ); + + try { + $constraint->fail('foo', 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that file \"foo\" does not exist.", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintGreaterThan() + { + $constraint = new PHPUnit_Framework_Constraint_GreaterThan(1); + + $this->assertFalse($constraint->evaluate(0)); + $this->assertTrue($constraint->evaluate(2)); + $this->assertEquals('is greater than ', $constraint->toString()); + + try { + $constraint->fail(0, ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that is greater than .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintGreaterThan2() + { + $constraint = new PHPUnit_Framework_Constraint_GreaterThan(1); + + try { + $constraint->fail(0, 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that is greater than .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintNotGreaterThan() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_GreaterThan(1) + ); + + $this->assertTrue($constraint->evaluate(1)); + $this->assertEquals('is not greater than ', $constraint->toString()); + + try { + $constraint->fail(1, '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that is not greater than .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintNotGreaterThan2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_GreaterThan(1) + ); + + try { + $constraint->fail(1, 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that is not greater than .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintIsAnything() + { + $constraint = new PHPUnit_Framework_Constraint_IsAnything; + + $this->assertTrue($constraint->evaluate(NULL)); + $this->assertNull($constraint->fail(NULL, '')); + $this->assertEquals('is anything', $constraint->toString()); + } + + public function testConstraintNotIsAnything() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsAnything + ); + + $this->assertFalse($constraint->evaluate(NULL)); + $this->assertNull($constraint->fail(NULL, '')); + $this->assertEquals('is not anything', $constraint->toString()); + } + + public function testConstraintIsEqual() + { + $constraint = new PHPUnit_Framework_Constraint_IsEqual(1); + + $this->assertFalse($constraint->evaluate(0)); + $this->assertTrue($constraint->evaluate(1)); + $this->assertEquals('is equal to ', $constraint->toString()); + + try { + $constraint->fail(0, ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that is equal to .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintIsEqual2() + { + $constraint = new PHPUnit_Framework_Constraint_IsEqual(1); + + try { + $constraint->fail(0, 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that is equal to .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintIsNotEqual() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsEqual(1) + ); + + $this->assertTrue($constraint->evaluate(0)); + $this->assertFalse($constraint->evaluate(1)); + $this->assertEquals('is not equal to ', $constraint->toString()); + + try { + $constraint->fail(1, '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that is not equal to .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintIsNotEqual2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsEqual(1) + ); + + try { + $constraint->fail(1, 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that is not equal to .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintIsIdentical() + { + $a = new stdClass; + $b = new stdClass; + + $constraint = new PHPUnit_Framework_Constraint_IsIdentical($a); + + $this->assertFalse($constraint->evaluate($b)); + $this->assertTrue($constraint->evaluate($a)); + $this->assertEquals('is identical to an object of class "stdClass"', $constraint->toString()); + + try { + $constraint->fail($b, ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that \nstdClass Object\n(\n)\n is identical to an object of class \"stdClass\".", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintIsIdentical2() + { + $a = new stdClass; + $b = new stdClass; + + $constraint = new PHPUnit_Framework_Constraint_IsIdentical($a); + + try { + $constraint->fail($b, 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that \nstdClass Object\n(\n)\n is identical to an object of class \"stdClass\".", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintIsNotIdentical() + { + $a = new stdClass; + $b = new stdClass; + + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsIdentical($a) + ); + + $this->assertTrue($constraint->evaluate($b)); + $this->assertFalse($constraint->evaluate($a)); + $this->assertEquals("is not identical to an object of class \"stdClass\"", $constraint->toString()); + + try { + $constraint->fail($a, '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that \nstdClass Object\n(\n)\n is not identical to an object of class \"stdClass\".", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintIsNotIdentical2() + { + $a = new stdClass; + + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsIdentical($a) + ); + + try { + $constraint->fail($a, 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that \nstdClass Object\n(\n)\n is not identical to an object of class \"stdClass\".", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintIsInstanceOf() + { + $constraint = new PHPUnit_Framework_Constraint_IsInstanceOf('Exception'); + + $this->assertFalse($constraint->evaluate(new stdClass)); + $this->assertTrue($constraint->evaluate(new Exception)); + $this->assertEquals('is instance of class "Exception"', $constraint->toString()); + + try { + $constraint->fail(new stdClass, ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + 'Failed asserting that is an instance of class "Exception".', + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintIsInstanceOf2() + { + $constraint = new PHPUnit_Framework_Constraint_IsInstanceOf('Exception'); + + try { + $constraint->fail(new stdClass, 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that is an instance of class \"Exception\".", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintIsNotInstanceOf() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsInstanceOf('stdClass') + ); + + $this->assertFalse($constraint->evaluate(new stdClass)); + $this->assertTrue($constraint->evaluate(new Exception)); + $this->assertEquals('is not instance of class "stdClass"', $constraint->toString()); + + try { + $constraint->fail(new stdClass, '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + 'Failed asserting that is not an instance of class "stdClass".', + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintIsNotInstanceOf2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsInstanceOf('stdClass') + ); + + try { + $constraint->fail(new stdClass, 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that is not an instance of class \"stdClass\".", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintIsType() + { + $constraint = new PHPUnit_Framework_Constraint_IsType('string'); + + $this->assertFalse($constraint->evaluate(0)); + $this->assertTrue($constraint->evaluate('')); + $this->assertEquals('is of type "string"', $constraint->toString()); + + try { + $constraint->fail(new stdClass, ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that \nstdClass Object\n(\n)\n is of type \"string\".", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintIsType2() + { + $constraint = new PHPUnit_Framework_Constraint_IsType('string'); + + try { + $constraint->fail(new stdClass, 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that \nstdClass Object\n(\n)\n is of type \"string\".", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintIsNotType() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsType('string') + ); + + $this->assertTrue($constraint->evaluate(0)); + $this->assertFalse($constraint->evaluate('')); + $this->assertEquals('is not of type "string"', $constraint->toString()); + + try { + $constraint->fail('', '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + 'Failed asserting that is not of type "string".', + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintIsNotType2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsType('string') + ); + + try { + $constraint->fail('', 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that is not of type \"string\".", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintLessThan() + { + $constraint = new PHPUnit_Framework_Constraint_LessThan(1); + + $this->assertTrue($constraint->evaluate(0)); + $this->assertFalse($constraint->evaluate(2)); + $this->assertEquals('is less than ', $constraint->toString()); + + try { + $constraint->fail(0, ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that is less than .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintLessThan2() + { + $constraint = new PHPUnit_Framework_Constraint_LessThan(1); + + try { + $constraint->fail(0, 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that is less than .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintNotLessThan() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_LessThan(1) + ); + + $this->assertTrue($constraint->evaluate(1)); + $this->assertEquals('is not less than ', $constraint->toString()); + + try { + $constraint->fail(1, '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that is not less than .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintNotLessThan2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_LessThan(1) + ); + + try { + $constraint->fail(1, 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that is not less than .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintObjectHasAttribute() + { + $constraint = new PHPUnit_Framework_Constraint_ObjectHasAttribute('foo'); + + $this->assertFalse($constraint->evaluate(new stdClass)); + $this->assertEquals('has attribute "foo"', $constraint->toString()); + + try { + $constraint->fail(new stdClass, ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + 'Failed asserting that object of class "stdClass" has attribute "foo".', + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintObjectHasAttribute2() + { + $constraint = new PHPUnit_Framework_Constraint_ObjectHasAttribute('foo'); + + try { + $constraint->fail(new stdClass, 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that object of class \"stdClass\" has attribute \"foo\".", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintObjectNotHasAttribute() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_ObjectHasAttribute('foo') + ); + + $this->assertTrue($constraint->evaluate(new stdClass)); + $this->assertEquals('does not have attribute "foo"', $constraint->toString()); + + $o = new stdClass; + $o->foo = 'bar'; + + try { + $constraint->fail($o, '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + 'Failed asserting that object of class "stdClass" does not have attribute "foo".', + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintObjectNotHasAttribute2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_ObjectHasAttribute('foo') + ); + + $o = new stdClass; + $o->foo = 'bar'; + + try { + $constraint->fail($o, 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that object of class \"stdClass\" does not have attribute \"foo\".", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintPCREMatch() + { + $constraint = new PHPUnit_Framework_Constraint_PCREMatch('/foo/'); + + $this->assertFalse($constraint->evaluate('barbazbar')); + $this->assertTrue($constraint->evaluate('barfoobar')); + $this->assertEquals('matches PCRE pattern "/foo/"', $constraint->toString()); + + try { + $constraint->fail('barbazbar', ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + 'Failed asserting that matches PCRE pattern "/foo/".', + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintPCREMatch2() + { + $constraint = new PHPUnit_Framework_Constraint_PCREMatch('/foo/'); + + try { + $constraint->fail('barbazbar', 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that matches PCRE pattern \"/foo/\".", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintPCRENotMatch() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_PCREMatch('/foo/') + ); + + $this->assertTrue($constraint->evaluate('barbazbar')); + $this->assertFalse($constraint->evaluate('barfoobar')); + $this->assertEquals('does not match PCRE pattern "/foo/"', $constraint->toString()); + + try { + $constraint->fail('barfoobar', '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + 'Failed asserting that does not match PCRE pattern "/foo/".', + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintPCRENotMatch2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_PCREMatch('/foo/') + ); + + try { + $constraint->fail('barfoobar', 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that does not match PCRE pattern \"/foo/\".", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintStringContains() + { + $constraint = new PHPUnit_Framework_Constraint_StringContains('foo'); + + $this->assertFalse($constraint->evaluate('barbazbar')); + $this->assertTrue($constraint->evaluate('barfoobar')); + $this->assertEquals('contains "foo"', $constraint->toString()); + + try { + $constraint->fail('barbazbar', ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + 'Failed asserting that contains "foo".', + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintStringContains2() + { + $constraint = new PHPUnit_Framework_Constraint_StringContains('foo'); + + try { + $constraint->fail('barbazbar', 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that contains \"foo\".", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintStringNotContains() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_StringContains('foo') + ); + + $this->assertTrue($constraint->evaluate('barbazbar')); + $this->assertFalse($constraint->evaluate('barfoobar')); + $this->assertEquals('does not contain "foo"', $constraint->toString()); + + try { + $constraint->fail('barfoobar', '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + 'Failed asserting that does not contain "foo".', + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintStringNotContains2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_StringContains('foo') + ); + + try { + $constraint->fail('barfoobar', 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that does not contain \"foo\".", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintArrayContains() + { + $constraint = new PHPUnit_Framework_Constraint_TraversableContains('foo'); + + $this->assertFalse($constraint->evaluate(array('bar'))); + $this->assertTrue($constraint->evaluate(array('foo'))); + $this->assertEquals('contains ', $constraint->toString()); + + try { + $constraint->fail(array('bar'), ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + 'Failed asserting that an array contains .', + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintArrayContains2() + { + $constraint = new PHPUnit_Framework_Constraint_TraversableContains('foo'); + + try { + $constraint->fail(array('bar'), 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that an array contains .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintArrayNotContains() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_TraversableContains('foo') + ); + + $this->assertTrue($constraint->evaluate(array('bar'))); + $this->assertFalse($constraint->evaluate(array('foo'))); + $this->assertEquals('does not contain ', $constraint->toString()); + + try { + $constraint->fail(array('foo'), '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + 'Failed asserting that an array does not contain .', + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + public function testConstraintArrayNotContains2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_TraversableContains('foo') + ); + + try { + $constraint->fail(array('foo'), 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that an array does not contain .", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + /** + * @covers PHPUnit_Framework_Constraint_TraversableContains + */ + public function testConstraintSplObjectStorageContains() + { + $object = new StdClass; + $constraint = new PHPUnit_Framework_Constraint_TraversableContains($object); + $this->assertEquals("contains \nstdClass Object\n(\n)\n", $constraint->toString()); + + $storage = new SplObjectStorage; + $this->assertFalse($constraint->evaluate($storage)); + + $storage->attach($object); + $this->assertTrue($constraint->evaluate($storage)); + + try { + $constraint->fail(new SplObjectStorage, ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that an iterator contains \nstdClass Object\n(\n)\n.", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } + + /** + * @covers PHPUnit_Framework_Constraint_TraversableContains + */ + public function testConstraintSplObjectStorageContains2() + { + $object = new StdClass; + $constraint = new PHPUnit_Framework_Constraint_TraversableContains($object); + + try { + $constraint->fail(new SplObjectStorage, 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that an iterator contains \nstdClass Object\n(\n)\n.", + $e->getDescription() + ); + + return; + } + + $this->fail(); + } +} +?> diff --git a/tests/PHPUnit/Tests/Framework/MockObjectTest.php b/tests/PHPUnit/Tests/Framework/MockObjectTest.php new file mode 100755 index 00000000..be59b987 --- /dev/null +++ b/tests/PHPUnit/Tests/Framework/MockObjectTest.php @@ -0,0 +1,251 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; + +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'AnInterface.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'FunctionCallback.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'MethodCallback.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'PartialMockTestClass.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @author Patrick Mueller + * @author Frank Kleine + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class Framework_MockObjectTest extends PHPUnit_Framework_TestCase +{ + public function testMockedMethodIsNeverCalled() + { + $mock = $this->getMock('AnInterface'); + $mock->expects($this->never()) + ->method('doSomething'); + } + + public function testMockedMethodIsCalledAtLeastOnce() + { + $mock = $this->getMock('AnInterface'); + $mock->expects($this->atLeastOnce()) + ->method('doSomething'); + + $mock->doSomething(); + } + + public function testMockedMethodIsCalledAtLeastOnce2() + { + $mock = $this->getMock('AnInterface'); + $mock->expects($this->atLeastOnce()) + ->method('doSomething'); + + $mock->doSomething(); + $mock->doSomething(); + } + + public function testMockedMethodIsCalledOnce() + { + $mock = $this->getMock('AnInterface'); + $mock->expects($this->once()) + ->method('doSomething'); + + $mock->doSomething(); + } + + public function testMockedMethodIsCalledOnceWithParameter() + { + $mock = $this->getMock('AnInterface'); + $mock->expects($this->once()) + ->method('doSomething') + ->with($this->equalTo('something')); + + $mock->doSomething('something'); + } + + public function testMockedMethodIsCalledExactly() + { + $mock = $this->getMock('AnInterface'); + $mock->expects($this->exactly(2)) + ->method('doSomething'); + + $mock->doSomething(); + $mock->doSomething(); + } + + public function testStubbedException() + { + $mock = $this->getMock('AnInterface'); + $mock->expects($this->any()) + ->method('doSomething') + ->will($this->throwException(new Exception)); + + try { + $mock->doSomething(); + } + + catch (Exception $e) { + return; + } + + $this->fail(); + } + + public function testStubbedReturnValue() + { + $mock = $this->getMock('AnInterface'); + $mock->expects($this->any()) + ->method('doSomething') + ->will($this->returnValue('something')); + + $this->assertEquals('something', $mock->doSomething()); + } + + public function testFunctionCallback() + { + $mock = $this->getMock('StdClass', array('callback'), array(), '', FALSE); + $mock->expects($this->once()) + ->method('callback') + ->will($this->returnCallback('functionCallback')); + + $this->assertEquals('pass', $mock->callback('foo', 'bar')); + } + + public function testStaticMethodCallback() + { + $mock = $this->getMock('StdClass', array('callback'), array(), '', FALSE); + $mock->expects($this->once()) + ->method('callback') + ->will($this->returnCallback(array('MethodCallback', 'staticCallback'))); + + $this->assertEquals('pass', $mock->callback('foo', 'bar')); + } + + public function testPublicMethodCallback() + { + $mock = $this->getMock('StdClass', array('callback'), array(), '', FALSE); + $mock->expects($this->once()) + ->method('callback') + ->will($this->returnCallback(array(new MethodCallback, 'nonStaticCallback'))); + + $this->assertEquals('pass', $mock->callback('foo', 'bar')); + } + + public function testMockClassOnlyGeneratedOnce() + { + $mock1 = $this->getMock('AnInterface'); + $mock2 = $this->getMock('AnInterface'); + + $this->assertEquals(get_class($mock1), get_class($mock2)); + } + + public function testMockClassDifferentForPartialMocks() + { + $mock1 = $this->getMock('PartialMockTestClass'); + $mock2 = $this->getMock('PartialMockTestClass', array('doSomething')); + $mock3 = $this->getMock('PartialMockTestClass', array('doSomething')); + $mock4 = $this->getMock('PartialMockTestClass', array('doAnotherThing')); + $mock5 = $this->getMock('PartialMockTestClass', array('doAnotherThing')); + + $this->assertNotEquals(get_class($mock1), get_class($mock2)); + $this->assertNotEquals(get_class($mock1), get_class($mock3)); + $this->assertNotEquals(get_class($mock1), get_class($mock4)); + $this->assertNotEquals(get_class($mock1), get_class($mock5)); + $this->assertEquals(get_class($mock2), get_class($mock3)); + $this->assertNotEquals(get_class($mock2), get_class($mock4)); + $this->assertNotEquals(get_class($mock2), get_class($mock5)); + $this->assertEquals(get_class($mock4), get_class($mock5)); + } + + public function testMockClassStoreOverrulable() + { + $mock1 = $this->getMock('PartialMockTestClass'); + $mock2 = $this->getMock('PartialMockTestClass', array(), array(), 'MyMockClassNameForPartialMockTestClass1'); + $mock3 = $this->getMock('PartialMockTestClass'); + $mock4 = $this->getMock('PartialMockTestClass', array('doSomething'), array(), 'AnotherMockClassNameForPartialMockTestClass'); + $mock5 = $this->getMock('PartialMockTestClass', array(), array(), 'MyMockClassNameForPartialMockTestClass2'); + + $this->assertNotEquals(get_class($mock1), get_class($mock2)); + $this->assertEquals(get_class($mock1), get_class($mock3)); + $this->assertNotEquals(get_class($mock1), get_class($mock4)); + $this->assertNotEquals(get_class($mock2), get_class($mock3)); + $this->assertNotEquals(get_class($mock2), get_class($mock4)); + $this->assertNotEquals(get_class($mock2), get_class($mock5)); + $this->assertNotEquals(get_class($mock3), get_class($mock4)); + $this->assertNotEquals(get_class($mock3), get_class($mock5)); + $this->assertNotEquals(get_class($mock4), get_class($mock5)); + } + + public function testMockClassStoreOverruleSameClassNameThrowsException() + { + $mock1 = $this->getMock('PartialMockTestClass', array(), array(), __FUNCTION__); + $this->setExpectedException('RuntimeException'); + $mock2 = $this->getMock('PartialMockTestClass', array(), array(), __FUNCTION__); + } + + public function testOriginalConstructorSettingConsidered() + { + $mock1 = $this->getMock('PartialMockTestClass'); + $mock2 = $this->getMock('PartialMockTestClass', array(), array(), '', FALSE); + + $this->assertNotEquals(get_class($mock1), get_class($mock2)); + } + + public function testOriginalCloneSettingConsidered() + { + $mock1 = $this->getMock('PartialMockTestClass'); + $mock2 = $this->getMock('PartialMockTestClass', array(), array(), '', TRUE, FALSE); + + $this->assertNotEquals(get_class($mock1), get_class($mock2)); + } +} +?> diff --git a/tests/PHPUnit/Tests/Framework/SuiteTest.php b/tests/PHPUnit/Tests/Framework/SuiteTest.php new file mode 100755 index 00000000..45edc598 --- /dev/null +++ b/tests/PHPUnit/Tests/Framework/SuiteTest.php @@ -0,0 +1,198 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; +require_once 'PHPUnit/Framework/TestResult.php'; +require_once 'PHPUnit/Framework/TestSuite.php'; + +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'InheritedTestCase.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'NoTestCaseClass.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'NoTestCases.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'NotPublicTestCase.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'NotVoidTestCase.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'OneTestCase.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'OverrideTestCase.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class Framework_SuiteTest extends PHPUnit_Framework_TestCase { + protected $result; + + protected function setUp() + { + $this->result = new PHPUnit_Framework_TestResult; + } + + public static function suite() + { + $suite = new PHPUnit_Framework_TestSuite; + + $suite->addTest(new Framework_SuiteTest('testAddTestSuite')); + $suite->addTest(new Framework_SuiteTest('testInheritedTests')); + $suite->addTest(new Framework_SuiteTest('testNoTestCases')); + $suite->addTest(new Framework_SuiteTest('testNoTestCaseClass')); + $suite->addTest(new Framework_SuiteTest('testNotExistingTestCase')); + $suite->addTest(new Framework_SuiteTest('testNotPublicTestCase')); + $suite->addTest(new Framework_SuiteTest('testNotVoidTestCase')); + $suite->addTest(new Framework_SuiteTest('testOneTestCase')); + $suite->addTest(new Framework_SuiteTest('testShadowedTests')); + + return $suite; + } + + public function testAddTestSuite() + { + $suite = new PHPUnit_Framework_TestSuite( + 'OneTestCase' + ); + + $suite->run($this->result); + + $this->assertEquals(1, count($this->result)); + } + + public function testInheritedTests() + { + $suite = new PHPUnit_Framework_TestSuite( + 'InheritedTestCase' + ); + + $suite->run($this->result); + + $this->assertTrue($this->result->wasSuccessful()); + $this->assertEquals(2, count($this->result)); + } + + public function testNoTestCases() + { + $suite = new PHPUnit_Framework_TestSuite( + 'NoTestCases' + ); + + $suite->run($this->result); + + $this->assertTrue(!$this->result->wasSuccessful()); + $this->assertEquals(1, $this->result->failureCount()); + $this->assertEquals(1, count($this->result)); + } + + public function testNoTestCaseClass() + { + $suite = new PHPUnit_Framework_TestSuite( + 'NoTestCaseClass' + ); + + $suite->run($this->result); + + $this->assertTrue(!$this->result->wasSuccessful()); + $this->assertEquals(1, count($this->result)); + } + + public function testNotExistingTestCase() + { + $suite = new Framework_SuiteTest('notExistingMethod'); + + $suite->run($this->result); + + $this->assertEquals(0, $this->result->errorCount()); + $this->assertEquals(1, $this->result->failureCount()); + $this->assertEquals(1, count($this->result)); + } + + public function testNotPublicTestCase() + { + $suite = new PHPUnit_Framework_TestSuite( + 'NotPublicTestCase' + ); + + $this->assertEquals(2, count($suite)); + } + + public function testNotVoidTestCase() + { + $suite = new PHPUnit_Framework_TestSuite( + 'NotVoidTestCase' + ); + + $this->assertEquals(1, count($suite)); + } + + public function testOneTestCase() + { + $suite = new PHPUnit_Framework_TestSuite( + 'OneTestCase' + ); + + $suite->run($this->result); + + $this->assertEquals(0, $this->result->errorCount()); + $this->assertEquals(0, $this->result->failureCount()); + $this->assertEquals(1, count($this->result)); + $this->assertTrue($this->result->wasSuccessful()); + } + + public function testShadowedTests() + { + $suite = new PHPUnit_Framework_TestSuite( + 'OverrideTestCase' + ); + + $suite->run($this->result); + + $this->assertEquals(1, count($this->result)); + } +} +?> diff --git a/tests/PHPUnit/Tests/Framework/TestCaseTest.php b/tests/PHPUnit/Tests/Framework/TestCaseTest.php new file mode 100755 index 00000000..5e213862 --- /dev/null +++ b/tests/PHPUnit/Tests/Framework/TestCaseTest.php @@ -0,0 +1,297 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; + +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'Error.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'Failure.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'NoArgTestCaseTest.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'SetupFailure.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'Success.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'TearDownFailure.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'ThrowExceptionTestCase.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'ThrowNoExceptionTestCase.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'TornDown.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'TornDown2.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'TornDown3.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'TornDown4.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'WasRun.php'; + +$GLOBALS['a'] = 'a'; +$_ENV['b'] = 'b'; +$_POST['c'] = 'c'; +$_GET['d'] = 'd'; +$_COOKIE['e'] = 'e'; +$_SERVER['f'] = 'f'; +$_FILES['g'] = 'g'; +$_REQUEST['h'] = 'h'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class Framework_TestCaseTest extends PHPUnit_Framework_TestCase +{ + public function testCaseToString() + { + $this->assertEquals( + 'testCaseToString(Framework_TestCaseTest)', + $this->toString() + ); + } + + public function testError() + { + $this->verifyError(new Error); + } + + public function testExceptionRunningAndTearDown() + { + $result = new PHPUnit_Framework_TestResult(); + $t = new TornDown4; + + $t->run($result); + + $errors = $result->errors(); + + $this->assertEquals( + 'tearDown', + $errors[0]->thrownException()->getMessage() + ); + } + + public function testFailure() + { + $this->verifyFailure(new Failure); + } + + /* PHP does not support anonymous classes + public function testNamelessTestCase() + { + } + */ + + public function testNoArgTestCasePasses() + { + $result = new PHPUnit_Framework_TestResult(); + $t = new PHPUnit_Framework_TestSuite('NoArgTestCaseTest'); + + $t->run($result); + + $this->assertEquals(1, count($result)); + $this->assertEquals(0, $result->failureCount()); + $this->assertEquals(0, $result->errorCount()); + } + + public function testRunAndTearDownFails() + { + $fails = new TornDown2; + + $this->verifyError($fails); + $this->assertTrue($fails->tornDown); + } + + public function testSetupFails() + { + $this->verifyError(new SetupFailure); + } + + public function testSuccess() + { + $this->verifySuccess(new Success); + } + + public function testTearDownAfterError() + { + $fails = new TornDown; + + $this->verifyError($fails); + $this->assertTrue($fails->tornDown); + } + + public function testTearDownFails() + { + $this->verifyError(new TearDownFailure); + } + + public function testTearDownSetupFails() + { + $fails = new TornDown3; + + $this->verifyError($fails); + $this->assertFalse($fails->tornDown); + } + + public function testWasRun() + { + $test = new WasRun; + $test->run(); + + $this->assertTrue($test->wasRun); + } + + public function testException() + { + $test = new ThrowExceptionTestCase('test'); + $test->setExpectedException('Exception'); + + $result = $test->run(); + + $this->assertEquals(1, count($result)); + $this->assertTrue($result->wasSuccessful()); + } + + public function testNoException() + { + $test = new ThrowNoExceptionTestCase('test'); + $test->setExpectedException('Exception'); + + $result = $test->run(); + + $this->assertEquals(1, $result->failureCount()); + $this->assertEquals(1, count($result)); + } + + public function testWrongException() + { + $test = new ThrowExceptionTestCase('test'); + $test->setExpectedException('RuntimeException'); + + $result = $test->run(); + + $this->assertEquals(1, $result->errorCount()); + $this->assertEquals(1, count($result)); + } + + public function testGlobalsBackupPre() + { + global $a; + + $this->assertEquals('a', $a); + $this->assertEquals('a', $GLOBALS['a']); + $this->assertEquals('b', $_ENV['b']); + $this->assertEquals('c', $_POST['c']); + $this->assertEquals('d', $_GET['d']); + $this->assertEquals('e', $_COOKIE['e']); + $this->assertEquals('f', $_SERVER['f']); + $this->assertEquals('g', $_FILES['g']); + $this->assertEquals('h', $_REQUEST['h']); + + $GLOBALS['a'] = 'aa'; + $GLOBALS['foo'] = 'bar'; + $_ENV['b'] = 'bb'; + $_POST['c'] = 'cc'; + $_GET['d'] = 'dd'; + $_COOKIE['e'] = 'ee'; + $_SERVER['f'] = 'ff'; + $_FILES['g'] = 'gg'; + $_REQUEST['h'] = 'hh'; + + $this->assertEquals('aa', $a); + $this->assertEquals('aa', $GLOBALS['a']); + $this->assertEquals('bar', $GLOBALS['foo']); + $this->assertEquals('bb', $_ENV['b']); + $this->assertEquals('cc', $_POST['c']); + $this->assertEquals('dd', $_GET['d']); + $this->assertEquals('ee', $_COOKIE['e']); + $this->assertEquals('ff', $_SERVER['f']); + $this->assertEquals('gg', $_FILES['g']); + $this->assertEquals('hh', $_REQUEST['h']); + } + + public function testGlobalsBackupPost() + { + global $a; + + $this->assertEquals('a', $a); + $this->assertEquals('a', $GLOBALS['a']); + $this->assertEquals('b', $_ENV['b']); + $this->assertEquals('c', $_POST['c']); + $this->assertEquals('d', $_GET['d']); + $this->assertEquals('e', $_COOKIE['e']); + $this->assertEquals('f', $_SERVER['f']); + $this->assertEquals('g', $_FILES['g']); + $this->assertEquals('h', $_REQUEST['h']); + + $this->assertArrayNotHasKey('foo', $GLOBALS); + } + + protected function verifyError(PHPUnit_Framework_TestCase $test) + { + $result = $test->run(); + + $this->assertEquals(1, $result->errorCount()); + $this->assertEquals(0, $result->failureCount()); + $this->assertEquals(1, count($result)); + } + + protected function verifyFailure(PHPUnit_Framework_TestCase $test) + { + $result = $test->run(); + + $this->assertEquals(0, $result->errorCount()); + $this->assertEquals(1, $result->failureCount()); + $this->assertEquals(1, count($result)); + } + + protected function verifySuccess(PHPUnit_Framework_TestCase $test) + { + $result = $test->run(); + + $this->assertEquals(0, $result->errorCount()); + $this->assertEquals(0, $result->failureCount()); + $this->assertEquals(1, count($result)); + } +} +?> diff --git a/tests/PHPUnit/Tests/Framework/TestFailureTest.php b/tests/PHPUnit/Tests/Framework/TestFailureTest.php new file mode 100755 index 00000000..d1a267d7 --- /dev/null +++ b/tests/PHPUnit/Tests/Framework/TestFailureTest.php @@ -0,0 +1,1090 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; + +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'ClassWithNonPublicAttributes.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class Framework_TestFailureTest extends PHPUnit_Framework_TestCase +{ + public function testFailureArrayHasKey() + { + $constraint = new PHPUnit_Framework_Constraint_ArrayHasKey(0); + + try { + $constraint->fail(array(), ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that an array has the key .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureArrayHasKey2() + { + $constraint = new PHPUnit_Framework_Constraint_ArrayHasKey(0); + + try { + $constraint->fail(array(), 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that an array has the key .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureArrayNotHasKey() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_ArrayHasKey(0) + ); + + try { + $constraint->fail(array(0), '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that an array does not have the key .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureArrayNotHasKey2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_ArrayHasKey(0) + ); + + try { + $constraint->fail(array(0), 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that an array does not have the key .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureFileExists() + { + $constraint = new PHPUnit_Framework_Constraint_FileExists; + + try { + $constraint->fail('foo', ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that file \"foo\" exists.\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureFileExists2() + { + $constraint = new PHPUnit_Framework_Constraint_FileExists; + + try { + $constraint->fail('foo', 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that file \"foo\" exists.\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureFileNotExists() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_FileExists + ); + + try { + $constraint->fail('foo', '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that file \"foo\" does not exist.\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureFileNotExists2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_FileExists + ); + + try { + $constraint->fail('foo', 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that file \"foo\" does not exist.\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureGreaterThan() + { + $constraint = new PHPUnit_Framework_Constraint_GreaterThan(1); + + try { + $constraint->fail(0, ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that is greater than .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureGreaterThan2() + { + $constraint = new PHPUnit_Framework_Constraint_GreaterThan(1); + + try { + $constraint->fail(0, 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that is greater than .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureNotGreaterThan() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_GreaterThan(1) + ); + + try { + $constraint->fail(1, '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that is not greater than .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureNotGreaterThan2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_GreaterThan(1) + ); + + try { + $constraint->fail(1, 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that is not greater than .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureIsEqual() + { + $constraint = new PHPUnit_Framework_Constraint_IsEqual(1); + + try { + $constraint->fail(0, ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that matches expected value .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureIsEqual2() + { + $constraint = new PHPUnit_Framework_Constraint_IsEqual(1); + + try { + $constraint->fail(0, 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that matches expected value .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureIsNotEqual() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsEqual(1) + ); + + try { + $constraint->fail(1, '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that is not equal to .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureIsNotEqual2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsEqual(1) + ); + + try { + $constraint->fail(1, 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that is not equal to .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureIsIdentical() + { + $a = new stdClass; + $b = new stdClass; + + $constraint = new PHPUnit_Framework_Constraint_IsIdentical($a); + + try { + $constraint->fail($b, ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that two variables reference the same object.\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureIsIdentical2() + { + $a = new stdClass; + $b = new stdClass; + + $constraint = new PHPUnit_Framework_Constraint_IsIdentical($a); + + try { + $constraint->fail($b, 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that two variables reference the same object.\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureIsNotIdentical() + { + $a = new stdClass; + $b = new stdClass; + + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsIdentical($a) + ); + + try { + $constraint->fail($a, '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that \nstdClass Object\n(\n)\n is not identical to an object of class \"stdClass\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureIsNotIdentical2() + { + $a = new stdClass; + + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsIdentical($a) + ); + + try { + $constraint->fail($a, 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that \nstdClass Object\n(\n)\n is not identical to an object of class \"stdClass\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureIsInstanceOf() + { + $constraint = new PHPUnit_Framework_Constraint_IsInstanceOf('Exception'); + + try { + $constraint->fail(new stdClass, ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that is an instance of class \"Exception\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureIsInstanceOf2() + { + $constraint = new PHPUnit_Framework_Constraint_IsInstanceOf('Exception'); + + try { + $constraint->fail(new stdClass, 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that is an instance of class \"Exception\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureIsNotInstanceOf() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsInstanceOf('stdClass') + ); + + try { + $constraint->fail(new stdClass, '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that is not an instance of class \"stdClass\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureIsNotInstanceOf2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsInstanceOf('stdClass') + ); + + try { + $constraint->fail(new stdClass, 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that is not an instance of class \"stdClass\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureIsType() + { + $constraint = new PHPUnit_Framework_Constraint_IsType('string'); + + try { + $constraint->fail(new stdClass, ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that \nstdClass Object\n(\n)\n is of type \"string\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureIsType2() + { + $constraint = new PHPUnit_Framework_Constraint_IsType('string'); + + try { + $constraint->fail(new stdClass, 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that \nstdClass Object\n(\n)\n is of type \"string\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureIsNotType() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsType('string') + ); + + try { + $constraint->fail('', '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that is not of type \"string\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureIsNotType2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_IsType('string') + ); + + try { + $constraint->fail('', 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that is not of type \"string\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureLessThan() + { + $constraint = new PHPUnit_Framework_Constraint_LessThan(1); + + try { + $constraint->fail(0, ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that is less than .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureLessThan2() + { + $constraint = new PHPUnit_Framework_Constraint_LessThan(1); + + try { + $constraint->fail(0, 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that is less than .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureNotLessThan() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_LessThan(1) + ); + + try { + $constraint->fail(1, '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that is not less than .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureNotLessThan2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_LessThan(1) + ); + + try { + $constraint->fail(1, 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that is not less than .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureObjectHasAttribute() + { + $constraint = new PHPUnit_Framework_Constraint_ObjectHasAttribute('foo'); + + try { + $constraint->fail(new stdClass, ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that object of class \"stdClass\" has attribute \"foo\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureObjectHasAttribute2() + { + $constraint = new PHPUnit_Framework_Constraint_ObjectHasAttribute('foo'); + + try { + $constraint->fail(new stdClass, 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that object of class \"stdClass\" has attribute \"foo\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureObjectNotHasAttribute() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_ObjectHasAttribute('foo') + ); + + $o = new stdClass; + $o->foo = 'bar'; + + try { + $constraint->fail($o, '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that object of class \"stdClass\" does not have attribute \"foo\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureObjectNotHasAttribute2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_ObjectHasAttribute('foo') + ); + + $o = new stdClass; + $o->foo = 'bar'; + + try { + $constraint->fail($o, 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that object of class \"stdClass\" does not have attribute \"foo\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailurePCREMatch() + { + $constraint = new PHPUnit_Framework_Constraint_PCREMatch('/foo/'); + + try { + $constraint->fail('barbazbar', ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that matches PCRE pattern \"/foo/\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailurePCREMatch2() + { + $constraint = new PHPUnit_Framework_Constraint_PCREMatch('/foo/'); + + try { + $constraint->fail('barbazbar', 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that matches PCRE pattern \"/foo/\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailurePCRENotMatch() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_PCREMatch('/foo/') + ); + + try { + $constraint->fail('barfoobar', '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that does not match PCRE pattern \"/foo/\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailurePCRENotMatch2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_PCREMatch('/foo/') + ); + + try { + $constraint->fail('barfoobar', 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that does not match PCRE pattern \"/foo/\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureStringContains() + { + $constraint = new PHPUnit_Framework_Constraint_StringContains('foo'); + + try { + $constraint->fail('barbazbar', ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that contains \"foo\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureStringContains2() + { + $constraint = new PHPUnit_Framework_Constraint_StringContains('foo'); + + try { + $constraint->fail('barbazbar', 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that contains \"foo\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureStringNotContains() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_StringContains('foo') + ); + + try { + $constraint->fail('barfoobar', '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that does not contain \"foo\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureStringNotContains2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_StringContains('foo') + ); + + try { + $constraint->fail('barfoobar', 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that does not contain \"foo\".\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureTraversableContains() + { + $constraint = new PHPUnit_Framework_Constraint_TraversableContains('foo'); + + try { + $constraint->fail(array('bar'), ''); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that an array contains .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureTraversableContains2() + { + $constraint = new PHPUnit_Framework_Constraint_TraversableContains('foo'); + + try { + $constraint->fail(array('bar'), 'custom message'); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that an array contains .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureTraversableNotContains() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_TraversableContains('foo') + ); + + try { + $constraint->fail(array('foo'), '', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "Failed asserting that an array does not contain .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } + + public function testFailureTraversableNotContains2() + { + $constraint = new PHPUnit_Framework_Constraint_Not( + new PHPUnit_Framework_Constraint_TraversableContains('foo') + ); + + try { + $constraint->fail(array('foo'), 'custom message', TRUE); + } + + catch (PHPUnit_Framework_ExpectationFailedException $e) { + $this->assertEquals( + "custom message\nFailed asserting that an array does not contain .\n", + PHPUnit_Framework_TestFailure::exceptionToString($e) + ); + + return; + } + + $this->fail(); + } +} +?> diff --git a/tests/PHPUnit/Tests/Framework/TestImplementorTest.php b/tests/PHPUnit/Tests/Framework/TestImplementorTest.php new file mode 100755 index 00000000..b7e89672 --- /dev/null +++ b/tests/PHPUnit/Tests/Framework/TestImplementorTest.php @@ -0,0 +1,87 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; +require_once 'PHPUnit/Framework/TestResult.php'; + +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'DoubleTestCase.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'Success.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class Framework_TestImplementorTest extends PHPUnit_Framework_TestCase +{ + protected $test; + + public function __construct() + { + $this->test = new DoubleTestCase( + new Success + ); + } + + public function testSuccessfulRun() + { + $result = new PHPUnit_Framework_TestResult; + + $this->test->run($result); + + $this->assertEquals(count($this->test), count($result)); + $this->assertEquals(0, $result->errorCount()); + $this->assertEquals(0, $result->failureCount()); + } +} +?> diff --git a/tests/PHPUnit/Tests/Framework/TestListenerTest.php b/tests/PHPUnit/Tests/Framework/TestListenerTest.php new file mode 100755 index 00000000..ceb47af7 --- /dev/null +++ b/tests/PHPUnit/Tests/Framework/TestListenerTest.php @@ -0,0 +1,154 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; +require_once 'PHPUnit/Framework/TestListener.php'; +require_once 'PHPUnit/Framework/TestResult.php'; + +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'Error.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'Failure.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'Success.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class Framework_TestListenerTest extends PHPUnit_Framework_TestCase implements PHPUnit_Framework_TestListener +{ + protected $endCount; + protected $errorCount; + protected $failureCount; + protected $notImplementedCount; + protected $skippedCount; + protected $result; + protected $startCount; + + public function addError(PHPUnit_Framework_Test $test, Exception $e, $time) + { + $this->errorCount++; + } + + public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time) + { + $this->failureCount++; + } + + public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time) + { + $this->notImplementedCount++; + } + + public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time) + { + $this->skippedCount++; + } + + public function startTestSuite(PHPUnit_Framework_TestSuite $suite) + { + } + + public function endTestSuite(PHPUnit_Framework_TestSuite $suite) + { + } + + public function startTest(PHPUnit_Framework_Test $test) + { + $this->startCount++; + } + + public function endTest(PHPUnit_Framework_Test $test, $time) + { + $this->endCount++; + } + + protected function setUp() + { + $this->result = new PHPUnit_Framework_TestResult; + $this->result->addListener($this); + + $this->endCount = 0; + $this->failureCount = 0; + $this->notImplementedCount = 0; + $this->skippedCount = 0; + $this->startCount = 0; + } + + public function testError() + { + $test = new Error; + $test->run($this->result); + + $this->assertEquals(1, $this->errorCount); + $this->assertEquals(1, $this->endCount); + } + + public function testFailure() + { + $test = new Failure; + $test->run($this->result); + + $this->assertEquals(1, $this->failureCount); + $this->assertEquals(1, $this->endCount); + } + + public function testStartStop() + { + $test = new Success; + $test->run($this->result); + + $this->assertEquals(1, $this->startCount); + $this->assertEquals(1, $this->endCount); + } +} +?> diff --git a/tests/PHPUnit/Tests/Regression/578.phpt b/tests/PHPUnit/Tests/Regression/578.phpt new file mode 100755 index 00000000..b9fe5e71 --- /dev/null +++ b/tests/PHPUnit/Tests/Regression/578.phpt @@ -0,0 +1,36 @@ +--TEST-- +#578: Double printing of trace line for exceptions from notices and warnings +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +EEE + +Time: %i seconds + +There were 3 errors: + +1) testNoticesDoublePrintStackTrace(Issue578Test) +Invalid error type specified +%s/Issue578Test.php:%i +%s/578.php:%i + +2) testWarningsDoublePrintStackTrace(Issue578Test) +Invalid error type specified +%s/Issue578Test.php:%i +%s/578.php:%i + +3) testUnexpectedExceptionsPrintsCorrectly(Issue578Test) +Exception: Double printed exception +%s/Issue578Test.php:%i +%s/578.php:%i + +FAILURES! +Tests: 3, Assertions: 0, Errors: 3. diff --git a/tests/PHPUnit/Tests/Regression/684.phpt b/tests/PHPUnit/Tests/Regression/684.phpt new file mode 100755 index 00000000..cb5f165d --- /dev/null +++ b/tests/PHPUnit/Tests/Regression/684.phpt @@ -0,0 +1,25 @@ +--TEST-- +#684: Unable to find test class when no test methods exists +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +F + +Time: %i seconds + +There was 1 failure: + +1) Warning(PHPUnit_Framework_Warning) +No tests found in class "Foo_Bar_Issue684Test". +%s/684.php:%i + +FAILURES! +Tests: 1, Assertions: 0, Failures: 1. diff --git a/tests/PHPUnit/Tests/Regression/Issue578Test.php b/tests/PHPUnit/Tests/Regression/Issue578Test.php new file mode 100755 index 00000000..9b3e5adc --- /dev/null +++ b/tests/PHPUnit/Tests/Regression/Issue578Test.php @@ -0,0 +1,22 @@ +iniSet('error_reporting', E_ALL | E_NOTICE); + trigger_error('Stack Trace Test Notice', E_NOTICE); + } + + public function testWarningsDoublePrintStackTrace() + { + $this->iniSet('error_reporting', E_ALL | E_NOTICE); + trigger_error('Stack Trace Test Notice', E_WARNING); + } + + public function testUnexpectedExceptionsPrintsCorrectly() + { + throw new Exception('Double printed exception'); + } +} diff --git a/tests/PHPUnit/Tests/Regression/Issue684Test.php b/tests/PHPUnit/Tests/Regression/Issue684Test.php new file mode 100755 index 00000000..e8e5d87e --- /dev/null +++ b/tests/PHPUnit/Tests/Regression/Issue684Test.php @@ -0,0 +1,4 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__); + +require_once 'PHPUnit/Framework/TestSuite.php'; + +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'BaseTestRunnerTest.php'; + +PHPUnit_Util_Filter::$filterPHPUnit = FALSE; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class Runner_AllTests +{ + public static function suite() + { + $suite = new PHPUnit_Framework_TestSuite('PHPUnit_Runner'); + + $suite->addTestSuite('Runner_BaseTestRunnerTest'); + + return $suite; + } +} +?> diff --git a/tests/PHPUnit/Tests/Runner/BaseTestRunnerTest.php b/tests/PHPUnit/Tests/Runner/BaseTestRunnerTest.php new file mode 100755 index 00000000..af7b4ea5 --- /dev/null +++ b/tests/PHPUnit/Tests/Runner/BaseTestRunnerTest.php @@ -0,0 +1,72 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.0.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; + +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'MockRunner.php'; +require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'NonStatic.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class Runner_BaseTestRunnerTest extends PHPUnit_Framework_TestCase +{ + public function testInvokeNonStaticSuite() + { + $runner = new MockRunner; + $runner->getTest('NonStatic'); + } +} +?> diff --git a/tests/PHPUnit/Tests/TextUI/abstract-test-class.phpt b/tests/PHPUnit/Tests/TextUI/abstract-test-class.phpt new file mode 100755 index 00000000..3344f5ba --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/abstract-test-class.phpt @@ -0,0 +1,26 @@ +--TEST-- +phpunit AbstractTest ../_files/AbstractTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +F + +Time: %i seconds + +There was 1 failure: + +1) Warning(PHPUnit_Framework_Warning) +Cannot instantiate class "AbstractTest". +%s/abstract-test-class.php:%i + +FAILURES! +Tests: 1, Assertions: 0, Failures: 1. + diff --git a/tests/PHPUnit/Tests/TextUI/concrete-test-class.phpt b/tests/PHPUnit/Tests/TextUI/concrete-test-class.phpt new file mode 100755 index 00000000..c6df09b7 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/concrete-test-class.phpt @@ -0,0 +1,19 @@ +--TEST-- +phpunit ConcreteTest ../_files/ConcreteTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +.. + +Time: %i seconds + +OK (2 tests, 0 assertions) + diff --git a/tests/PHPUnit/Tests/TextUI/coverage-clover-class-extended.phpt b/tests/PHPUnit/Tests/TextUI/coverage-clover-class-extended.phpt new file mode 100755 index 00000000..46aabb8b --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/coverage-clover-class-extended.phpt @@ -0,0 +1,55 @@ +--TEST-- +phpunit --coverage-clover php://stdout CoverageClassExtendedTest ../_files/CoverageClassExtendedTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +. + +Time: %i seconds + +OK (1 test, 0 assertions) + +Writing code coverage data to XML file, this may take a moment. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/PHPUnit/Tests/TextUI/coverage-clover-class.phpt b/tests/PHPUnit/Tests/TextUI/coverage-clover-class.phpt new file mode 100755 index 00000000..33b04f90 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/coverage-clover-class.phpt @@ -0,0 +1,55 @@ +--TEST-- +phpunit --coverage-clover php://stdout CoverageClassTest ../_files/CoverageClassTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +. + +Time: %i seconds + +OK (1 test, 0 assertions) + +Writing code coverage data to XML file, this may take a moment. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/PHPUnit/Tests/TextUI/coverage-clover-method.phpt b/tests/PHPUnit/Tests/TextUI/coverage-clover-method.phpt new file mode 100755 index 00000000..db399e13 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/coverage-clover-method.phpt @@ -0,0 +1,55 @@ +--TEST-- +phpunit --coverage-clover php://stdout CoverageMethodTest ../_files/CoverageMethodTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +. + +Time: %i seconds + +OK (1 test, 0 assertions) + +Writing code coverage data to XML file, this may take a moment. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/PHPUnit/Tests/TextUI/coverage-clover-not-private.phpt b/tests/PHPUnit/Tests/TextUI/coverage-clover-not-private.phpt new file mode 100755 index 00000000..5a74e713 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/coverage-clover-not-private.phpt @@ -0,0 +1,55 @@ +--TEST-- +phpunit --coverage-clover php://stdout CoverageNotPrivateTest ../_files/CoverageNotPrivateTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +. + +Time: %i seconds + +OK (1 test, 0 assertions) + +Writing code coverage data to XML file, this may take a moment. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/PHPUnit/Tests/TextUI/coverage-clover-not-protected.phpt b/tests/PHPUnit/Tests/TextUI/coverage-clover-not-protected.phpt new file mode 100755 index 00000000..59f4af26 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/coverage-clover-not-protected.phpt @@ -0,0 +1,55 @@ +--TEST-- +phpunit --coverage-clover php://stdout CoverageNotProtectedTest ../_files/CoverageNotProtectedTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +. + +Time: %i seconds + +OK (1 test, 0 assertions) + +Writing code coverage data to XML file, this may take a moment. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/PHPUnit/Tests/TextUI/coverage-clover-not-public.phpt b/tests/PHPUnit/Tests/TextUI/coverage-clover-not-public.phpt new file mode 100755 index 00000000..cc260e9c --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/coverage-clover-not-public.phpt @@ -0,0 +1,55 @@ +--TEST-- +phpunit --coverage-clover php://stdout CoverageNotPublicTest ../_files/CoverageNotPublicTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +. + +Time: %i seconds + +OK (1 test, 0 assertions) + +Writing code coverage data to XML file, this may take a moment. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/PHPUnit/Tests/TextUI/coverage-clover-private.phpt b/tests/PHPUnit/Tests/TextUI/coverage-clover-private.phpt new file mode 100755 index 00000000..2d49b3e0 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/coverage-clover-private.phpt @@ -0,0 +1,55 @@ +--TEST-- +phpunit --coverage-clover php://stdout CoveragePrivateTest ../_files/CoveragePrivateTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +. + +Time: %i seconds + +OK (1 test, 0 assertions) + +Writing code coverage data to XML file, this may take a moment. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/PHPUnit/Tests/TextUI/coverage-clover-protected.phpt b/tests/PHPUnit/Tests/TextUI/coverage-clover-protected.phpt new file mode 100755 index 00000000..816f44a4 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/coverage-clover-protected.phpt @@ -0,0 +1,55 @@ +--TEST-- +phpunit --coverage-clover php://stdout CoverageProtectedTest ../_files/CoverageProtectedTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +. + +Time: %i seconds + +OK (1 test, 0 assertions) + +Writing code coverage data to XML file, this may take a moment. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/PHPUnit/Tests/TextUI/coverage-clover-public.phpt b/tests/PHPUnit/Tests/TextUI/coverage-clover-public.phpt new file mode 100755 index 00000000..4920d180 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/coverage-clover-public.phpt @@ -0,0 +1,55 @@ +--TEST-- +phpunit --coverage-clover php://stdout CoveragePublicTest ../_files/CoveragePublicTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +. + +Time: %i seconds + +OK (1 test, 0 assertions) + +Writing code coverage data to XML file, this may take a moment. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/PHPUnit/Tests/TextUI/coverage-clover.phpt b/tests/PHPUnit/Tests/TextUI/coverage-clover.phpt new file mode 100755 index 00000000..12345c61 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/coverage-clover.phpt @@ -0,0 +1,50 @@ +--TEST-- +phpunit --coverage-clover php://stdout BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +... + +Time: %i seconds + +OK (3 tests, 3 assertions) + +Writing code coverage data to XML file, this may take a moment. + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/PHPUnit/Tests/TextUI/coverage-source.phpt b/tests/PHPUnit/Tests/TextUI/coverage-source.phpt new file mode 100755 index 00000000..0544722b --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/coverage-source.phpt @@ -0,0 +1,842 @@ +--TEST-- +phpunit --coverage-source /tmp BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--CLEAN-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +... + +Time: 0 seconds + +OK (3 tests, 3 assertions) + +Writing code coverage data to XML files, this may take a moment. + + + + <?php + + + /** + + + * PHPUnit + + + * + + + * Copyright (c) 2002-2009, Sebastian Bergmann <sb@sebastian-bergmann.de>. + + + * All rights reserved. + + + * + + + * Redistribution and use in source and binary forms, with or without + + + * modification, are permitted provided that the following conditions + + + * are met: + + + * + + + * * Redistributions of source code must retain the above copyright + + + * notice, this list of conditions and the following disclaimer. + + + * + + + * * Redistributions in binary form must reproduce the above copyright + + + * notice, this list of conditions and the following disclaimer in + + + * the documentation and/or other materials provided with the + + + * distribution. + + + * + + + * * Neither the name of Sebastian Bergmann nor the names of his + + + * contributors may be used to endorse or promote products derived + + + * from this software without specific prior written permission. + + + * + + + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + + + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + + + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + + + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + + + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + + + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + + + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + + + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + + + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + + + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + + + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + + + * POSSIBILITY OF SUCH DAMAGE. + + + * + + + * @category Testing + + + * @package PHPUnit + + + * @author Sebastian Bergmann <sb@sebastian-bergmann.de> + + + * @copyright 2002-2009 Sebastian Bergmann <sb@sebastian-bergmann.de> + + + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + + * @version SVN: $%s$ + + + * @link http://www.phpunit.de/ + + + * @since File available since Release 2.3.0 + + + */ + + + + + + class BankAccountException extends RuntimeException {} + + + + + + /** + + + * A bank account. + + + * + + + * @category Testing + + + * @package PHPUnit + + + * @author Sebastian Bergmann <sb@sebastian-bergmann.de> + + + * @copyright 2002-2009 Sebastian Bergmann <sb@sebastian-bergmann.de> + + + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + + * @version Release: %s + + + * @link http://www.phpunit.de/ + + + * @since Class available since Release 2.3.0 + + + */ + + + class BankAccount + + + { + + + /** + + + * The bank account's balance. + + + * + + + * @var float + + + */ + + + protected $balance = 0; + + + + + + /** + + + * Returns the bank account's balance. + + + * + + + * @return float + + + */ + + + public function getBalance() + + + { + + + return $this->balance; + + + + + + } + + + + + + /** + + + * Sets the bank account's balance. + + + * + + + * @param float $balance + + + * @throws BankAccountException + + + */ + + + protected function setBalance($balance) + + + { + + + if ($balance >= 0) { + + + $this->balance = $balance; + + + } else { + + + throw new BankAccountException; + + + } + + + } + + + + + + /** + + + * Deposits an amount of money to the bank account. + + + * + + + * @param float $balance + + + * @throws BankAccountException + + + */ + + + public function depositMoney($balance) + + + { + + + $this->setBalance($this->getBalance() + $balance); + + + + + + + + + return $this->getBalance(); + + + } + + + + + + /** + + + * Withdraws an amount of money from the bank account. + + + * + + + * @param float $balance + + + * @throws BankAccountException + + + */ + + + public function withdrawMoney($balance) + + + { + + + $this->setBalance($this->getBalance() - $balance); + + + + + + + + + return $this->getBalance(); + + + } + + + } + + + ?> + + + + + + <?php + + + /** + + + * PHPUnit + + + * + + + * Copyright (c) 2002-2009, Sebastian Bergmann <sb@sebastian-bergmann.de>. + + + * All rights reserved. + + + * + + + * Redistribution and use in source and binary forms, with or without + + + * modification, are permitted provided that the following conditions + + + * are met: + + + * + + + * * Redistributions of source code must retain the above copyright + + + * notice, this list of conditions and the following disclaimer. + + + * + + + * * Redistributions in binary form must reproduce the above copyright + + + * notice, this list of conditions and the following disclaimer in + + + * the documentation and/or other materials provided with the + + + * distribution. + + + * + + + * * Neither the name of Sebastian Bergmann nor the names of his + + + * contributors may be used to endorse or promote products derived + + + * from this software without specific prior written permission. + + + * + + + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + + + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + + + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + + + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + + + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + + + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + + + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + + + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + + + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + + + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + + + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + + + * POSSIBILITY OF SUCH DAMAGE. + + + * + + + * @category Testing + + + * @package PHPUnit + + + * @author Sebastian Bergmann <sb@sebastian-bergmann.de> + + + * @copyright 2002-2009 Sebastian Bergmann <sb@sebastian-bergmann.de> + + + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + + * @version SVN: $%s$ + + + * @link http://www.phpunit.de/ + + + * @since File available since Release 2.3.0 + + + */ + + + + + + require_once 'PHPUnit/Framework/TestCase.php'; + + + require_once 'BankAccount.php'; + + + + + + /** + + + * Tests for the BankAccount class. + + + * + + + * @category Testing + + + * @package PHPUnit + + + * @author Sebastian Bergmann <sb@sebastian-bergmann.de> + + + * @copyright 2002-2009 Sebastian Bergmann <sb@sebastian-bergmann.de> + + + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + + * @version Release: %s + + + * @link http://www.phpunit.de/ + + + * @since Class available since Release 2.3.0 + + + */ + + + class BankAccountTest extends PHPUnit_Framework_TestCase + + + { + + + protected $ba; + + + + + + protected function setUp() + + + { + + + $this->ba = new BankAccount; + + + } + + + + + + /** + + + * @covers BankAccount::getBalance + + + * @group balanceIsInitiallyZero + + + * @group specification + + + */ + + + public function testBalanceIsInitiallyZero() + + + 77 + + + + + { + + + $this->assertEquals(0, $this->ba->getBalance()); + + + } + + + + + + /** + + + * @covers BankAccount::withdrawMoney + + + * @group balanceCannotBecomeNegative + + + * @group specification + + + */ + + + public function testBalanceCannotBecomeNegative() + + + 116 + + + + + { + + + try { + + + $this->ba->withdrawMoney(1); + + + } + + + + + + catch (BankAccountException $e) { + + + $this->assertEquals(0, $this->ba->getBalance()); + + + + + + return; + + + } + + + + + + $this->fail(); + + + } + + + + + + /** + + + * @covers BankAccount::depositMoney + + + * @group balanceCannotBecomeNegative + + + * @group specification + + + */ + + + public function testBalanceCannotBecomeNegative2() + + + 103 + + + + + { + + + try { + + + $this->ba->depositMoney(-1); + + + } + + + + + + catch (BankAccountException $e) { + + + $this->assertEquals(0, $this->ba->getBalance()); + + + + + + return; + + + } + + + + + + $this->fail(); + + + } + + + + + + /** + + + * @covers BankAccount::getBalance + + + * @covers BankAccount::depositMoney + + + * @covers BankAccount::withdrawMoney + + + * @group balanceCannotBecomeNegative + + + */ + + + /* + + + public function testDepositWithdrawMoney() + + + { + + + $this->assertEquals(0, $this->ba->getBalance()); + + + $this->ba->depositMoney(1); + + + $this->assertEquals(1, $this->ba->getBalance()); + + + $this->ba->withdrawMoney(1); + + + $this->assertEquals(0, $this->ba->getBalance()); + + + } + + + */ + + + } + + + ?> + + diff --git a/tests/PHPUnit/Tests/TextUI/dataset-log-xml.phpt b/tests/PHPUnit/Tests/TextUI/dataset-log-xml.phpt new file mode 100755 index 00000000..e9f8ea8f --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/dataset-log-xml.phpt @@ -0,0 +1,47 @@ +--TEST-- +phpunit --log-xml php://stdout DataSetTest ../_files/DataSetTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +..F. + + + + + + + testAdd(DataSetTest) with data set #2 (1, 1, 3) +Failed asserting that <integer:2> matches expected value <integer:3>. + +%s:%i +%s:%i + + + + + + + + +Time: %i seconds + +There was 1 failure: + +1) testAdd(DataSetTest) with data set #2 (1, 1, 3) +Failed asserting that matches expected value . +%s:%i +%s:%i + +FAILURES! +Tests: 4, Assertions: 4, Failures: 1. + diff --git a/tests/PHPUnit/Tests/TextUI/debug.phpt b/tests/PHPUnit/Tests/TextUI/debug.phpt new file mode 100755 index 00000000..7643f643 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/debug.phpt @@ -0,0 +1,25 @@ +--TEST-- +phpunit --debug BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + + +Starting test 'testBalanceIsInitiallyZero(BankAccountTest)'. +. +Starting test 'testBalanceCannotBecomeNegative(BankAccountTest)'. +. +Starting test 'testBalanceCannotBecomeNegative2(BankAccountTest)'. +. + +Time: %i seconds + +OK (3 tests, 3 assertions) diff --git a/tests/PHPUnit/Tests/TextUI/default.phpt b/tests/PHPUnit/Tests/TextUI/default.phpt new file mode 100755 index 00000000..70959257 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/default.phpt @@ -0,0 +1,18 @@ +--TEST-- +phpunit BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +... + +Time: %i seconds + +OK (3 tests, 3 assertions) diff --git a/tests/PHPUnit/Tests/TextUI/exclude-group.phpt b/tests/PHPUnit/Tests/TextUI/exclude-group.phpt new file mode 100755 index 00000000..9b2cd0e0 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/exclude-group.phpt @@ -0,0 +1,20 @@ +--TEST-- +phpunit --exclude-group balanceIsInitiallyZero BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +.. + +Time: %i seconds + +OK (2 tests, 2 assertions) diff --git a/tests/PHPUnit/Tests/TextUI/filter-class.phpt b/tests/PHPUnit/Tests/TextUI/filter-class.phpt new file mode 100755 index 00000000..addae641 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/filter-class.phpt @@ -0,0 +1,20 @@ +--TEST-- +phpunit --filter BankAccountTest BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +... + +Time: %i seconds + +OK (3 tests, 3 assertions) diff --git a/tests/PHPUnit/Tests/TextUI/filter-method.phpt b/tests/PHPUnit/Tests/TextUI/filter-method.phpt new file mode 100755 index 00000000..fbf94936 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/filter-method.phpt @@ -0,0 +1,20 @@ +--TEST-- +phpunit --filter testBalanceIsInitiallyZero BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +. + +Time: %i seconds + +OK (1 test, 1 assertion) diff --git a/tests/PHPUnit/Tests/TextUI/group.phpt b/tests/PHPUnit/Tests/TextUI/group.phpt new file mode 100755 index 00000000..f482f0be --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/group.phpt @@ -0,0 +1,20 @@ +--TEST-- +phpunit --group balanceIsInitiallyZero BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +PHPUnit @package_version@ by Sebastian Bergmann. + +. + +Time: %i seconds + +OK (1 test, 1 assertion) diff --git a/tests/PHPUnit/Tests/TextUI/help.phpt b/tests/PHPUnit/Tests/TextUI/help.phpt new file mode 100755 index 00000000..dc8d745f --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/help.phpt @@ -0,0 +1,63 @@ +--TEST-- +phpunit +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +Usage: phpunit [switches] UnitTest [UnitTest.php] + phpunit [switches] + + --log-graphviz Log test execution in GraphViz markup. + --log-json Log test execution in JSON format. + --log-tap Log test execution in TAP format to file. + --log-xml Log test execution in XML format to file. + --log-metrics Write metrics report in XML format. + --log-pmd Write violations report in PMD XML format. + + --coverage-html Generate code coverage report in HTML format. + --coverage-clover Write code coverage data in Clover XML format. + --coverage-source Write code coverage / source data in XML format. + + --test-db-dsn DSN for the test database. + --test-db-log-rev Revision information for database logging. + --test-db-prefix ... Prefix that should be stripped from filenames. + --test-db-log-info ... Additional information for database logging. + + --story-html Write Story/BDD results in HTML format to file. + --story-text Write Story/BDD results in Text format to file. + + --testdox-html Write agile documentation in HTML format to file. + --testdox-text Write agile documentation in Text format to file. + + --filter Filter which tests to run. + --group ... Only runs tests from the specified group(s). + --exclude-group ... Exclude tests from the specified group(s). + --list-groups List available test groups. + + --loader TestSuiteLoader implementation to use. + --repeat Runs the test(s) repeatedly. + + --story Report test execution progress in Story/BDD format. + --tap Report test execution progress in TAP format. + --testdox Report test execution progress in TestDox format. + + --no-syntax-check Disable syntax check of test source files. + --stop-on-failure Stop execution upon first error or failure. + --colors Use colors in output. + --verbose Output more verbose information. + --wait Waits for a keystroke after each test. + + --skeleton-class Generate Unit class for UnitTest in UnitTest.php. + --skeleton-test Generate UnitTest class for Unit in Unit.php. + + --help Prints this usage information. + --version Prints the version and exits. + + --bootstrap A "bootstrap" PHP file that is run before the tests. + --configuration Read configuration from XML file. + -d key[=value] Sets a php.ini value. + diff --git a/tests/PHPUnit/Tests/TextUI/help2.phpt b/tests/PHPUnit/Tests/TextUI/help2.phpt new file mode 100755 index 00000000..d43a6cf1 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/help2.phpt @@ -0,0 +1,65 @@ +--TEST-- +phpunit --help +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +Usage: phpunit [switches] UnitTest [UnitTest.php] + phpunit [switches] + + --log-graphviz Log test execution in GraphViz markup. + --log-json Log test execution in JSON format. + --log-tap Log test execution in TAP format to file. + --log-xml Log test execution in XML format to file. + --log-metrics Write metrics report in XML format. + --log-pmd Write violations report in PMD XML format. + + --coverage-html Generate code coverage report in HTML format. + --coverage-clover Write code coverage data in Clover XML format. + --coverage-source Write code coverage / source data in XML format. + + --test-db-dsn DSN for the test database. + --test-db-log-rev Revision information for database logging. + --test-db-prefix ... Prefix that should be stripped from filenames. + --test-db-log-info ... Additional information for database logging. + + --story-html Write Story/BDD results in HTML format to file. + --story-text Write Story/BDD results in Text format to file. + + --testdox-html Write agile documentation in HTML format to file. + --testdox-text Write agile documentation in Text format to file. + + --filter Filter which tests to run. + --group ... Only runs tests from the specified group(s). + --exclude-group ... Exclude tests from the specified group(s). + --list-groups List available test groups. + + --loader TestSuiteLoader implementation to use. + --repeat Runs the test(s) repeatedly. + + --story Report test execution progress in Story/BDD format. + --tap Report test execution progress in TAP format. + --testdox Report test execution progress in TestDox format. + + --no-syntax-check Disable syntax check of test source files. + --stop-on-failure Stop execution upon first error or failure. + --colors Use colors in output. + --verbose Output more verbose information. + --wait Waits for a keystroke after each test. + + --skeleton-class Generate Unit class for UnitTest in UnitTest.php. + --skeleton-test Generate UnitTest class for Unit in Unit.php. + + --help Prints this usage information. + --version Prints the version and exits. + + --bootstrap A "bootstrap" PHP file that is run before the tests. + --configuration Read configuration from XML file. + -d key[=value] Sets a php.ini value. + diff --git a/tests/PHPUnit/Tests/TextUI/list-groups.phpt b/tests/PHPUnit/Tests/TextUI/list-groups.phpt new file mode 100755 index 00000000..f210e6b9 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/list-groups.phpt @@ -0,0 +1,18 @@ +--TEST-- +phpunit --list-groups BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +PHPUnit @package_version@ by Sebastian Bergmann. + +Available test group(s): + - balanceCannotBecomeNegative + - balanceIsInitiallyZero + - specification diff --git a/tests/PHPUnit/Tests/TextUI/log-graphviz.phpt b/tests/PHPUnit/Tests/TextUI/log-graphviz.phpt new file mode 100755 index 00000000..5ac52dd2 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/log-graphviz.phpt @@ -0,0 +1,35 @@ +--TEST-- +phpunit --log-graphviz php://stdout BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +...strict digraph G { + overlap=scale; + splines=true; + sep=.1; + fontsize=8; + BankAccountTest [ color=green ]; + subgraph BankAccountTest { + testBalanceIsInitiallyZero [ color=green ]; + testBalanceCannotBecomeNegative [ color=green ]; + testBalanceCannotBecomeNegative2 [ color=green ]; + } + BankAccountTest -> testBalanceIsInitiallyZero; + BankAccountTest -> testBalanceCannotBecomeNegative; + BankAccountTest -> testBalanceCannotBecomeNegative2; +} + + +Time: %i seconds + +OK (3 tests, 3 assertions) diff --git a/tests/PHPUnit/Tests/TextUI/log-json.phpt b/tests/PHPUnit/Tests/TextUI/log-json.phpt new file mode 100755 index 00000000..10223dcf --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/log-json.phpt @@ -0,0 +1,20 @@ +--TEST-- +phpunit --log-json php://stdout BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +{"event":"suiteStart","suite":"BankAccountTest","tests":3}.{"event":"test","suite":"BankAccountTest","test":"testBalanceIsInitiallyZero(BankAccountTest)","status":"pass","time":%f,"trace":[],"message":""}.{"event":"test","suite":"BankAccountTest","test":"testBalanceCannotBecomeNegative(BankAccountTest)","status":"pass","time":%f,"trace":[],"message":""}.{"event":"test","suite":"BankAccountTest","test":"testBalanceCannotBecomeNegative2(BankAccountTest)","status":"pass","time":%f,"trace":[],"message":""} + +Time: %i seconds + +OK (3 tests, 3 assertions) diff --git a/tests/PHPUnit/Tests/TextUI/log-tap.phpt b/tests/PHPUnit/Tests/TextUI/log-tap.phpt new file mode 100755 index 00000000..84b23dc2 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/log-tap.phpt @@ -0,0 +1,25 @@ +--TEST-- +phpunit --log-tap php://stdout BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +TAP version 13 +.ok 1 - testBalanceIsInitiallyZero(BankAccountTest) +.ok 2 - testBalanceCannotBecomeNegative(BankAccountTest) +.ok 3 - testBalanceCannotBecomeNegative2(BankAccountTest) +1..3 + + +Time: %i seconds + +OK (3 tests, 3 assertions) diff --git a/tests/PHPUnit/Tests/TextUI/log-xml.phpt b/tests/PHPUnit/Tests/TextUI/log-xml.phpt new file mode 100755 index 00000000..0f865edc --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/log-xml.phpt @@ -0,0 +1,28 @@ +--TEST-- +phpunit --log-xml php://stdout BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +... + + + + + + + + + +Time: %i seconds + +OK (3 tests, 3 assertions) diff --git a/tests/PHPUnit/Tests/TextUI/repeat.phpt b/tests/PHPUnit/Tests/TextUI/repeat.phpt new file mode 100755 index 00000000..63763747 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/repeat.phpt @@ -0,0 +1,21 @@ +--TEST-- +phpunit --repeat 21 BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +............................................................ 60 / 63 +... + +Time: %i seconds + +OK (63 tests, 63 assertions) diff --git a/tests/PHPUnit/Tests/TextUI/skeleton.phpt b/tests/PHPUnit/Tests/TextUI/skeleton.phpt new file mode 100755 index 00000000..41e53ca2 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/skeleton.phpt @@ -0,0 +1,18 @@ +--TEST-- +phpunit Calculator ../_files/Calculator.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +.... + +Time: %i seconds + +OK (4 tests, 4 assertions) diff --git a/tests/PHPUnit/Tests/TextUI/story.phpt b/tests/PHPUnit/Tests/TextUI/story.phpt new file mode 100755 index 00000000..39ac63a6 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/story.phpt @@ -0,0 +1,79 @@ +--TEST-- +phpunit --story BowlingGameSpec ../Samples/BowlingGame/BowlingGameSpec.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +BowlingGameSpec + [x] Score for gutter game is 0 + + Given New game + Then Score should be 0 + + [x] Score for all ones is 20 + + Given New game + When Player rolls 1 + and Player rolls 1 + and Player rolls 1 + and Player rolls 1 + and Player rolls 1 + and Player rolls 1 + and Player rolls 1 + and Player rolls 1 + and Player rolls 1 + and Player rolls 1 + and Player rolls 1 + and Player rolls 1 + and Player rolls 1 + and Player rolls 1 + and Player rolls 1 + and Player rolls 1 + and Player rolls 1 + and Player rolls 1 + and Player rolls 1 + and Player rolls 1 + Then Score should be 20 + + [x] Score for one spare and 3 is 16 + + Given New game + When Player rolls 5 + and Player rolls 5 + and Player rolls 3 + Then Score should be 16 + + [x] Score for one strike and 3 and 4 is 24 + + Given New game + When Player rolls 10 + and Player rolls 3 + and Player rolls 4 + Then Score should be 24 + + [x] Score for perfect game is 300 + + Given New game + When Player rolls 10 + and Player rolls 10 + and Player rolls 10 + and Player rolls 10 + and Player rolls 10 + and Player rolls 10 + and Player rolls 10 + and Player rolls 10 + and Player rolls 10 + and Player rolls 10 + and Player rolls 10 + and Player rolls 10 + Then Score should be 300 + +Scenarios: 5, Failed: 0, Skipped: 0, Incomplete: 0. diff --git a/tests/PHPUnit/Tests/TextUI/tap.phpt b/tests/PHPUnit/Tests/TextUI/tap.phpt new file mode 100755 index 00000000..adfc85bd --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/tap.phpt @@ -0,0 +1,17 @@ +--TEST-- +phpunit --tap BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +TAP version 13 +ok 1 - testBalanceIsInitiallyZero(BankAccountTest) +ok 2 - testBalanceCannotBecomeNegative(BankAccountTest) +ok 3 - testBalanceCannotBecomeNegative2(BankAccountTest) +1..3 diff --git a/tests/PHPUnit/Tests/TextUI/testdox-html.phpt b/tests/PHPUnit/Tests/TextUI/testdox-html.phpt new file mode 100755 index 00000000..c43e2e86 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/testdox-html.phpt @@ -0,0 +1,20 @@ +--TEST-- +phpunit --testdox-html php://stdout BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +

BankAccount

    ...
  • Balance is initially zero
  • Balance cannot become negative
+ +Time: %i seconds + +OK (3 tests, 3 assertions) diff --git a/tests/PHPUnit/Tests/TextUI/testdox-text.phpt b/tests/PHPUnit/Tests/TextUI/testdox-text.phpt new file mode 100755 index 00000000..1e7a8797 --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/testdox-text.phpt @@ -0,0 +1,24 @@ +--TEST-- +phpunit --testdox-text php://stdout BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +BankAccount +... [x] Balance is initially zero + [x] Balance cannot become negative + + + +Time: %i seconds + +OK (3 tests, 3 assertions) diff --git a/tests/PHPUnit/Tests/TextUI/testdox.phpt b/tests/PHPUnit/Tests/TextUI/testdox.phpt new file mode 100755 index 00000000..632dbc8b --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/testdox.phpt @@ -0,0 +1,18 @@ +--TEST-- +phpunit --testdox php://stdout BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +BankAccount + [x] Balance is initially zero + [x] Balance cannot become negative + diff --git a/tests/PHPUnit/Tests/TextUI/verbose.phpt b/tests/PHPUnit/Tests/TextUI/verbose.phpt new file mode 100755 index 00000000..ab09b5eb --- /dev/null +++ b/tests/PHPUnit/Tests/TextUI/verbose.phpt @@ -0,0 +1,20 @@ +--TEST-- +phpunit --verbose BankAccountTest ../../Samples/BankAccount/BankAccountTest.php +--FILE-- + +--EXPECTF-- +PHPUnit %s by Sebastian Bergmann. + +BankAccountTest +... + +Time: %i seconds + +OK (3 tests, 3 assertions) diff --git a/tests/PHPUnit/Tests/Util/AllTests.php b/tests/PHPUnit/Tests/Util/AllTests.php new file mode 100755 index 00000000..05a40456 --- /dev/null +++ b/tests/PHPUnit/Tests/Util/AllTests.php @@ -0,0 +1,86 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.3.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +require_once 'PHPUnit/Framework/TestSuite.php'; + +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'TestDox' . DIRECTORY_SEPARATOR . 'AllTests.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'ConfigurationTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'TestTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'TimerTest.php'; +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'XMLTest.php'; + +PHPUnit_Util_Filter::$filterPHPUnit = FALSE; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.0.0 + */ +class Util_AllTests +{ + public static function suite() + { + $suite = new PHPUnit_Framework_TestSuite('PHPUnit_Util'); + + $suite->addTest(Util_TestDox_AllTests::suite()); + $suite->addTestSuite('Util_ConfigurationTest'); + $suite->addTestSuite('Util_TestTest'); + $suite->addTestSuite('Util_TimerTest'); + $suite->addTestSuite('Util_XMLTest'); + + return $suite; + } +} +?> diff --git a/tests/PHPUnit/Tests/Util/ConfigurationTest.php b/tests/PHPUnit/Tests/Util/ConfigurationTest.php new file mode 100755 index 00000000..7e82814d --- /dev/null +++ b/tests/PHPUnit/Tests/Util/ConfigurationTest.php @@ -0,0 +1,324 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; + +require_once 'PHPUnit/Util/Configuration.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class Util_ConfigurationTest extends PHPUnit_Framework_TestCase +{ + protected $configuration; + + protected function setUp() + { + $this->configuration = new PHPUnit_Util_Configuration( + dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'configuration.xml' + ); + } + + public function testGetFilterConfiguration() + { + $this->assertEquals( + array ( + 'blacklist' => + array ( + 'include' => + array ( + 'directory' => + array ( + 0 => + array ( + 'path' => '/path/to/files', + 'suffix' => '.php', + ), + ), + 'file' => + array ( + 0 => '/path/to/file', + ), + ), + 'exclude' => + array ( + 'directory' => + array ( + 0 => + array ( + 'path' => '/path/to/files', + 'suffix' => '.php', + ), + ), + 'file' => + array ( + 0 => '/path/to/file', + ), + ), + ), + 'whitelist' => + array ( + 'addUncoveredFilesFromWhitelist' => TRUE, + 'include' => + array ( + 'directory' => + array ( + 0 => + array ( + 'path' => '/path/to/files', + 'suffix' => '.php', + ), + ), + 'file' => + array ( + 0 => '/path/to/file', + ), + ), + 'exclude' => + array ( + 'directory' => + array ( + 0 => + array ( + 'path' => '/path/to/files', + 'suffix' => '.php', + ), + ), + 'file' => + array ( + 0 => '/path/to/file', + ), + ), + ), + ), + $this->configuration->getFilterConfiguration() + ); + } + + public function testGetGroupConfiguration() + { + $this->assertEquals( + array ( + 'include' => + array ( + 0 => 'name', + ), + 'exclude' => + array ( + 0 => 'name', + ), + ), + $this->configuration->getGroupConfiguration() + ); + } + + public function testGetLoggingConfiguration() + { + $this->assertEquals( + array ( + 'charset' => 'UTF-8', + 'lowUpperBound' => '35', + 'highLowerBound' => '70', + 'yui' => TRUE, + 'highlight' => FALSE, + 'coverage-html' => '/tmp/report', + 'coverage-clover' => '/tmp/clover.xml', + 'coverage-source' => '/tmp/coverage', + 'graphviz' => '/tmp/logfile.dot', + 'json' => '/tmp/logfile.json', + 'metrics-xml' => '/tmp/metrics.xml', + 'plain' => '/tmp/logfile.txt', + 'cpdMinLines' => '5', + 'cpdMinMatches' => '70', + 'pmd-xml' => '/tmp/pmd.xml', + 'tap' => '/tmp/logfile.tap', + 'logIncompleteSkipped' => FALSE, + 'test-xml' => '/tmp/logfile.xml', + 'story-html' => '/tmp/story.html', + 'story-text' => '/tmp/story.txt', + 'testdox-html' => '/tmp/testdox.html', + 'testdox-text' => '/tmp/testdox.txt', + ), + $this->configuration->getLoggingConfiguration() + ); + } + + public function testGetPHPConfiguration() + { + $this->assertEquals( + array ( + 'ini' => + array ( + 'foo' => 'bar', + ), + 'var' => + array ( + 'foo' => 'bar', + ), + ), + $this->configuration->getPHPConfiguration() + ); + } + + public function testGetPHPUnitConfiguration() + { + $this->assertEquals( + array ( + 'bootstrap' => '/path/to/bootstrap.php', + 'colors' => FALSE, + 'convertErrorsToExceptions' => TRUE, + 'convertNoticesToExceptions' => TRUE, + 'convertWarningsToExceptions' => TRUE, + 'stopOnFailure' => FALSE, + ), + $this->configuration->getPHPUnitConfiguration() + ); + } + + public function testGetPMDConfiguration() + { + $this->assertEquals( + array ( + 'PHPUnit_Util_Log_PMD_Rule_Project_CRAP' => + array ( + 'threshold' => + array ( + 0 => '5', + 1 => '30', + ), + 'priority' => 1, + ), + 'PHPUnit_Util_Log_PMD_Rule_Class_DepthOfInheritanceTree' => + array ( + 'threshold' => '6', + 'priority' => 1, + ), + 'PHPUnit_Util_Log_PMD_Rule_Class_EfferentCoupling' => + array ( + 'threshold' => '20', + 'priority' => 1, + ), + 'PHPUnit_Util_Log_PMD_Rule_Class_ExcessiveClassLength' => + array ( + 'threshold' => '1000', + 'priority' => 1, + ), + 'PHPUnit_Util_Log_PMD_Rule_Class_ExcessivePublicCount' => + array ( + 'threshold' => '45', + 'priority' => 1, + ), + 'PHPUnit_Util_Log_PMD_Rule_Class_TooManyFields' => + array ( + 'threshold' => '15', + 'priority' => 1, + ), + 'PHPUnit_Util_Log_PMD_Rule_Function_CodeCoverage' => + array ( + 'threshold' => + array ( + 0 => '35', + 1 => '70', + ), + 'priority' => 1, + ), + 'PHPUnit_Util_Log_PMD_Rule_Function_CRAP' => + array ( + 'threshold' => '30', + 'priority' => 1, + ), + 'PHPUnit_Util_Log_PMD_Rule_Function_CyclomaticComplexity' => + array ( + 'threshold' => '20', + 'priority' => 1, + ), + 'PHPUnit_Util_Log_PMD_Rule_Function_ExcessiveMethodLength' => + array ( + 'threshold' => '100', + 'priority' => 1, + ), + 'PHPUnit_Util_Log_PMD_Rule_Function_ExcessiveParameterList' => + array ( + 'threshold' => '10', + 'priority' => 1, + ), + 'PHPUnit_Util_Log_PMD_Rule_Function_NPathComplexity' => + array ( + 'threshold' => '200', + 'priority' => 1, + ), + ), + $this->configuration->getPMDConfiguration() + ); + } + + public function testGetSeleniumBrowserConfiguration() + { + $this->assertEquals( + array ( + 0 => + array ( + 'name' => 'Firefox on Linux', + 'browser' => '*firefox /usr/lib/firefox/firefox-bin', + 'host' => 'my.linux.box', + 'port' => 4444, + 'timeout' => 30000, + ), + ), + $this->configuration->getSeleniumBrowserConfiguration() + ); + } +} +?> diff --git a/tests/PHPUnit/Tests/Util/TestDox/AllTests.php b/tests/PHPUnit/Tests/Util/TestDox/AllTests.php new file mode 100755 index 00000000..c3007c30 --- /dev/null +++ b/tests/PHPUnit/Tests/Util/TestDox/AllTests.php @@ -0,0 +1,80 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.3.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__); + +require_once 'PHPUnit/Framework/TestSuite.php'; + +require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'NamePrettifierTest.php'; + +PHPUnit_Util_Filter::$filterPHPUnit = FALSE; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.1.0 + */ +class Util_TestDox_AllTests +{ + public static function suite() + { + $suite = new PHPUnit_Framework_TestSuite('PHPUnit_Util_TestDox'); + + $suite->addTestSuite('Util_TestDox_NamePrettifierTest'); + + return $suite; + } +} +?> diff --git a/tests/PHPUnit/Tests/Util/TestDox/NamePrettifierTest.php b/tests/PHPUnit/Tests/Util/TestDox/NamePrettifierTest.php new file mode 100755 index 00000000..b1457128 --- /dev/null +++ b/tests/PHPUnit/Tests/Util/TestDox/NamePrettifierTest.php @@ -0,0 +1,108 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.3.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; + +require_once 'PHPUnit/Util/TestDox/NamePrettifier.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.1.0 + */ +class Util_TestDox_NamePrettifierTest extends PHPUnit_Framework_TestCase +{ + protected $namePrettifier; + + protected function setUp() + { + $this->namePrettifier = new PHPUnit_Util_TestDox_NamePrettifier; + } + + public function testTitleHasSensibleDefaults() + { + $this->assertEquals('Foo', $this->namePrettifier->prettifyTestClass('FooTest')); + $this->assertEquals('Foo', $this->namePrettifier->prettifyTestClass('TestFoo')); + $this->assertEquals('Foo', $this->namePrettifier->prettifyTestClass('TestFooTest')); + } + + public function testCaterForUserDefinedSuffix() + { + $this->namePrettifier->setSuffix('TestCase'); + $this->namePrettifier->setPrefix(NULL); + + $this->assertEquals('Foo', $this->namePrettifier->prettifyTestClass('FooTestCase')); + $this->assertEquals('TestFoo', $this->namePrettifier->prettifyTestClass('TestFoo')); + $this->assertEquals('FooTest', $this->namePrettifier->prettifyTestClass('FooTest')); + } + + public function testCaterForUserDefinedPrefix() + { + $this->namePrettifier->setSuffix(NULL); + $this->namePrettifier->setPrefix('XXX'); + + $this->assertEquals('Foo', $this->namePrettifier->prettifyTestClass('XXXFoo')); + $this->assertEquals('TestXXX', $this->namePrettifier->prettifyTestClass('TestXXX')); + $this->assertEquals('XXX', $this->namePrettifier->prettifyTestClass('XXXXXX')); + } + + public function testTestNameIsConvertedToASentence() + { + $this->assertEquals('This is a test', $this->namePrettifier->prettifyTestMethod('testThisIsATest')); + $this->assertEquals('This is a test', $this->namePrettifier->prettifyTestMethod('testThisIsATest2')); + $this->assertEquals('database_column_spec is set correctly', $this->namePrettifier->prettifyTestMethod('testdatabase_column_specIsSetCorrectly')); + $this->assertEquals('Foo for bar is 0', $this->namePrettifier->prettifyTestMethod('testFooForBarIs0')); + $this->assertEquals('Foo for baz is 1', $this->namePrettifier->prettifyTestMethod('testFooForBazIs1')); + } +} +?> diff --git a/tests/PHPUnit/Tests/Util/TestTest.php b/tests/PHPUnit/Tests/Util/TestTest.php new file mode 100755 index 00000000..7eb59440 --- /dev/null +++ b/tests/PHPUnit/Tests/Util/TestTest.php @@ -0,0 +1,102 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.6 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; + +require_once 'PHPUnit/Util/Timer.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.6 + */ +class Util_TestTest extends PHPUnit_Framework_TestCase +{ + public function testGetExpectedException() + { + $this->assertEquals( + array('class' => 'FooBarBaz', 'code' => 0, 'message' => ''), + PHPUnit_Util_Test::getExpectedException('@expectedException FooBarBaz') + ); + + $this->assertEquals( + array('class' => 'Foo_Bar_Baz', 'code' => 0, 'message' => ''), + PHPUnit_Util_Test::getExpectedException('@expectedException Foo_Bar_Baz') + ); + + $this->assertEquals( + array('class' => 'Foo\Bar\Baz', 'code' => 0, 'message' => ''), + PHPUnit_Util_Test::getExpectedException('@expectedException Foo\Bar\Baz') + ); + } + + public function testGetProvidedDataRegEx() + { + $result = preg_match(PHPUnit_Util_Test::REGEX_DATA_PROVIDER, '@dataProvider method', $matches); + $this->assertEquals(1, $result); + $this->assertEquals('method', $matches[1]); + + $result = preg_match(PHPUnit_Util_Test::REGEX_DATA_PROVIDER, '@dataProvider class::method', $matches); + $this->assertEquals(1, $result); + $this->assertEquals('class::method', $matches[1]); + + $result = preg_match(PHPUnit_Util_Test::REGEX_DATA_PROVIDER, '@dataProvider namespace\class::method', $matches); + $this->assertEquals(1, $result); + $this->assertEquals('namespace\class::method', $matches[1]); + + $result = preg_match(PHPUnit_Util_Test::REGEX_DATA_PROVIDER, '@dataProvider namespace\namespace\class::method', $matches); + $this->assertEquals(1, $result); + $this->assertEquals('namespace\namespace\class::method', $matches[1]); + } +} +?> diff --git a/tests/PHPUnit/Tests/Util/TimerTest.php b/tests/PHPUnit/Tests/Util/TimerTest.php new file mode 100755 index 00000000..510c005d --- /dev/null +++ b/tests/PHPUnit/Tests/Util/TimerTest.php @@ -0,0 +1,78 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.3.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; + +require_once 'PHPUnit/Util/Timer.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.1.0 + */ +class Util_TimerTest extends PHPUnit_Framework_TestCase +{ + public function testSecondsToTimeString() + { + $this->assertEquals('0 seconds', PHPUnit_Util_Timer::secondsToTimeString(0)); + $this->assertEquals('1 second', PHPUnit_Util_Timer::secondsToTimeString(1)); + $this->assertEquals('2 seconds', PHPUnit_Util_Timer::secondsToTimeString(2)); + $this->assertEquals('01:00', PHPUnit_Util_Timer::secondsToTimeString(60)); + $this->assertEquals('01:01', PHPUnit_Util_Timer::secondsToTimeString(61)); + $this->assertEquals('02:00', PHPUnit_Util_Timer::secondsToTimeString(120)); + $this->assertEquals('02:01', PHPUnit_Util_Timer::secondsToTimeString(121)); + $this->assertEquals('01:00:00', PHPUnit_Util_Timer::secondsToTimeString(3600)); + $this->assertEquals('01:00:01', PHPUnit_Util_Timer::secondsToTimeString(3601)); + } +} +?> diff --git a/tests/PHPUnit/Tests/Util/XMLTest.php b/tests/PHPUnit/Tests/Util/XMLTest.php new file mode 100755 index 00000000..577f75c9 --- /dev/null +++ b/tests/PHPUnit/Tests/Util/XMLTest.php @@ -0,0 +1,332 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Mike Naberezny + * @author Derek DeVries + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Framework/TestCase.php'; + +require_once 'PHPUnit/Util/XML.php'; + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Mike Naberezny + * @author Derek DeVries + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class Util_XMLTest extends PHPUnit_Framework_TestCase +{ + public function testAssertValidKeysValidKeys() + { + $options = array('testA' => 1, 'testB' => 2, 'testC' => 3); + $valid = array('testA', 'testB', 'testC'); + $expected = array('testA' => 1, 'testB' => 2, 'testC' => 3); + $validated = PHPUnit_Util_XML::assertValidKeys($options, $valid); + + $this->assertEquals($expected, $validated); + } + + public function testAssertValidKeysValidKeysEmpty() + { + $options = array('testA' => 1, 'testB' => 2); + $valid = array('testA', 'testB', 'testC'); + $expected = array('testA' => 1, 'testB' => 2, 'testC' => NULL); + $validated = PHPUnit_Util_XML::assertValidKeys($options, $valid); + + $this->assertEquals($expected, $validated); + } + + public function testAssertValidKeysDefaultValuesA() + { + $options = array('testA' => 1, 'testB' => 2); + $valid = array('testA' => 23, 'testB' => 24, 'testC' => 25); + $expected = array('testA' => 1, 'testB' => 2, 'testC' => 25); + $validated = PHPUnit_Util_XML::assertValidKeys($options, $valid); + + $this->assertEquals($expected, $validated); + } + + public function testAssertValidKeysDefaultValuesB() + { + $options = array(); + $valid = array('testA' => 23, 'testB' => 24, 'testC' => 25); + $expected = array('testA' => 23, 'testB' => 24, 'testC' => 25); + $validated = PHPUnit_Util_XML::assertValidKeys($options, $valid); + + $this->assertEquals($expected, $validated); + } + + public function testAssertValidKeysInvalidKey() + { + $options = array('testA' => 1, 'testB' => 2, 'testD' => 3); + $valid = array('testA', 'testB', 'testC'); + + try { + $validated = PHPUnit_Util_XML::assertValidKeys($options, $valid); + $this->fail(); + } + + catch (InvalidArgumentException $e) { + $this->assertEquals('Unknown key(s): testD', $e->getMessage()); + } + } + + public function testAssertValidKeysInvalidKeys() + { + $options = array('testA' => 1, 'testD' => 2, 'testE' => 3); + $valid = array('testA', 'testB', 'testC'); + + try { + $validated = PHPUnit_Util_XML::assertValidKeys($options, $valid); + $this->fail(); + } + + catch (InvalidArgumentException $e) { + $this->assertEquals('Unknown key(s): testD, testE', $e->getMessage()); + } + } + + public function testConvertAssertSelect() + { + $selector = 'div#folder.open a[href="http://www.xerox.com"][title="xerox"].selected.big > span'; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector); + $tag = array('tag' => 'div', + 'id' => 'folder', + 'class' => 'open', + 'descendant' => array('tag' => 'a', + 'class' => 'selected big', + 'attributes' => array('href' => 'http://www.xerox.com', + 'title' => 'xerox'), + 'child' => array('tag' => 'span'))); + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertSelectElt() + { + $selector = 'div'; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector); + $tag = array('tag' => 'div'); + + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertClass() + { + $selector = '.foo'; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector); + $tag = array('class' => 'foo'); + + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertId() + { + $selector = '#foo'; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector); + $tag = array('id' => 'foo'); + + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertAttribute() + { + $selector = '[foo="bar"]'; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector); + $tag = array('attributes' => array('foo' => 'bar')); + + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertAttributeSpaces() + { + $selector = '[foo="bar baz"] div[value="foo bar"]'; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector); + $tag = array('attributes' => array('foo' => 'bar baz'), + 'descendant' => array('tag' => 'div', + 'attributes' => array('value' => 'foo bar'))); + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertAttributeMultipleSpaces() + { + $selector = '[foo="bar baz"] div[value="foo bar baz"]'; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector); + $tag = array('attributes' => array('foo' => 'bar baz'), + 'descendant' => array('tag' => 'div', + 'attributes' => array('value' => 'foo bar baz'))); + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertSelectEltClass() + { + $selector = 'div.foo'; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector); + $tag = array('tag' => 'div', 'class' => 'foo'); + + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertSelectEltId() + { + $selector = 'div#foo'; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector); + $tag = array('tag' => 'div', 'id' => 'foo'); + + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertSelectEltAttrEqual() + { + $selector = 'div[foo="bar"]'; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector); + $tag = array('tag' => 'div', 'attributes' => array('foo' => 'bar')); + + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertSelectEltMultiAttrEqual() + { + $selector = 'div[foo="bar"][baz="fob"]'; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector); + $tag = array('tag' => 'div', 'attributes' => array('foo' => 'bar', 'baz' => 'fob')); + + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertSelectEltAttrHasOne() + { + $selector = 'div[foo~="bar"]'; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector); + $tag = array('tag' => 'div', 'attributes' => array('foo' => 'regexp:/.*\bbar\b.*/')); + + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertSelectEltAttrContains() + { + $selector = 'div[foo*="bar"]'; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector); + $tag = array('tag' => 'div', 'attributes' => array('foo' => 'regexp:/.*bar.*/')); + + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertSelectEltChild() + { + $selector = 'div > a'; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector); + $tag = array('tag' => 'div', 'child' => array('tag' => 'a')); + + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertSelectEltDescendant() + { + $selector = 'div a'; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector); + $tag = array('tag' => 'div', 'descendant' => array('tag' => 'a')); + + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertSelectContent() + { + $selector = '#foo'; + $content = 'div contents'; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector, $content); + $tag = array('id' => 'foo', 'content' => 'div contents'); + + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertSelectTrue() + { + $selector = '#foo'; + $content = TRUE; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector, $content); + $tag = array('id' => 'foo'); + + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertSelectFalse() + { + $selector = '#foo'; + $content = FALSE; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector, $content); + $tag = array('id' => 'foo'); + + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertNumber() + { + $selector = '.foo'; + $content = 3; + $converted = PHPUnit_Util_XML::convertSelectToTag($selector, $content); + $tag = array('class' => 'foo'); + + $this->assertEquals($tag, $converted); + } + + public function testConvertAssertRange() + { + $selector = '#foo'; + $content = array('greater_than' => 5, 'less_than' => 10); + $converted = PHPUnit_Util_XML::convertSelectToTag($selector, $content); + $tag = array('id' => 'foo'); + + $this->assertEquals($tag, $converted); + } +} +?> diff --git a/tests/PHPUnit/Tests/_files/AbstractTest.php b/tests/PHPUnit/Tests/_files/AbstractTest.php new file mode 100755 index 00000000..556e7dbc --- /dev/null +++ b/tests/PHPUnit/Tests/_files/AbstractTest.php @@ -0,0 +1,7 @@ + diff --git a/tests/PHPUnit/Tests/_files/Calculator.php b/tests/PHPUnit/Tests/_files/Calculator.php new file mode 100755 index 00000000..c1a6a226 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/Calculator.php @@ -0,0 +1,15 @@ + diff --git a/tests/PHPUnit/Tests/_files/ClassWithNonPublicAttributes.php b/tests/PHPUnit/Tests/_files/ClassWithNonPublicAttributes.php new file mode 100755 index 00000000..9bdb9256 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/ClassWithNonPublicAttributes.php @@ -0,0 +1,30 @@ + diff --git a/tests/PHPUnit/Tests/_files/ConcreteTest.php b/tests/PHPUnit/Tests/_files/ConcreteTest.php new file mode 100755 index 00000000..b38d74d7 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/ConcreteTest.php @@ -0,0 +1,9 @@ + + */ + public function testPublicMethod() + { + $o = new CoveredClass; + $o->publicMethod(); + } +} diff --git a/tests/PHPUnit/Tests/_files/CoverageClassTest.php b/tests/PHPUnit/Tests/_files/CoverageClassTest.php new file mode 100755 index 00000000..06d78d2e --- /dev/null +++ b/tests/PHPUnit/Tests/_files/CoverageClassTest.php @@ -0,0 +1,14 @@ +publicMethod(); + } +} diff --git a/tests/PHPUnit/Tests/_files/CoverageMethodTest.php b/tests/PHPUnit/Tests/_files/CoverageMethodTest.php new file mode 100755 index 00000000..4489919f --- /dev/null +++ b/tests/PHPUnit/Tests/_files/CoverageMethodTest.php @@ -0,0 +1,14 @@ +publicMethod(); + } +} diff --git a/tests/PHPUnit/Tests/_files/CoverageNotPrivateTest.php b/tests/PHPUnit/Tests/_files/CoverageNotPrivateTest.php new file mode 100755 index 00000000..11bb523e --- /dev/null +++ b/tests/PHPUnit/Tests/_files/CoverageNotPrivateTest.php @@ -0,0 +1,14 @@ + + */ + public function testPublicMethod() + { + $o = new CoveredClass; + $o->publicMethod(); + } +} diff --git a/tests/PHPUnit/Tests/_files/CoverageNotProtectedTest.php b/tests/PHPUnit/Tests/_files/CoverageNotProtectedTest.php new file mode 100755 index 00000000..14d9a421 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/CoverageNotProtectedTest.php @@ -0,0 +1,14 @@ + + */ + public function testPublicMethod() + { + $o = new CoveredClass; + $o->publicMethod(); + } +} diff --git a/tests/PHPUnit/Tests/_files/CoverageNotPublicTest.php b/tests/PHPUnit/Tests/_files/CoverageNotPublicTest.php new file mode 100755 index 00000000..3724007f --- /dev/null +++ b/tests/PHPUnit/Tests/_files/CoverageNotPublicTest.php @@ -0,0 +1,14 @@ + + */ + public function testPublicMethod() + { + $o = new CoveredClass; + $o->publicMethod(); + } +} diff --git a/tests/PHPUnit/Tests/_files/CoveragePrivateTest.php b/tests/PHPUnit/Tests/_files/CoveragePrivateTest.php new file mode 100755 index 00000000..641703ea --- /dev/null +++ b/tests/PHPUnit/Tests/_files/CoveragePrivateTest.php @@ -0,0 +1,14 @@ + + */ + public function testPublicMethod() + { + $o = new CoveredClass; + $o->publicMethod(); + } +} diff --git a/tests/PHPUnit/Tests/_files/CoverageProtectedTest.php b/tests/PHPUnit/Tests/_files/CoverageProtectedTest.php new file mode 100755 index 00000000..821d9ea9 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/CoverageProtectedTest.php @@ -0,0 +1,14 @@ + + */ + public function testPublicMethod() + { + $o = new CoveredClass; + $o->publicMethod(); + } +} diff --git a/tests/PHPUnit/Tests/_files/CoveragePublicTest.php b/tests/PHPUnit/Tests/_files/CoveragePublicTest.php new file mode 100755 index 00000000..2a7fff05 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/CoveragePublicTest.php @@ -0,0 +1,14 @@ + + */ + public function testPublicMethod() + { + $o = new CoveredClass; + $o->publicMethod(); + } +} diff --git a/tests/PHPUnit/Tests/_files/CoveredClass.php b/tests/PHPUnit/Tests/_files/CoveredClass.php new file mode 100755 index 00000000..921bf925 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/CoveredClass.php @@ -0,0 +1,37 @@ +privateMethod(); + } + + public function publicMethod() + { + $this->protectedMethod(); + } +} + +class CoveredClass extends CoveredParentClass +{ + private function privateMethod() + { + } + + protected function protectedMethod() + { + parent::protectedMethod(); + $this->privateMethod(); + } + + public function publicMethod() + { + parent::publicMethod(); + $this->protectedMethod(); + } +} + diff --git a/tests/PHPUnit/Tests/_files/DataSetTest.php b/tests/PHPUnit/Tests/_files/DataSetTest.php new file mode 100755 index 00000000..5e18bc52 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/DataSetTest.php @@ -0,0 +1,21 @@ +assertEquals($c, $a + $b); + } + + public static function providerMethod() + { + return array( + array(0, 0, 0), + array(0, 1, 1), + array(1, 1, 3), + array(1, 0, 1) + ); + } +} diff --git a/tests/PHPUnit/Tests/_files/DoubleTestCase.php b/tests/PHPUnit/Tests/_files/DoubleTestCase.php new file mode 100755 index 00000000..25ea69ad --- /dev/null +++ b/tests/PHPUnit/Tests/_files/DoubleTestCase.php @@ -0,0 +1,26 @@ +testCase = $testCase; + } + + public function count() + { + return 2; + } + + public function run(PHPUnit_Framework_TestResult $result = NULL) + { + $result->startTest($this); + + $this->testCase->runBare(); + $this->testCase->runBare(); + + $result->endTest($this, 0); + } +} +?> diff --git a/tests/PHPUnit/Tests/_files/Error.php b/tests/PHPUnit/Tests/_files/Error.php new file mode 100755 index 00000000..82ca195c --- /dev/null +++ b/tests/PHPUnit/Tests/_files/Error.php @@ -0,0 +1,9 @@ + diff --git a/tests/PHPUnit/Tests/_files/Failure.php b/tests/PHPUnit/Tests/_files/Failure.php new file mode 100755 index 00000000..b1da5f17 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/Failure.php @@ -0,0 +1,9 @@ +fail(); + } +} +?> diff --git a/tests/PHPUnit/Tests/_files/FunctionCallback.php b/tests/PHPUnit/Tests/_files/FunctionCallback.php new file mode 100755 index 00000000..cc763866 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/FunctionCallback.php @@ -0,0 +1,10 @@ + diff --git a/tests/PHPUnit/Tests/_files/InheritedTestCase.php b/tests/PHPUnit/Tests/_files/InheritedTestCase.php new file mode 100755 index 00000000..b6f8f507 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/InheritedTestCase.php @@ -0,0 +1,10 @@ + diff --git a/tests/PHPUnit/Tests/_files/MethodCallback.php b/tests/PHPUnit/Tests/_files/MethodCallback.php new file mode 100755 index 00000000..172b1d31 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/MethodCallback.php @@ -0,0 +1,22 @@ + diff --git a/tests/PHPUnit/Tests/_files/MockRunner.php b/tests/PHPUnit/Tests/_files/MockRunner.php new file mode 100755 index 00000000..ee2f2680 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/MockRunner.php @@ -0,0 +1,22 @@ + diff --git a/tests/PHPUnit/Tests/_files/NoArgTestCaseTest.php b/tests/PHPUnit/Tests/_files/NoArgTestCaseTest.php new file mode 100755 index 00000000..53e4c56b --- /dev/null +++ b/tests/PHPUnit/Tests/_files/NoArgTestCaseTest.php @@ -0,0 +1,8 @@ + diff --git a/tests/PHPUnit/Tests/_files/NoTestCaseClass.php b/tests/PHPUnit/Tests/_files/NoTestCaseClass.php new file mode 100755 index 00000000..ca3c5370 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/NoTestCaseClass.php @@ -0,0 +1,5 @@ + diff --git a/tests/PHPUnit/Tests/_files/NoTestCases.php b/tests/PHPUnit/Tests/_files/NoTestCases.php new file mode 100755 index 00000000..6226cdd4 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/NoTestCases.php @@ -0,0 +1,8 @@ + diff --git a/tests/PHPUnit/Tests/_files/NonStatic.php b/tests/PHPUnit/Tests/_files/NonStatic.php new file mode 100755 index 00000000..4260b96b --- /dev/null +++ b/tests/PHPUnit/Tests/_files/NonStatic.php @@ -0,0 +1,9 @@ + diff --git a/tests/PHPUnit/Tests/_files/NotPublicTestCase.php b/tests/PHPUnit/Tests/_files/NotPublicTestCase.php new file mode 100755 index 00000000..e281f272 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/NotPublicTestCase.php @@ -0,0 +1,12 @@ + diff --git a/tests/PHPUnit/Tests/_files/NotVoidTestCase.php b/tests/PHPUnit/Tests/_files/NotVoidTestCase.php new file mode 100755 index 00000000..332b8d2d --- /dev/null +++ b/tests/PHPUnit/Tests/_files/NotVoidTestCase.php @@ -0,0 +1,5 @@ + diff --git a/tests/PHPUnit/Tests/_files/OneTestCase.php b/tests/PHPUnit/Tests/_files/OneTestCase.php new file mode 100755 index 00000000..7f5d7842 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/OneTestCase.php @@ -0,0 +1,12 @@ + diff --git a/tests/PHPUnit/Tests/_files/OutputTestCase.php b/tests/PHPUnit/Tests/_files/OutputTestCase.php new file mode 100755 index 00000000..c09b95c6 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/OutputTestCase.php @@ -0,0 +1,30 @@ +expectOutputString('foo'); + print 'foo'; + } + + public function testExpectOutputStringFooActualBar() + { + $this->expectOutputString('foo'); + print 'bar'; + } + + public function testExpectOutputRegexFooActualFoo() + { + $this->expectOutputRegex('/foo/'); + print 'foo'; + } + + public function testExpectOutputRegexFooActualBar() + { + $this->expectOutputRegex('/foo/'); + print 'bar'; + } +} +?> diff --git a/tests/PHPUnit/Tests/_files/OverrideTestCase.php b/tests/PHPUnit/Tests/_files/OverrideTestCase.php new file mode 100755 index 00000000..dc55a2a5 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/OverrideTestCase.php @@ -0,0 +1,10 @@ + diff --git a/tests/PHPUnit/Tests/_files/PartialMockTestClass.php b/tests/PHPUnit/Tests/_files/PartialMockTestClass.php new file mode 100755 index 00000000..f4387e3f --- /dev/null +++ b/tests/PHPUnit/Tests/_files/PartialMockTestClass.php @@ -0,0 +1,12 @@ + diff --git a/tests/PHPUnit/Tests/_files/SampleClass.php b/tests/PHPUnit/Tests/_files/SampleClass.php new file mode 100755 index 00000000..e80136e1 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/SampleClass.php @@ -0,0 +1,15 @@ +a = $a; + $this->b = $b; + $this->c = $c; + } +} +?> diff --git a/tests/PHPUnit/Tests/_files/SelectorAssertionsFixture.html b/tests/PHPUnit/Tests/_files/SelectorAssertionsFixture.html new file mode 100755 index 00000000..2c6600c5 --- /dev/null +++ b/tests/PHPUnit/Tests/_files/SelectorAssertionsFixture.html @@ -0,0 +1,41 @@ + + + + Login + + + + + + + + + + + + + + + + + +
{title}
+ + + + + + + + + +
Current file:{link}
Legend: + executed + not executed + dead code +
+
+ +
+ +
+ + + + + + + + + + + +{total_item}{items} +
 Coverage
 ClassesFunctions / MethodsLines
+
+ +
+ + + + + + + + +

+
+{lines}
+
+
+ + + + +
Generated by PHPUnit {phpunit_version} and Xdebug {xdebug_version} at {date}.
+ +
+ + + + diff --git a/tests/PHPUnit/Util/Report/Template/file_item.html.dist b/tests/PHPUnit/Util/Report/Template/file_item.html.dist new file mode 100755 index 00000000..602163e8 --- /dev/null +++ b/tests/PHPUnit/Util/Report/Template/file_item.html.dist @@ -0,0 +1,31 @@ + + {name} + + + + + +
{classes_called_percent}{classes_called_percent}
+ + {classes_called_percent} + {classes_number} + + + + + +
{methods_called_percent}{methods_called_percent}
+ + {methods_called_percent} + {methods_number} + + + + + +
{lines_executed_percent}{lines_executed_percent}
+ + {lines_executed_percent} + {num_executed_lines} / {num_executable_lines} + + diff --git a/tests/PHPUnit/Util/Report/Template/file_no_yui.html.dist b/tests/PHPUnit/Util/Report/Template/file_no_yui.html.dist new file mode 100755 index 00000000..4c12e384 --- /dev/null +++ b/tests/PHPUnit/Util/Report/Template/file_no_yui.html.dist @@ -0,0 +1,79 @@ + + + + + + {title} + + + + + + + + + + + + + + + +
{title}
+ + + + + + + + + +
Current file:{link}
Legend: + executed + not executed + dead code +
+
+ +
+ +
+ + + + + + + + + + + +{total_item}{items} +
 Coverage
 ClassesFunctions / MethodsLines
+
+ +
+ + + + + + + + +

+
+{lines}
+
+
+ + + + +
Generated by PHPUnit {phpunit_version} and Xdebug {xdebug_version} at {date}.
+ +
+ + diff --git a/tests/PHPUnit/Util/Report/Template/glass.png b/tests/PHPUnit/Util/Report/Template/glass.png new file mode 100755 index 0000000000000000000000000000000000000000..e1abc00680a3093c49fdb775ae6bdb6764c95af2 GIT binary patch literal 167 zcmeAS@N?(olHy`uVBq!ia0vp^j3CU&3?x-=hn)gaEa{HEjtmSN`?>!lvI6;R0X`wF z|Ns97GD8ntt^-nxB|(0{3=Yq3q=7g|-tI089jvk*Kn`btM`SSr1Gf+eGhVt|_XjA* zUgGKN%6^Gmn4d%Ph(nkFP>9RZ#WAE}PI3Z}&BVayv3^M*kj3EX>gTe~DWM4f=_Dpv literal 0 HcmV?d00001 diff --git a/tests/PHPUnit/Util/Report/Template/method_item.html.dist b/tests/PHPUnit/Util/Report/Template/method_item.html.dist new file mode 100755 index 00000000..7a304705 --- /dev/null +++ b/tests/PHPUnit/Util/Report/Template/method_item.html.dist @@ -0,0 +1,22 @@ + + {name} + + + + + +
{methods_called_percent}{methods_called_percent}
+ + {methods_called_percent} + {methods_number} + + + + + +
{lines_executed_percent}{lines_executed_percent}
+ + {lines_executed_percent} + {num_executed_lines} / {num_executable_lines} + + diff --git a/tests/PHPUnit/Util/Report/Template/scarlet_red.png b/tests/PHPUnit/Util/Report/Template/scarlet_red.png new file mode 100755 index 0000000000000000000000000000000000000000..a879424d5a211cb33221e66174277791f59013eb GIT binary patch literal 150 zcmeAS@N?(olHy`uVBq!ia0vp^j3CUx1SBVv2j2ryoCO|{#S9GG!XV7ZFl&wkP>{XE z)7O>#8Y?HesoB-}R}KM%WJ_ElN}Tg^b5rw57@Uhz6H8K46v{J8G895GQWe}ieFNU7 psOA9`@_4#9hHzX@u2{d4lY!ZX(W(5B_f()bgQu&X%Q~loCIDbBC29Zw literal 0 HcmV?d00001 diff --git a/tests/PHPUnit/Util/Report/Template/snow.png b/tests/PHPUnit/Util/Report/Template/snow.png new file mode 100755 index 0000000000000000000000000000000000000000..2cdae107fceec6e7f02ac7acb4a34a82a540caa5 GIT binary patch literal 141 zcmeAS@N?(olHy`uVBq!ia0vp^j3CU&3?x-=hn)ga>?NMQuI!iC1^MM!lvI6;R0X`wF|Ns97GD8ntt^-nBo-U3d c6}OTTfNUlP#;5A{K>8RwUHx3vIVCg!071?oo&W#< literal 0 HcmV?d00001 diff --git a/tests/PHPUnit/Util/Report/Template/style.css b/tests/PHPUnit/Util/Report/Template/style.css new file mode 100755 index 00000000..b7af596d --- /dev/null +++ b/tests/PHPUnit/Util/Report/Template/style.css @@ -0,0 +1,450 @@ +/* All views: initial background and text color */ +body +{ + background-color: #fff; + color: #2e3436; + font-family: arial, helvetica, sans-serif; + font-size: 12px; + margin: 0 auto; + width: 100%; +} + +/* All views: standard link format*/ +a:link +{ + color: #2e3436; + text-decoration: underline; +} + +/* All views: standard link - visited format */ +a:visited +{ + color: #2e3436; + text-decoration: underline; +} + +/* All views: standard link - activated format */ +a:active +{ + color: #2e3436; + text-decoration: underline; +} + +/* All views: main title format */ +td.title +{ + text-align: center; + padding: 10px; + font-family: sans-serif; + font-style: italic; + font-weight: bold; + font-size: 1.6em; +} + +/* All views: header item format */ +td.headerItem +{ + text-align: right; + padding-right: 6px; + font-family: sans-serif; + font-weight: bold; +} + +/* All views: header item value format */ +td.headerValue +{ + text-align: left; + font-family: sans-serif; + font-weight: bold; +} + +/* All views: header legend item format */ +td.legendItem +{ + text-align: right; + padding-right: 6px; + padding-top: 10px; + padding-bottom: 2px; + font-family: sans-serif; + font-weight: bold; +} + +/* All views: header legend item value format */ +td.legendValue +{ + text-align: left; + padding-top: 10px; + padding-bottom: 2px; + color: #2e3436; + font-family: sans-serif; + font-weight: bold; +} + +/* All views: color of horizontal ruler */ +td.ruler +{ + background-color: #d3d7cf; +} + +/* All views: version string format */ +td.versionInfo +{ + text-align: center; + padding-top: 2px; + font-family: sans-serif; + font-style: italic; +} + +/* Directory view/File view (all)/Test case descriptions: +table headline format */ +td.tableHead +{ + text-align: center; + color: #ffffff; + background-color: #555753; + font-family: sans-serif; + font-weight: bold; +} + +/* Directory view/File view (all): filename entry format */ +td.coverItem, td.coverDirectory, td.coverFile +{ + text-align: left; + padding-left: 10px; + padding-right: 20px; + background-color: #d3d7cf; + font-family: monospace; +} + +td.coverDirectory +{ + font-weight: bold; +} + +/* Directory view/File view (all): bar-graph entry format*/ +td.coverBar +{ + padding-left: 10px; + padding-right: 10px; + background-color: #d3d7cf; +} + +/* Directory view/File view (all): bar-graph outline color */ +td.coverBarOutline +{ + background-color: #2e3436; +} + +/* Directory view/File view (all): percentage entry for files with +no coverage rate */ +td.coverPerNone +{ + text-align: right; + padding-left: 10px; + padding-right: 10px; + background-color: #d3d7cf; + font-weight: bold; +} + +/* Directory view/File view (all): line count entry for files with +no coverage rate */ +td.coverNumNone +{ + text-align: right; + padding-left: 10px; + padding-right: 10px; + background-color: #d3d7cf; + white-space: nowrap; +} + +/* Directory view/File view (all): percentage entry for files with +high coverage rate */ +td.coverPerHi +{ + text-align: right; + padding-left: 10px; + padding-right: 10px; + background-color: #8ae234; + font-weight: bold; +} + +/* Directory view/File view (all): line count entry for files with +high coverage rate */ +td.coverNumHi +{ + text-align: right; + padding-left: 10px; + padding-right: 10px; + background-color: #8ae234; + white-space: nowrap; +} + +/* Directory view/File view (all): legend entry for high coverage +rate */ +span.coverLegendHi +{ + text-align: center; + padding-left: 10px; + padding-right: 10px; + background-color: #8ae234; +} + +/* Directory view/File view (all): percentage entry for files with +medium coverage rate */ +td.coverPerMed +{ + text-align: right; + padding-left: 10px; + padding-right: 10px; + background-color: #fce94f; + font-weight: bold; +} + +/* Directory view/File view (all): line count entry for files with +medium coverage rate */ +td.coverNumMed +{ + text-align: right; + padding-left: 10px; + padding-right: 10px; + background-color: #fce94f; + white-space: nowrap; +} + +/* Directory view/File view (all): legend entry for medium coverage +rate */ +span.coverLegendMed +{ + text-align: center; + padding-left: 10px; + padding-right: 10px; + margin-top: 5px; + margin-bottom: 5px; + margin-right: 2px; + background-color: #fce94f; +} + +/* Directory view/File view (all): percentage entry for files with +low coverage rate */ +td.coverPerLo +{ + text-align: right; + padding-left: 10px; + padding-right: 10px; + background-color: #f57900; + font-weight: bold; +} + +/* Directory view/File view (all): line count entry for files with +low coverage rate */ +td.coverNumLo +{ + text-align: right; + padding-left: 10px; + padding-right: 10px; + background-color: #f57900; + white-space: nowrap; +} + +/* Directory view/File view (all): legend entry for low coverage +rate */ +span.coverLegendLo +{ + text-align: center; + padding-left: 10px; + padding-right: 10px; + margin-right: 2px; + background-color: #f57900; +} + +/* File view (all): "show/hide details" link format */ +a.detail:link +{ + color: #ffffff; +} + +/* File view (all): "show/hide details" link - visited format */ +a.detail:visited +{ + color: #ffffff; +} + +/* File view (all): "show/hide details" link - activated format */ +a.detail:active +{ + color: #ffffff; +} + +/* File view (detail): test name table headline format */ +td.testNameHead +{ + text-align: left; + padding-left: 10px; + background-color: #729fcf; + font-family: sans-serif; + font-weight: bold; +} + +/* File view (detail): test lines table headline format */ +td.testLinesHead +{ + text-align: center; + background-color: #729fcf; + font-family: sans-serif; + font-weight: bold; +} + +/* File view (detail): test name entry */ +td.testName +{ + text-align: left; + padding-left: 10px; + background-color: #729fcf; +} + +/* File view (detail): test percentage entry */ +td.testPer +{ + text-align: right; + vertical-align: top; + padding-left: 10px; + padding-right: 10px; + background-color: #729fcf; +} + +/* File view (detail): test lines count entry */ +td.testNum +{ + text-align: right; + vertical-align: top; + padding-left: 10px; + padding-right: 10px; + background-color: #729fcf; + white-space: nowrap; +} + +/* Test case descriptions: test name format*/ +dt +{ + font-family: sans-serif; + font-weight: bold; +} + +/* Test case descriptions: description table body */ +td.testDescription +{ + padding-top: 10px; + padding-left: 30px; + padding-bottom: 10px; + padding-right: 30px; + background-color: #729fcf; +} + +/* Source code view: source code format */ +pre.source +{ + font-family: monospace; + white-space: pre; +} + +/* Source code view: line number format */ +span.lineNum +{ + background-color: #d3d7cf; +} + +span.lineNum a { + text-decoration: none; +} + +/* Source code view: format for lines which were executed */ +span.lineCov +{ + background-color: #8ae234; +} + +/* Source code view: format for Cov legend */ +span.LegendCov +{ + text-align: center; + padding-left: 10px; + padding-right: 10px; + margin-right: 2px; + background-color: #8ae234; +} + +/* Source code view: format for lines which were not executed */ +span.lineNoCov +{ + background-color: #f57900; +} + +/* Source code view: format for NoCov legend */ +span.LegendNoCov +{ + text-align: center; + padding-left: 10px; + padding-right: 10px; + margin-right: 2px; + background-color: #f57900; +} + +/* Source code view: format for lines which are dead code */ +span.lineDeadCode +{ + background-color: #d3d7cf; +} + +/* Source code view: format for NoCov legend */ +span.LegendDeadCode +{ + text-align: center; + padding-left: 10px; + padding-right: 10px; + margin-right: 2px; + background-color: #d3d7cf; +} + +/* Test view: format for tests which have passed */ +li.testPassed +{ +} + +/* Test view: format for tests which failed */ +li.testFailure +{ + background-color: #f57900; +} + +/* Test view: format for tests which failed with an error */ +li.testError +{ + background-color: #f57900; +} + +/* Test view: format for incomplete and skipped tests */ +li.testIncomplete +{ + background-color: #fcaf3e; +} + +pre span.comment { + color: #888a85; +} + +pre span.default { + color: #2e3436; +} + +pre span.html { + color: #888a85; +} + +pre span.keyword { + color: #2e3436; + font-weight: bold; +} + +pre span.string { + color: #2e3436; +} diff --git a/tests/PHPUnit/Util/Report/Template/yahoo-dom-event.js b/tests/PHPUnit/Util/Report/Template/yahoo-dom-event.js new file mode 100755 index 00000000..2465a2a7 --- /dev/null +++ b/tests/PHPUnit/Util/Report/Template/yahoo-dom-event.js @@ -0,0 +1,12 @@ +/* +Copyright (c) 2008, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.net/yui/license.txt +version: 2.6.0 +*/ +if(typeof YAHOO=="undefined"||!YAHOO){var YAHOO={};}YAHOO.namespace=function(){var A=arguments,E=null,C,B,D;for(C=0;C0)?A.dump(D[F],I-1):L);}else{K.push(D[F]);}K.push(J);}if(K.length>1){K.pop();}K.push("]");}else{K.push("{");for(F in D){if(A.hasOwnProperty(D,F)){K.push(F+G);if(A.isObject(D[F])){K.push((I>0)?A.dump(D[F],I-1):L);}else{K.push(D[F]);}K.push(J);}}if(K.length>1){K.pop();}K.push("}");}return K.join("");},substitute:function(S,E,L){var I,H,G,O,P,R,N=[],F,J="dump",M=" ",D="{",Q="}";for(;;){I=S.lastIndexOf(D);if(I<0){break;}H=S.indexOf(Q,I);if(I+1>=H){break;}F=S.substring(I+1,H);O=F;R=null;G=O.indexOf(M);if(G>-1){R=O.substring(G+1);O=O.substring(0,G);}P=E[O];if(L){P=L(O,P,R);}if(A.isObject(P)){if(A.isArray(P)){P=A.dump(P,parseInt(R,10));}else{R=R||"";var K=R.indexOf(J);if(K>-1){R=R.substring(4);}if(P.toString===Object.prototype.toString||K>-1){P=A.dump(P,parseInt(R,10));}else{P=P.toString();}}}else{if(!A.isString(P)&&!A.isNumber(P)){P="~-"+N.length+"-~";N[N.length]=F;}}S=S.substring(0,I)+P+S.substring(H+1);}for(I=N.length-1;I>=0;I=I-1){S=S.replace(new RegExp("~-"+I+"-~"),"{"+N[I]+"}","g");}return S;},trim:function(D){try{return D.replace(/^\s+|\s+$/g,"");}catch(E){return D;}},merge:function(){var G={},E=arguments;for(var F=0,D=E.length;F=this.left&&A.right<=this.right&&A.top>=this.top&&A.bottom<=this.bottom);};YAHOO.util.Region.prototype.getArea=function(){return((this.bottom-this.top)*(this.right-this.left));};YAHOO.util.Region.prototype.intersect=function(E){var C=Math.max(this.top,E.top);var D=Math.min(this.right,E.right);var A=Math.min(this.bottom,E.bottom);var B=Math.max(this.left,E.left);if(A>=C&&D>=B){return new YAHOO.util.Region(C,D,A,B);}else{return null;}};YAHOO.util.Region.prototype.union=function(E){var C=Math.min(this.top,E.top);var D=Math.max(this.right,E.right);var A=Math.max(this.bottom,E.bottom);var B=Math.min(this.left,E.left);return new YAHOO.util.Region(C,D,A,B);};YAHOO.util.Region.prototype.toString=function(){return("Region {"+"top: "+this.top+", right: "+this.right+", bottom: "+this.bottom+", left: "+this.left+"}");};YAHOO.util.Region.getRegion=function(D){var F=YAHOO.util.Dom.getXY(D);var C=F[1];var E=F[0]+D.offsetWidth;var A=F[1]+D.offsetHeight;var B=F[0];return new YAHOO.util.Region(C,E,A,B);};YAHOO.util.Point=function(A,B){if(YAHOO.lang.isArray(A)){B=A[1];A=A[0];}this.x=this.right=this.left=this[0]=A;this.y=this.top=this.bottom=this[1]=B;};YAHOO.util.Point.prototype=new YAHOO.util.Region();YAHOO.register("dom",YAHOO.util.Dom,{version:"2.6.0",build:"1321"});YAHOO.util.CustomEvent=function(D,B,C,A){this.type=D;this.scope=B||window;this.silent=C;this.signature=A||YAHOO.util.CustomEvent.LIST;this.subscribers=[];if(!this.silent){}var E="_YUICEOnSubscribe";if(D!==E){this.subscribeEvent=new YAHOO.util.CustomEvent(E,this,true);}this.lastError=null;};YAHOO.util.CustomEvent.LIST=0;YAHOO.util.CustomEvent.FLAT=1;YAHOO.util.CustomEvent.prototype={subscribe:function(B,C,A){if(!B){throw new Error("Invalid callback for subscriber to '"+this.type+"'");}if(this.subscribeEvent){this.subscribeEvent.fire(B,C,A);}this.subscribers.push(new YAHOO.util.Subscriber(B,C,A));},unsubscribe:function(D,F){if(!D){return this.unsubscribeAll();}var E=false;for(var B=0,A=this.subscribers.length;B0){B=I[0];}try{G=M.fn.call(L,B,M.obj);}catch(F){this.lastError=F;if(A){throw F;}}}else{try{G=M.fn.call(L,this.type,I,M.obj);}catch(H){this.lastError=H;if(A){throw H;}}}if(false===G){if(!this.silent){}break;}}}return(G!==false);},unsubscribeAll:function(){for(var A=this.subscribers.length-1;A>-1;A--){this._delete(A);}this.subscribers=[];return A;},_delete:function(A){var B=this.subscribers[A];if(B){delete B.fn;delete B.obj;}this.subscribers.splice(A,1);},toString:function(){return"CustomEvent: "+"'"+this.type+"', "+"scope: "+this.scope;}};YAHOO.util.Subscriber=function(B,C,A){this.fn=B;this.obj=YAHOO.lang.isUndefined(C)?null:C;this.override=A;};YAHOO.util.Subscriber.prototype.getScope=function(A){if(this.override){if(this.override===true){return this.obj;}else{return this.override;}}return A;};YAHOO.util.Subscriber.prototype.contains=function(A,B){if(B){return(this.fn==A&&this.obj==B);}else{return(this.fn==A);}};YAHOO.util.Subscriber.prototype.toString=function(){return"Subscriber { obj: "+this.obj+", override: "+(this.override||"no")+" }";};if(!YAHOO.util.Event){YAHOO.util.Event=function(){var H=false;var I=[];var J=[];var G=[];var E=[];var C=0;var F=[];var B=[];var A=0;var D={63232:38,63233:40,63234:37,63235:39,63276:33,63277:34,25:9};var K=YAHOO.env.ua.ie?"focusin":"focus";var L=YAHOO.env.ua.ie?"focusout":"blur";return{POLL_RETRYS:2000,POLL_INTERVAL:20,EL:0,TYPE:1,FN:2,WFN:3,UNLOAD_OBJ:3,ADJ_SCOPE:4,OBJ:5,OVERRIDE:6,CAPTURE:7,lastError:null,isSafari:YAHOO.env.ua.webkit,webkit:YAHOO.env.ua.webkit,isIE:YAHOO.env.ua.ie,_interval:null,_dri:null,DOMReady:false,throwErrors:false,startInterval:function(){if(!this._interval){var M=this;var N=function(){M._tryPreloadAttach();};this._interval=setInterval(N,this.POLL_INTERVAL);}},onAvailable:function(R,O,S,Q,P){var M=(YAHOO.lang.isString(R))?[R]:R;for(var N=0;N-1;Q--){W=(this._removeListener(N[Q],M,V,Y)&&W);}return W;}}if(!V||!V.call){return this.purgeElement(N,false,M);}if("unload"==M){for(Q=J.length-1;Q>-1;Q--){X=J[Q];if(X&&X[0]==N&&X[1]==M&&X[2]==V){J.splice(Q,1);return true;}}return false;}var R=null;var S=arguments[4];if("undefined"===typeof S){S=this._getCacheIndex(N,M,V);}if(S>=0){R=I[S];}if(!N||!R){return false;}if(this.useLegacyEvent(N,M)){var P=this.getLegacyIndex(N,M);var O=E[P];if(O){for(Q=0,T=O.length;Q0&&F.length>0);}var R=[];var T=function(V,W){var U=V;if(W.override){if(W.override===true){U=W.obj;}else{U=W.override;}}W.fn.call(U,W.obj);};var N,M,Q,P,O=[];for(N=0,M=F.length;N-1;N--){Q=F[N];if(!Q||!Q.id){F.splice(N,1);}}this.startInterval();}else{clearInterval(this._interval);this._interval=null;}this.locked=false;},purgeElement:function(Q,R,T){var O=(YAHOO.lang.isString(Q))?this.getEl(Q):Q;var S=this.getListeners(O,T),P,M;if(S){for(P=S.length-1;P>-1;P--){var N=S[P];this._removeListener(O,N.type,N.fn,N.capture);}}if(R&&O&&O.childNodes){for(P=0,M=O.childNodes.length;P-1;O--){N=I[O];if(N){M._removeListener(N[M.EL],N[M.TYPE],N[M.FN],N[M.CAPTURE],O);}}N=null;}G=null;M._simpleRemove(window,"unload",M._unload);},_getScrollLeft:function(){return this._getScroll()[1];},_getScrollTop:function(){return this._getScroll()[0];},_getScroll:function(){var M=document.documentElement,N=document.body;if(M&&(M.scrollTop||M.scrollLeft)){return[M.scrollTop,M.scrollLeft];}else{if(N){return[N.scrollTop,N.scrollLeft];}else{return[0,0];}}},regCE:function(){},_simpleAdd:function(){if(window.addEventListener){return function(O,P,N,M){O.addEventListener(P,N,(M));};}else{if(window.attachEvent){return function(O,P,N,M){O.attachEvent("on"+P,N);};}else{return function(){};}}}(),_simpleRemove:function(){if(window.removeEventListener){return function(O,P,N,M){O.removeEventListener(P,N,(M));};}else{if(window.detachEvent){return function(N,O,M){N.detachEvent("on"+O,M);};}else{return function(){};}}}()};}();(function(){var EU=YAHOO.util.Event;EU.on=EU.addListener;EU.onFocus=EU.addFocusListener;EU.onBlur=EU.addBlurListener; +/* DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller */ +if(EU.isIE){YAHOO.util.Event.onDOMReady(YAHOO.util.Event._tryPreloadAttach,YAHOO.util.Event,true);var n=document.createElement("p");EU._dri=setInterval(function(){try{n.doScroll("left");clearInterval(EU._dri);EU._dri=null;EU._ready();n=null;}catch(ex){}},EU.POLL_INTERVAL);}else{if(EU.webkit&&EU.webkit<525){EU._dri=setInterval(function(){var rs=document.readyState;if("loaded"==rs||"complete"==rs){clearInterval(EU._dri);EU._dri=null;EU._ready();}},EU.POLL_INTERVAL);}else{EU._simpleAdd(document,"DOMContentLoaded",EU._ready);}}EU._simpleAdd(window,"load",EU._load);EU._simpleAdd(window,"unload",EU._unload);EU._tryPreloadAttach();})();}YAHOO.util.EventProvider=function(){};YAHOO.util.EventProvider.prototype={__yui_events:null,__yui_subscribers:null,subscribe:function(A,C,F,E){this.__yui_events=this.__yui_events||{}; +var D=this.__yui_events[A];if(D){D.subscribe(C,F,E);}else{this.__yui_subscribers=this.__yui_subscribers||{};var B=this.__yui_subscribers;if(!B[A]){B[A]=[];}B[A].push({fn:C,obj:F,override:E});}},unsubscribe:function(C,E,G){this.__yui_events=this.__yui_events||{};var A=this.__yui_events;if(C){var F=A[C];if(F){return F.unsubscribe(E,G);}}else{var B=true;for(var D in A){if(YAHOO.lang.hasOwnProperty(A,D)){B=B&&A[D].unsubscribe(E,G);}}return B;}return false;},unsubscribeAll:function(A){return this.unsubscribe(A);},createEvent:function(G,D){this.__yui_events=this.__yui_events||{};var A=D||{};var I=this.__yui_events;if(I[G]){}else{var H=A.scope||this;var E=(A.silent);var B=new YAHOO.util.CustomEvent(G,H,E,YAHOO.util.CustomEvent.FLAT);I[G]=B;if(A.onSubscribeCallback){B.subscribeEvent.subscribe(A.onSubscribeCallback);}this.__yui_subscribers=this.__yui_subscribers||{};var F=this.__yui_subscribers[G];if(F){for(var C=0;C{tests}", + "footer": "" + }, diff --git a/tests/PHPUnit/Util/Skeleton.php b/tests/PHPUnit/Util/Skeleton.php new file mode 100755 index 00000000..d10b45b1 --- /dev/null +++ b/tests/PHPUnit/Util/Skeleton.php @@ -0,0 +1,121 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.1.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Template.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Generator for skeletons. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.1.0 + */ +abstract class PHPUnit_Util_Skeleton +{ + /** + * @var string + */ + protected $inClassName; + + /** + * @var string + */ + protected $inSourceFile; + + /** + * @var string + */ + protected $outClassName; + + /** + * @var string + */ + protected $outSourceFile; + + /** + * @return string + */ + public function getOutClassName() + { + return $this->outClassName; + } + + /** + * @return string + */ + public function getOutSourceFile() + { + return $this->outSourceFile; + } + + /** + * Generates the code and writes it to a source file. + * + * @param string $file + */ + public function write($file = '') + { + if ($file == '') { + $file = $this->outSourceFile; + } + + if ($fp = @fopen($file, 'wt')) { + @fwrite($fp, $this->generate()); + @fclose($fp); + } + } + + abstract public function generate(); +} +?> diff --git a/tests/PHPUnit/Util/Skeleton/Class.php b/tests/PHPUnit/Util/Skeleton/Class.php new file mode 100755 index 00000000..3542821f --- /dev/null +++ b/tests/PHPUnit/Util/Skeleton/Class.php @@ -0,0 +1,257 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Template.php'; +require_once 'PHPUnit/Util/Skeleton.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Generator for class skeletons from test classes. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class PHPUnit_Util_Skeleton_Class extends PHPUnit_Util_Skeleton +{ + protected $tokens = array(); + + /** + * Constructor. + * + * @param string $inClassName + * @param string $inSourceFile + * @throws RuntimeException + */ + public function __construct($inClassName, $inSourceFile = '') + { + if (empty($inSourceFile)) { + $this->inSourceFile = $inClassName . '.php'; + } else { + $this->inSourceFile = $inSourceFile; + } + + if (!is_file($inSourceFile)) { + throw new RuntimeException( + sprintf( + '"%s" could not be opened.', + + $inSourceFile + ) + ); + } + + $this->tokens = token_get_all(file_get_contents($inSourceFile)); + + $this->inClassName = $inClassName; + $this->outClassName = substr($inClassName, 0, strlen($inClassName) - 4); + $this->outSourceFile = dirname($this->inSourceFile) . DIRECTORY_SEPARATOR . $this->outClassName . '.php'; + } + + /** + * Generates the class' source. + * + * @return mixed + */ + public function generate() + { + $methods = ''; + + foreach ($this->findMethods() as $method) { + $methodTemplate = new PHPUnit_Util_Template( + sprintf( + '%s%sTemplate%sMethod.tpl', + + dirname(__FILE__), + DIRECTORY_SEPARATOR, + DIRECTORY_SEPARATOR + ) + ); + + $methodTemplate->setVar( + array( + 'methodName' => $method, + ) + ); + + $methods .= $methodTemplate->render(); + } + + $classTemplate = new PHPUnit_Util_Template( + sprintf( + '%s%sTemplate%sClass.tpl', + + dirname(__FILE__), + DIRECTORY_SEPARATOR, + DIRECTORY_SEPARATOR + ) + ); + + $classTemplate->setVar( + array( + 'className' => $this->outClassName, + 'methods' => $methods, + 'date' => date('Y-m-d'), + 'time' => date('H:i:s') + ) + ); + + return $classTemplate->render(); + } + + /** + * Returns the methods of the class under test + * that are called from the test methods. + * + * @return array + */ + protected function findMethods() + { + $methods = array(); + $numTokens = count($this->tokens); + $variables = $this->findVariablesThatReferenceClass(); + + for ($i = 0; $i < $numTokens; $i++) { + if (is_array($this->tokens[$i])) { + if ($this->tokens[$i][0] == T_DOUBLE_COLON && + $this->tokens[$i-1][0] == T_STRING && + $this->tokens[$i+1][0] == T_STRING && + trim($this->tokens[$i+2]) == '(' && + !in_array($this->tokens[$i+1][1], $methods)) { + $methods[] = $this->tokens[$i+1][1]; + } + + else if ($this->tokens[$i][0] == T_OBJECT_OPERATOR && + is_string($this->tokens[$i+2]) && trim($this->tokens[$i+2]) == '(' && + in_array($this->findVariableName($i), $variables) && + !in_array($this->tokens[$i+1][1], $methods)) { + $methods[] = $this->tokens[$i+1][1]; + } + } + } + + sort($methods); + + return $methods; + } + + /** + * Returns the variables used in test methods + * that reference the class under test. + * + * @return array + */ + protected function findVariablesThatReferenceClass() + { + $inNew = FALSE; + $numTokens = count($this->tokens); + $variables = array(); + + for ($i = 0; $i < $numTokens; $i++) { + if (is_string($this->tokens[$i])) { + if (trim($this->tokens[$i]) == ';') { + $inNew = FALSE; + } + + continue; + } + + list ($_token, $_value) = $this->tokens[$i]; + + switch ($_token) { + case T_NEW: { + $inNew = TRUE; + } + break; + + case T_STRING: { + if ($inNew) { + if ($_value == $this->outClassName) { + $variables[] = $this->findVariableName($i); + } + } + + $inNew = FALSE; + } + break; + } + } + + return $variables; + } + + /** + * Finds the variable name of the object for the method call + * that is currently being processed. + * + * @param integer $start + * @return mixed + */ + protected function findVariableName($start) + { + for ($i = $start - 1; $i >= 0; $i--) { + if (is_array($this->tokens[$i]) && $this->tokens[$i][0] == T_VARIABLE) { + $variable = $this->tokens[$i][1]; + + if (is_array($this->tokens[$i+1]) && $this->tokens[$i+1][0] == T_OBJECT_OPERATOR) { + $variable .= '->' . $this->tokens[$i+2][1]; + } + + return $variable; + } + } + + return FALSE; + } +} +?> diff --git a/tests/PHPUnit/Util/Skeleton/Template/Class.tpl.dist b/tests/PHPUnit/Util/Skeleton/Template/Class.tpl.dist new file mode 100755 index 00000000..2a29e5e0 --- /dev/null +++ b/tests/PHPUnit/Util/Skeleton/Template/Class.tpl.dist @@ -0,0 +1,7 @@ + diff --git a/tests/PHPUnit/Util/Skeleton/Template/IncompleteTestMethod.tpl.dist b/tests/PHPUnit/Util/Skeleton/Template/IncompleteTestMethod.tpl.dist new file mode 100755 index 00000000..d89f90ee --- /dev/null +++ b/tests/PHPUnit/Util/Skeleton/Template/IncompleteTestMethod.tpl.dist @@ -0,0 +1,11 @@ + + /** + * @todo Implement test{methodName}(). + */ + public function test{methodName}() + { + // Remove the following lines when you implement this test. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + } diff --git a/tests/PHPUnit/Util/Skeleton/Template/Method.tpl.dist b/tests/PHPUnit/Util/Skeleton/Template/Method.tpl.dist new file mode 100755 index 00000000..dd3b0449 --- /dev/null +++ b/tests/PHPUnit/Util/Skeleton/Template/Method.tpl.dist @@ -0,0 +1,9 @@ + + /** + * @todo Implement {methodName}(). + */ + public function {methodName}() + { + // Remove the following line when you implement this method. + throw new RuntimeException('Not yet implemented.'); + } diff --git a/tests/PHPUnit/Util/Skeleton/Template/TestClass.tpl.dist b/tests/PHPUnit/Util/Skeleton/Template/TestClass.tpl.dist new file mode 100755 index 00000000..e71de2ce --- /dev/null +++ b/tests/PHPUnit/Util/Skeleton/Template/TestClass.tpl.dist @@ -0,0 +1,37 @@ +object = new {className}; + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + * + * @access protected + */ + protected function tearDown() + { + } +{methods}} +?> diff --git a/tests/PHPUnit/Util/Skeleton/Template/TestMethod.tpl.dist b/tests/PHPUnit/Util/Skeleton/Template/TestMethod.tpl.dist new file mode 100755 index 00000000..68acf2b7 --- /dev/null +++ b/tests/PHPUnit/Util/Skeleton/Template/TestMethod.tpl.dist @@ -0,0 +1,11 @@ + + /** + * Generated from @assert {annotation}. + */ + public function test{methodName}() + { + $this->assert{assertion}( + {expected}, + $this->object->{origMethodName}({arguments}) + ); + } diff --git a/tests/PHPUnit/Util/Skeleton/Template/TestMethodBool.tpl.dist b/tests/PHPUnit/Util/Skeleton/Template/TestMethodBool.tpl.dist new file mode 100755 index 00000000..483a2729 --- /dev/null +++ b/tests/PHPUnit/Util/Skeleton/Template/TestMethodBool.tpl.dist @@ -0,0 +1,10 @@ + + /** + * Generated from @assert {annotation}. + */ + public function test{methodName}() + { + $this->assert{assertion}( + $this->object->{origMethodName}({arguments}) + ); + } diff --git a/tests/PHPUnit/Util/Skeleton/Template/TestMethodBoolStatic.tpl.dist b/tests/PHPUnit/Util/Skeleton/Template/TestMethodBoolStatic.tpl.dist new file mode 100755 index 00000000..f46d84da --- /dev/null +++ b/tests/PHPUnit/Util/Skeleton/Template/TestMethodBoolStatic.tpl.dist @@ -0,0 +1,10 @@ + + /** + * Generated from @assert {annotation}. + */ + public function test{methodName}() + { + $this->assert{assertion}( + {className}::{origMethodName}({arguments}) + ); + } diff --git a/tests/PHPUnit/Util/Skeleton/Template/TestMethodException.tpl.dist b/tests/PHPUnit/Util/Skeleton/Template/TestMethodException.tpl.dist new file mode 100755 index 00000000..75c02b0f --- /dev/null +++ b/tests/PHPUnit/Util/Skeleton/Template/TestMethodException.tpl.dist @@ -0,0 +1,9 @@ + + /** + * Generated from @assert {annotation}. + * @expectedException {expected} + */ + public function test{methodName}() + { + $this->object->{origMethodName}({arguments}); + } diff --git a/tests/PHPUnit/Util/Skeleton/Template/TestMethodExceptionStatic.tpl.dist b/tests/PHPUnit/Util/Skeleton/Template/TestMethodExceptionStatic.tpl.dist new file mode 100755 index 00000000..5f27729e --- /dev/null +++ b/tests/PHPUnit/Util/Skeleton/Template/TestMethodExceptionStatic.tpl.dist @@ -0,0 +1,9 @@ + + /** + * Generated from @assert {annotation}. + * @expectedException {expected} + */ + public function test{methodName}() + { + {className}::{origMethodName}({arguments}); + } diff --git a/tests/PHPUnit/Util/Skeleton/Template/TestMethodStatic.tpl.dist b/tests/PHPUnit/Util/Skeleton/Template/TestMethodStatic.tpl.dist new file mode 100755 index 00000000..b4fe571b --- /dev/null +++ b/tests/PHPUnit/Util/Skeleton/Template/TestMethodStatic.tpl.dist @@ -0,0 +1,11 @@ + + /** + * Generated from @assert {annotation}. + */ + public function test{methodName}() + { + $this->assert{assertion}( + {expected}, + {className}::{origMethodName}({arguments}) + ); + } diff --git a/tests/PHPUnit/Util/Skeleton/Test.php b/tests/PHPUnit/Util/Skeleton/Test.php new file mode 100755 index 00000000..d35617a2 --- /dev/null +++ b/tests/PHPUnit/Util/Skeleton/Test.php @@ -0,0 +1,348 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.3.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/Template.php'; +require_once 'PHPUnit/Util/Skeleton.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Generator for test class skeletons from classes. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.3.0 + */ +class PHPUnit_Util_Skeleton_Test extends PHPUnit_Util_Skeleton +{ + /** + * @var array + */ + protected $methodNameCounter = array(); + + /** + * Constructor. + * + * @param string $inClassName + * @param string $inSourceFile + * @throws RuntimeException + */ + public function __construct($inClassName, $inSourceFile = '') + { + $this->inClassName = $inClassName; + $this->outClassName = $inClassName . 'Test'; + + if (class_exists($inClassName)) { + $this->inSourceFile = ''; + } + + else if (empty($inSourceFile) && is_file($inClassName . '.php')) { + $this->inSourceFile = $inClassName . '.php'; + } + + else if (empty($inSourceFile) || + is_file(str_replace('_', '/', $inClassName) . '.php')) { + $this->inSourceFile = str_replace('_', '/', $inClassName) . '.php'; + $this->outSourceFile = str_replace('_', '/', $inClassName) . 'Test.php'; + } + + else if (empty($inSourceFile)) { + throw new RuntimeException( + sprintf( + 'Neither "%s.php" nor "%s.php" could be opened.', + $inClassName, + str_replace('_', '/', $inClassName) + ) + ); + } + + else if (!is_file($inSourceFile)) { + throw new RuntimeException( + sprintf( + '"%s" could not be opened.', + + $inSourceFile + ) + ); + } else { + $this->inSourceFile = $inSourceFile; + } + + if ($this->inSourceFile != '') { + include_once $this->inSourceFile; + } + + if (!class_exists($inClassName)) { + throw new RuntimeException( + sprintf( + 'Could not find class "%s" in "%s".', + + $inClassName, + realpath($this->inSourceFile) + ) + ); + } + + $this->outSourceFile = dirname($this->inSourceFile) . DIRECTORY_SEPARATOR . $this->inClassName . 'Test.php'; + } + + /** + * Generates the test class' source. + * + * @param boolean $verbose + * @return mixed + */ + public function generate($verbose = FALSE) + { + $class = new ReflectionClass($this->inClassName); + $methods = ''; + $incompleteMethods = ''; + + foreach ($class->getMethods() as $method) { + if (!$method->isConstructor() && + !$method->isAbstract() && + $method->isPublic() && + $method->getDeclaringClass()->getName() == $this->inClassName) { + $assertAnnotationFound = FALSE; + + if (preg_match_all('/@assert(.*)$/Um', $method->getDocComment(), $annotations)) { + foreach ($annotations[1] as $annotation) { + if (preg_match('/\((.*)\)\s+([^\s]*)\s+(.*)/', $annotation, $matches)) { + switch ($matches[2]) { + case '==': { + $assertion = 'Equals'; + } + break; + + case '!=': { + $assertion = 'NotEquals'; + } + break; + + case '===': { + $assertion = 'Same'; + } + break; + + case '!==': { + $assertion = 'NotSame'; + } + break; + + case '>': { + $assertion = 'GreaterThan'; + } + break; + + case '>=': { + $assertion = 'GreaterThanOrEqual'; + } + break; + + case '<': { + $assertion = 'LessThan'; + } + break; + + case '<=': { + $assertion = 'LessThanOrEqual'; + } + break; + + case 'throws': { + $assertion = 'exception'; + } + break; + + default: { + throw new RuntimeException; + } + } + + if ($assertion == 'exception') { + $template = 'TestMethodException'; + } + + else if ($assertion == 'Equals' && strtolower($matches[3]) == 'true') { + $assertion = 'True'; + $template = 'TestMethodBool'; + } + + else if ($assertion == 'NotEquals' && strtolower($matches[3]) == 'true') { + $assertion = 'False'; + $template = 'TestMethodBool'; + } + + else if ($assertion == 'Equals' && strtolower($matches[3]) == 'false') { + $assertion = 'False'; + $template = 'TestMethodBool'; + } + + else if ($assertion == 'NotEquals' && strtolower($matches[3]) == 'false') { + $assertion = 'True'; + $template = 'TestMethodBool'; + } + + else { + $template = 'TestMethod'; + } + + if ($method->isStatic()) { + $template .= 'Static'; + } + + $methodTemplate = new PHPUnit_Util_Template( + sprintf( + '%s%sTemplate%s%s.tpl', + + dirname(__FILE__), + DIRECTORY_SEPARATOR, + DIRECTORY_SEPARATOR, + $template + ) + ); + + $origMethodName = $method->getName(); + $methodName = ucfirst($origMethodName); + + if (isset($this->methodNameCounter[$methodName])) { + $this->methodNameCounter[$methodName]++; + } else { + $this->methodNameCounter[$methodName] = 1; + } + + if ($this->methodNameCounter[$methodName] > 1) { + $methodName .= $this->methodNameCounter[$methodName]; + } + + $methodTemplate->setVar( + array( + 'annotation' => trim($annotation), + 'arguments' => $matches[1], + 'assertion' => isset($assertion) ? $assertion : '', + 'expected' => $matches[3], + 'origMethodName' => $origMethodName, + 'className' => $this->inClassName, + 'methodName' => $methodName + ) + ); + + $methods .= $methodTemplate->render(); + + $assertAnnotationFound = TRUE; + } + } + } + + if (!$assertAnnotationFound) { + $methodTemplate = new PHPUnit_Util_Template( + sprintf( + '%s%sTemplate%sIncompleteTestMethod.tpl', + + dirname(__FILE__), + DIRECTORY_SEPARATOR, + DIRECTORY_SEPARATOR + ) + ); + + $methodTemplate->setVar( + array( + 'methodName' => ucfirst($method->getName()) + ) + ); + + $incompleteMethods .= $methodTemplate->render(); + } + } + } + + $classTemplate = new PHPUnit_Util_Template( + sprintf( + '%s%sTemplate%sTestClass.tpl', + + dirname(__FILE__), + DIRECTORY_SEPARATOR, + DIRECTORY_SEPARATOR + ) + ); + + if ($this->inSourceFile != '') { + $requireClassFile = sprintf( + "\n\nrequire_once '%s';", + + $this->inSourceFile + ); + } else { + $requireClassFile = ''; + } + + $classTemplate->setVar( + array( + 'className' => $this->inClassName, + 'requireClassFile' => $requireClassFile, + 'methods' => $methods . $incompleteMethods, + 'date' => date('Y-m-d'), + 'time' => date('H:i:s') + ) + ); + + if (!$verbose) { + return $classTemplate->render(); + } else { + return array( + 'code' => $classTemplate->render(), + 'incomplete' => empty($methods) + ); + } + } +} +?> diff --git a/tests/PHPUnit/Util/Template.php b/tests/PHPUnit/Util/Template.php new file mode 100755 index 00000000..7fb349d4 --- /dev/null +++ b/tests/PHPUnit/Util/Template.php @@ -0,0 +1,179 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Util_Template +{ + /** + * @var string + */ + protected static $date = ''; + + /** + * @var string + */ + protected $template = ''; + + /** + * @var array + */ + protected $values = array(); + + /** + * Constructor. + * + * @param string $file + * @throws InvalidArgumentException + */ + public function __construct($file = '') + { + $this->setFile($file); + } + + /** + * Sets the template file. + * + * @param string $file + * @throws InvalidArgumentException + */ + public function setFile($file) + { + $distFile = $file . '.dist'; + + if (file_exists($file)) { + $this->template = file_get_contents($file); + } + + else if (file_exists($distFile)) { + $this->template = file_get_contents($distFile); + } + + else { + throw new InvalidArgumentException( + 'Template file could not be loaded.' + ); + } + } + + /** + * Sets one or more template variables. + * + * @param array $values + * @param boolean $merge + */ + public function setVar(array $values, $merge = TRUE) + { + if (!$merge || empty($this->values)) { + $this->values = $values; + } else { + $this->values = array_merge($this->values, $values); + } + } + + /** + * Renders the template and returns the result. + * + * @return string + */ + public function render() + { + $keys = array(); + + foreach ($this->values as $key => $value) { + $keys[] = '{' . $key . '}'; + } + + return str_replace($keys, $this->values, $this->template); + } + + /** + * Renders the template and writes the result to a file. + * + * @param string $target + */ + public function renderTo($target) + { + $fp = @fopen($target, 'wt'); + + if ($fp) { + fwrite($fp, $this->render()); + fclose($fp); + } else { + throw new RuntimeException('Could not write to ' . $target . '.'); + } + } + + /** + * Returns the cached result of date('D M j G:i:s T Y'). + * + * @return string + * @since Method available since Release 3.0.1 + */ + public static function getDate() + { + if (self::$date == '') { + self::$date = date('D M j G:i:s T Y'); + } + + return self::$date; + } +} +?> diff --git a/tests/PHPUnit/Util/Test.php b/tests/PHPUnit/Util/Test.php new file mode 100755 index 00000000..a5dc3fae --- /dev/null +++ b/tests/PHPUnit/Util/Test.php @@ -0,0 +1,371 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Test helpers. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Util_Test +{ + const REGEX_COVERS = '/@covers[\s]+([\!<>\:\.\w]+)([\s]+)?/'; + const REGEX_DATA_PROVIDER = '/@dataProvider\s+([a-zA-Z0-9._:-\\\]+)/'; + const REGEX_EXPECTED_EXCEPTION = '(@expectedException\s+([:.\w\\\]+)(?:[\t ]+(\S*))?(?:[\t ]+(\S*))?\s*$)m'; + const REGEX_GROUP = '/@group\s+([a-zA-Z0-9._-]+)/'; + + /** + * @param PHPUnit_Framework_Test $test + * @param boolean $asString + * @return mixed + */ + public static function describe(PHPUnit_Framework_Test $test, $asString = TRUE) + { + if ($asString) { + if ($test instanceof PHPUnit_Framework_SelfDescribing) { + return $test->toString(); + } else { + return get_class($test); + } + } else { + if ($test instanceof PHPUnit_Framework_TestCase) { + return array( + get_class($test), $test->getName() + ); + } + + else if ($test instanceof PHPUnit_Framework_SelfDescribing) { + return array('', $test->toString()); + } + + else { + return array('', get_class($test)); + } + } + } + + /** + * @param PHPUnit_Framework_Test $test + * @param PHPUnit_Framework_TestResult $result + * @return mixed + */ + public static function lookupResult(PHPUnit_Framework_Test $test, PHPUnit_Framework_TestResult $result) + { + $testName = self::describe($test); + + foreach ($result->errors() as $error) { + if ($testName == self::describe($error->failedTest())) { + return $error; + } + } + + foreach ($result->failures() as $failure) { + if ($testName == self::describe($failure->failedTest())) { + return $failure; + } + } + + foreach ($result->notImplemented() as $notImplemented) { + if ($testName == self::describe($notImplemented->failedTest())) { + return $notImplemented; + } + } + + foreach ($result->skipped() as $skipped) { + if ($testName == self::describe($skipped->failedTest())) { + return $skipped; + } + } + + return PHPUnit_Runner_BaseTestRunner::STATUS_PASSED; + } + + /** + * Returns the files and lines a test method wants to cover. + * + * @param string $className + * @param string $methodName + * @return array + * @since Method available since Release 3.2.0 + */ + public static function getLinesToBeCovered($className, $methodName) + { + $result = array(); + $codeToCoverList = array(); + + if (($pos = strpos($methodName, ' ')) !== FALSE) { + $methodName = substr($methodName, 0, $pos); + } + + try { + $class = new ReflectionClass($className); + $method = new ReflectionMethod($className, $methodName); + $docComment = $class->getDocComment() . $method->getDocComment(); + + if (preg_match_all(self::REGEX_COVERS, $docComment, $matches)) { + foreach ($matches[1] as $i => $method) { + $codeToCoverList = array_merge( + $codeToCoverList, + self::resolveCoversToReflectionObjects($method, !empty($matches[2][$i])) + ); + } + + foreach ($codeToCoverList as $codeToCover) { + $fileName = $codeToCover->getFileName(); + $startLine = $codeToCover->getStartLine(); + $endLine = $codeToCover->getEndLine(); + + if (!isset($result[$fileName])) { + $result[$fileName] = array(); + } + + $result[$fileName] = array_unique( + array_merge($result[$fileName], range($startLine, $endLine)) + ); + } + } + } + + catch (ReflectionException $e) { + } + + return $result; + } + + /** + * Returns the expected exception for a test. + * + * @param string $docComment + * @return array + * @since Method available since Release 3.3.6 + */ + public static function getExpectedException($docComment) + { + if (preg_match(self::REGEX_EXPECTED_EXCEPTION, $docComment, $matches)) { + $class = $matches[1]; + $code = 0; + $message = ''; + + if (isset($matches[2])) { + $message = trim($matches[2]); + } + + if (isset($matches[3])) { + $code = (int)$matches[3]; + } + + return array( + 'class' => $class, 'code' => $code, 'message' => $message + ); + } + + return FALSE; + } + + /** + * Returns the groups for a test class or method. + * + * @param string $docComment + * @param array $groups + * @return array + * @since Method available since Release 3.2.0 + */ + public static function getGroups($docComment, array $groups = array()) + { + if (preg_match_all(self::REGEX_GROUP, $docComment, $matches)) { + $groups = array_unique(array_merge($groups, $matches[1])); + } + + return $groups; + } + + /** + * Returns the provided data for a method. + * + * @param string $className + * @param string $methodName + * @param string $docComment + * @return array + * @since Method available since Release 3.2.0 + */ + public static function getProvidedData($className, $methodName, $docComment) + { + if (preg_match(self::REGEX_DATA_PROVIDER, $docComment, $matches)) { + try { + $dataProviderMethodNameNamespace = explode('\\', $matches[1]); + $leaf = explode('::', array_pop($dataProviderMethodNameNamespace)); + $dataProviderMethodName = array_pop($leaf); + + if (!empty($dataProviderMethodNameNamespace)) { + $dataProviderMethodNameNamespace = join('\\', $dataProviderMethodNameNamespace) . '\\'; + } else { + $dataProviderMethodNameNamespace = ''; + } + + if (!empty($leaf)) { + $dataProviderClassName = $dataProviderMethodNameNamespace . array_pop($leaf); + } else { + $dataProviderClassName = $className; + } + + $dataProviderClass = new ReflectionClass($dataProviderClassName); + $dataProviderMethod = $dataProviderClass->getMethod( + $dataProviderMethodName + ); + + if ($dataProviderMethod->isStatic()) { + $object = NULL; + } else { + $object = $dataProviderClass->newInstance(); + } + + if ($dataProviderMethod->getNumberOfParameters() == 0) { + return $dataProviderMethod->invoke($object); + } else { + return $dataProviderMethod->invoke($object, $methodName); + } + } + + catch (ReflectionException $e) { + } + } + } + + /** + * Returns the files and lines a test method wants to cover. + * + * @param string $method + * @param boolean $extended + * @return array + * @since Method available since Release 3.3.0 + */ + private static function resolveCoversToReflectionObjects($method, $extended) + { + $codeToCoverList = array(); + + if (strpos($method, '::') !== FALSE) { + list($className, $methodName) = explode('::', $method); + + if ($methodName{0} == '<') { + $classes = array($className); + + if ($extended) { + $classes = array_merge( + $classes, + class_implements($className), + class_parents($className) + ); + } + + foreach ($classes as $className) + { + $class = new ReflectionClass($className); + $methods = $class->getMethods(); + $inverse = isset($methodName{1}) && $methodName{1} == '!'; + + if (strpos($methodName, 'protected')) { + $visibility = 'isProtected'; + } + + else if (strpos($methodName, 'private')) { + $visibility = 'isPrivate'; + } + + else if (strpos($methodName, 'public')) { + $visibility = 'isPublic'; + } + + foreach ($methods as $method) { + if ($inverse && !$method->$visibility()) { + $codeToCoverList[] = $method; + } + + else if (!$inverse && $method->$visibility()) { + $codeToCoverList[] = $method; + } + } + } + } else { + $classes = array($className); + + if ($extended) { + $classes = array_merge($classes, class_parents($className)); + } + + foreach ($classes as $className) { + $codeToCoverList[] = new ReflectionMethod($className, $methodName); + } + } + } else { + $classes = array($method); + + if ($extended) { + $classes = array_merge( + $classes, + class_implements($method), + class_parents($method) + ); + } + + foreach ($classes as $className) { + $codeToCoverList[] = new ReflectionClass($className); + } + } + + return $codeToCoverList; + } +} +?> diff --git a/tests/PHPUnit/Util/TestDox/NamePrettifier.php b/tests/PHPUnit/Util/TestDox/NamePrettifier.php new file mode 100755 index 00000000..6bd9dab2 --- /dev/null +++ b/tests/PHPUnit/Util/TestDox/NamePrettifier.php @@ -0,0 +1,180 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.3.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Prettifies class and method names for use in TestDox documentation. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.1.0 + */ +class PHPUnit_Util_TestDox_NamePrettifier +{ + /** + * @var string + */ + protected $prefix = 'Test'; + + /** + * @var string + */ + protected $suffix = 'Test'; + + /** + * @var array + */ + protected $strings = array(); + + /** + * Prettifies the name of a test class. + * + * @param string $testClassName + * @return string + */ + public function prettifyTestClass($testClassName) + { + $title = $testClassName; + + if ($this->suffix !== NULL && + $this->suffix == substr($testClassName, -1 * strlen($this->suffix))) { + $title = substr($title, 0, strripos($title, $this->suffix)); + } + + if ($this->prefix !== NULL && + $this->prefix == substr($testClassName, 0, strlen($this->prefix))) { + $title = substr($title, strlen($this->prefix)); + } + + return $title; + } + + /** + * Prettifies the name of a test method. + * + * @param string $testMethodName + * @return string + */ + public function prettifyTestMethod($testMethodName) + { + $buffer = ''; + + if (!is_string($testMethodName) || strlen($testMethodName) == 0) { + return $buffer; + } + + $string = preg_replace('#\d+$#', '', $testMethodName); + + if (in_array($string, $this->strings)) { + $testMethodName = $string; + } else { + $this->strings[] = $string; + } + + $max = strlen($testMethodName); + + if (substr($testMethodName, 0, 4) == 'test') { + $offset = 4; + } else { + $offset = 0; + $testMethodName[0] = strtoupper($testMethodName[0]); + } + + $wasNumeric = FALSE; + + for ($i = $offset; $i < $max; $i++) { + if ($i > $offset && + ord($testMethodName[$i]) >= 65 && + ord($testMethodName[$i]) <= 90) { + $buffer .= ' ' . strtolower($testMethodName[$i]); + } else { + $isNumeric = is_numeric($testMethodName[$i]); + + if (!$wasNumeric && $isNumeric) { + $buffer .= ' '; + $wasNumeric = TRUE; + } + + if ($wasNumeric && !$isNumeric) { + $wasNumeric = FALSE; + } + + $buffer .= $testMethodName[$i]; + } + } + + return $buffer; + } + + /** + * Sets the prefix of test names. + * + * @param string $prefix + */ + public function setPrefix($prefix) + { + $this->prefix = $prefix; + } + + /** + * Sets the suffix of test names. + * + * @param string $prefix + */ + public function setSuffix($suffix) + { + $this->suffix = $suffix; + } +} +?> diff --git a/tests/PHPUnit/Util/TestDox/ResultPrinter.php b/tests/PHPUnit/Util/TestDox/ResultPrinter.php new file mode 100755 index 00000000..0337f779 --- /dev/null +++ b/tests/PHPUnit/Util/TestDox/ResultPrinter.php @@ -0,0 +1,324 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.3.0 + */ + +require_once 'PHPUnit/Framework.php'; +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/TestDox/NamePrettifier.php'; +require_once 'PHPUnit/Util/Printer.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Base class for printers of TestDox documentation. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.1.0 + * @abstract + */ +abstract class PHPUnit_Util_TestDox_ResultPrinter extends PHPUnit_Util_Printer implements PHPUnit_Framework_TestListener +{ + /** + * @var PHPUnit_Util_TestDox_NamePrettifier + */ + protected $prettifier; + + /** + * @var string + */ + protected $testClass = ''; + + /** + * @var integer + */ + protected $testStatus = FALSE; + + /** + * @var array + */ + protected $tests = array(); + + protected $successful = 0; + protected $failed = 0; + protected $skipped = 0; + protected $incomplete = 0; + protected $testTypeOfInterest = 'PHPUnit_Framework_TestCase'; + + /** + * @var string + */ + protected $currentTestClassPrettified; + + /** + * @var string + */ + protected $currentTestMethodPrettified; + + /** + * Constructor. + * + * @param resource $out + */ + public function __construct($out = NULL) + { + parent::__construct($out); + + $this->prettifier = new PHPUnit_Util_TestDox_NamePrettifier; + $this->startRun(); + } + + /** + * Flush buffer and close output. + * + */ + public function flush() + { + $this->doEndClass(); + $this->endRun(); + + parent::flush(); + } + + /** + * An error occurred. + * + * @param PHPUnit_Framework_Test $test + * @param Exception $e + * @param float $time + */ + public function addError(PHPUnit_Framework_Test $test, Exception $e, $time) + { + if ($test instanceof $this->testTypeOfInterest) { + $this->testStatus = PHPUnit_Runner_BaseTestRunner::STATUS_ERROR; + $this->failed++; + } + } + + /** + * A failure occurred. + * + * @param PHPUnit_Framework_Test $test + * @param PHPUnit_Framework_AssertionFailedError $e + * @param float $time + */ + public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time) + { + if ($test instanceof $this->testTypeOfInterest) { + $this->testStatus = PHPUnit_Runner_BaseTestRunner::STATUS_FAILURE; + $this->failed++; + } + } + + /** + * Incomplete test. + * + * @param PHPUnit_Framework_Test $test + * @param Exception $e + * @param float $time + */ + public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time) + { + if ($test instanceof $this->testTypeOfInterest) { + $this->testStatus = PHPUnit_Runner_BaseTestRunner::STATUS_INCOMPLETE; + $this->incomplete++; + } + } + + /** + * Skipped test. + * + * @param PHPUnit_Framework_Test $test + * @param Exception $e + * @param float $time + * @since Method available since Release 3.0.0 + */ + public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time) + { + if ($test instanceof $this->testTypeOfInterest) { + $this->testStatus = PHPUnit_Runner_BaseTestRunner::STATUS_SKIPPED; + $this->skipped++; + } + } + + /** + * A testsuite started. + * + * @param PHPUnit_Framework_TestSuite $suite + * @since Method available since Release 2.2.0 + */ + public function startTestSuite(PHPUnit_Framework_TestSuite $suite) + { + } + + /** + * A testsuite ended. + * + * @param PHPUnit_Framework_TestSuite $suite + * @since Method available since Release 2.2.0 + */ + public function endTestSuite(PHPUnit_Framework_TestSuite $suite) + { + } + + /** + * A test started. + * + * @param PHPUnit_Framework_Test $test + */ + public function startTest(PHPUnit_Framework_Test $test) + { + if ($test instanceof $this->testTypeOfInterest) { + $class = get_class($test); + + if ($this->testClass != $class) { + if ($this->testClass != '') { + $this->doEndClass(); + } + + $this->currentTestClassPrettified = $this->prettifier->prettifyTestClass($class); + $this->startClass($class); + + $this->testClass = $class; + $this->tests = array(); + } + + $this->currentTestMethodPrettified = $this->prettifier->prettifyTestMethod($test->getName()); + $this->testStatus = PHPUnit_Runner_BaseTestRunner::STATUS_PASSED; + } + } + + /** + * A test ended. + * + * @param PHPUnit_Framework_Test $test + * @param float $time + */ + public function endTest(PHPUnit_Framework_Test $test, $time) + { + if ($test instanceof $this->testTypeOfInterest) { + if (!isset($this->tests[$this->currentTestMethodPrettified])) { + if ($this->testStatus == PHPUnit_Runner_BaseTestRunner::STATUS_PASSED) { + $this->tests[$this->currentTestMethodPrettified]['success'] = 1; + $this->tests[$this->currentTestMethodPrettified]['failure'] = 0; + } else { + $this->tests[$this->currentTestMethodPrettified]['success'] = 0; + $this->tests[$this->currentTestMethodPrettified]['failure'] = 1; + } + } else { + if ($this->testStatus == PHPUnit_Runner_BaseTestRunner::STATUS_PASSED) { + $this->tests[$this->currentTestMethodPrettified]['success']++; + } else { + $this->tests[$this->currentTestMethodPrettified]['failure']++; + } + } + + $this->currentTestClassPrettified = NULL; + $this->currentTestMethodPrettified = NULL; + } + } + + /** + * @since Method available since Release 2.3.0 + */ + protected function doEndClass() + { + foreach ($this->tests as $name => $data) { + $this->onTest($name, $data['failure'] == 0); + } + + $this->endClass($this->testClass); + } + + /** + * Handler for 'start run' event. + * + */ + protected function startRun() + { + } + + /** + * Handler for 'start class' event. + * + * @param string $name + */ + protected function startClass($name) + { + } + + /** + * Handler for 'on test' event. + * + * @param string $name + * @param boolean $success + */ + protected function onTest($name, $success = TRUE) + { + } + + /** + * Handler for 'end class' event. + * + * @param string $name + */ + protected function endClass($name) + { + } + + /** + * Handler for 'end run' event. + * + */ + protected function endRun() + { + } +} +?> diff --git a/tests/PHPUnit/Util/TestDox/ResultPrinter/HTML.php b/tests/PHPUnit/Util/TestDox/ResultPrinter/HTML.php new file mode 100755 index 00000000..724941fa --- /dev/null +++ b/tests/PHPUnit/Util/TestDox/ResultPrinter/HTML.php @@ -0,0 +1,128 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.3.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/TestDox/ResultPrinter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Prints TestDox documentation in HTML format. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.1.0 + */ +class PHPUnit_Util_TestDox_ResultPrinter_HTML extends PHPUnit_Util_TestDox_ResultPrinter +{ + /** + * @var boolean + */ + protected $printsHTML = TRUE; + + /** + * Handler for 'start run' event. + * + */ + protected function startRun() + { + $this->write(''); + } + + /** + * Handler for 'start class' event. + * + * @param string $name + */ + protected function startClass($name) + { + $this->write('

' . $this->currentTestClassPrettified . '

    '); + } + + /** + * Handler for 'on test' event. + * + * @param string $name + * @param boolean $success + */ + protected function onTest($name, $success = TRUE) + { + if (!$success) { + $strikeOpen = ''; + $strikeClose = ''; + } else { + $strikeOpen = ''; + $strikeClose = ''; + } + + $this->write('
  • ' . $strikeOpen . $name . $strikeClose . '
  • '); + } + + /** + * Handler for 'end class' event. + * + * @param string $name + */ + protected function endClass($name) + { + $this->write('
'); + } + + /** + * Handler for 'end run' event. + * + */ + protected function endRun() + { + $this->write(''); + } +} +?> diff --git a/tests/PHPUnit/Util/TestDox/ResultPrinter/Text.php b/tests/PHPUnit/Util/TestDox/ResultPrinter/Text.php new file mode 100755 index 00000000..e1a2839b --- /dev/null +++ b/tests/PHPUnit/Util/TestDox/ResultPrinter/Text.php @@ -0,0 +1,103 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 2.3.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; +require_once 'PHPUnit/Util/TestDox/ResultPrinter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Prints TestDox documentation in text format. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 2.1.0 + */ +class PHPUnit_Util_TestDox_ResultPrinter_Text extends PHPUnit_Util_TestDox_ResultPrinter +{ + /** + * Handler for 'start class' event. + * + * @param string $name + */ + protected function startClass($name) + { + $this->write($this->currentTestClassPrettified . "\n"); + } + + /** + * Handler for 'on test' event. + * + * @param string $name + * @param boolean $success + */ + protected function onTest($name, $success = TRUE) + { + if ($success) { + $this->write(' [x] '); + } else { + $this->write(' [ ] '); + } + + $this->write($name . "\n"); + } + + /** + * Handler for 'end class' event. + * + * @param string $name + */ + protected function endClass($name) + { + $this->write("\n"); + } +} +?> diff --git a/tests/PHPUnit/Util/TestSuiteIterator.php b/tests/PHPUnit/Util/TestSuiteIterator.php new file mode 100755 index 00000000..1f4c1f2b --- /dev/null +++ b/tests/PHPUnit/Util/TestSuiteIterator.php @@ -0,0 +1,153 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.1.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Iterator for test suites. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.1.0 + */ +class PHPUnit_Util_TestSuiteIterator implements RecursiveIterator +{ + /** + * @var integer + */ + protected $position; + + /** + * @var PHPUnit_Framework_Test[] + */ + protected $tests; + + /** + * Constructor. + * + * @param PHPUnit_Framework_TestSuite $suite + */ + public function __construct(PHPUnit_Framework_TestSuite $testSuite) + { + $this->tests = $testSuite->tests(); + } + + /** + * Rewinds the Iterator to the first element. + * + */ + public function rewind() + { + $this->position = 0; + } + + /** + * Checks if there is a current element after calls to rewind() or next(). + * + * @return boolean + */ + public function valid() + { + return $this->position < count($this->tests); + } + + /** + * Returns the key of the current element. + * + * @return integer + */ + public function key() + { + return $this->position; + } + + /** + * Returns the current element. + * + * @return PHPUnit_Framework_Test + */ + public function current() + { + return $this->valid() ? $this->tests[$this->position] : NULL; + } + + /** + * Moves forward to next element. + * + */ + public function next() + { + $this->position++; + } + + /** + * Returns the sub iterator for the current element. + * + * @return PHPUnit_Util_TestSuiteIterator + */ + public function getChildren() + { + return new PHPUnit_Util_TestSuiteIterator($this->tests[$this->position]); + } + + /** + * Checks whether the current element has children. + * + * @return boolean + */ + public function hasChildren() + { + return $this->tests[$this->position] instanceof PHPUnit_Framework_TestSuite; + } +} +?> diff --git a/tests/PHPUnit/Util/Timer.php b/tests/PHPUnit/Util/Timer.php new file mode 100755 index 00000000..91480415 --- /dev/null +++ b/tests/PHPUnit/Util/Timer.php @@ -0,0 +1,128 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Utility class for timing. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Util_Timer +{ + protected static $startTimes = array(); + + /** + * Starts the timer. + * + */ + public static function start() + { + array_push(self::$startTimes, microtime(TRUE)); + } + + /** + * Returns the currently elapsed time. + * + * @return float + */ + public static function current() + { + return microtime(TRUE) - self::$startTimes[count(self::$startTimes)-1]; + } + + /** + * Stops the timer and returns the elapsed time. + * + */ + public static function stop() + { + return microtime(TRUE) - array_pop(self::$startTimes); + } + + /** + * Formats elapsed time (in seconds) to a string. + * + * @param float $time + * @return float + */ + public static function secondsToTimeString($time) + { + $buffer = ''; + + $hours = sprintf('%02d', ($time >= 3600) ? floor($time / 3600) : 0); + $minutes = sprintf('%02d', ($time >= 60) ? floor($time / 60) - 60 * $hours : 0); + $seconds = sprintf('%02d', $time - 60 * 60 * $hours - 60 * $minutes); + + if ($hours == 0 && $minutes == 0) { + $seconds = sprintf('%1d', $seconds); + + $buffer .= $seconds . ' second'; + + if ($seconds != '1') { + $buffer .= 's'; + } + } else { + if ($hours > 0) { + $buffer = $hours . ':'; + } + + $buffer .= $minutes . ':' . $seconds; + } + + return $buffer; + } +} +?> diff --git a/tests/PHPUnit/Util/Type.php b/tests/PHPUnit/Util/Type.php new file mode 100755 index 00000000..c13275d4 --- /dev/null +++ b/tests/PHPUnit/Util/Type.php @@ -0,0 +1,197 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.0.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * Utility class for textual type (and value) representation. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.0.0 + */ +class PHPUnit_Util_Type +{ + public static function isType($type) + { + return in_array( + $type, + array( + 'numeric', + 'integer', + 'int', + 'float', + 'string', + 'boolean', + 'bool', + 'null', + 'array', + 'object', + 'resource' + ) + ); + } + + public static function shortenedExport($value) + { + if (is_string($value)) { + return self::shortenedString($value); + } + + elseif (is_array($value)) { + if (count($value) == 0) { + return 'array()'; + } + + $a1 = array_slice($value, 0, 1, TRUE); + $k1 = key($a1); + $v1 = $a1[$k1]; + + if (is_string($v1)) { + $v1 = self::shortenedString($v1); + } + + elseif (is_array($v1)) { + $v1 = 'array(...)'; + } else { + $v1 = self::toString($v1); + } + + $a2 = FALSE; + + if (count($value) > 1) { + $a2 = array_slice($value, -1, 1, TRUE); + $k2 = key($a2); + $v2 = $a2[$k2]; + + if (is_string($v2)) { + $v2 = self::shortenedString($v2); + } + + elseif (is_array($v2)) { + $v2 = 'array(...)'; + } else { + $v2 = self::toString($v2); + } + } + + $text = 'array( ' . self::toString($k1) . ' => ' . $v1; + + if ($a2 !== FALSE) { + $text .= ', ..., ' . self::toString($k2) . ' => ' . $v2 . ' )'; + } else { + $text .= ' )'; + } + + return $text; + } + + elseif (is_object($value)) { + return get_class($value) . '(...)'; + } + + return self::toString($value); + } + + public static function shortenedString($string) + { + $string = preg_replace('#\n|\r\n|\r#', ' ', $string); + + if (strlen($string) > 14) { + return PHPUnit_Util_Type::toString( + substr($string, 0, 7) . '...' . substr($string, -7) + ); + } else { + return PHPUnit_Util_Type::toString($string); + } + } + + public static function toString($value, $short = FALSE) + { + if (is_array($value) || is_object($value)) { + if (!$short) { + return "\n" . print_r($value, TRUE); + } else { + if (is_array($value)) { + return ''; + } else { + return '<' . get_class($value) . '>'; + } + } + } + + if (is_string($value) && strpos($value, "\n") !== FALSE) { + return ''; + } + + if (!is_null($value)) { + $type = gettype($value) . ':'; + } else { + $type = ''; + $value = 'null'; + } + + if (is_bool($value)) { + if ($value === TRUE) { + $value = 'true'; + } + + else if ($value === FALSE) { + $value = 'false'; + } + } + + return '<' . $type . $value . '>'; + } +} +?> diff --git a/tests/PHPUnit/Util/XML.php b/tests/PHPUnit/Util/XML.php new file mode 100755 index 00000000..38540ac8 --- /dev/null +++ b/tests/PHPUnit/Util/XML.php @@ -0,0 +1,784 @@ +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + + * @link http://www.phpunit.de/ + * @since File available since Release 3.2.0 + */ + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +/** + * XML helpers. + * + * @category Testing + * @package PHPUnit + * @author Sebastian Bergmann + * @copyright 2002-2009 Sebastian Bergmann + * @license http://www.opensource.org/licenses/bsd-license.php BSD License + * @version Release: 3.3.17 + * @link http://www.phpunit.de/ + * @since Class available since Release 3.2.0 + */ +class PHPUnit_Util_XML +{ + /** + * Converts a string to UTF-8 encoding. + * + * @param string $string + * @return string + * @since Method available since Release 3.2.19 + */ + public static function convertToUtf8($string) + { + if (!self::isUtf8($string)) { + if (function_exists('mb_convert_encoding')) { + $string = mb_convert_encoding($string, 'UTF-8'); + } else { + $string = utf8_encode($string); + } + } + + return $string; + } + + /** + * Checks a string for UTF-8 encoding. + * + * @param string $string + * @return boolean + * @since Method available since Release 3.3.0 + */ + public static function isUtf8($string) + { + $length = strlen($string); + + for ($i = 0; $i < $length; $i++) { + if (ord($string[$i]) < 0x80) $n = 0; + elseif ((ord($string[$i]) & 0xE0) == 0xC0) $n = 1; + elseif ((ord($string[$i]) & 0xF0) == 0xE0) $n = 2; + elseif ((ord($string[$i]) & 0xF0) == 0xF0) $n = 3; + else return FALSE; + + for ($j = 0; $j < $n; $j++) { + if ((++$i == $length) || ((ord($string[$i]) & 0xC0) != 0x80)) return FALSE; + } + } + + return TRUE; + } + + /** + * Loads an XML (or HTML) file into a DOMDocument object. + * + * @param string $filename + * @param boolean $isHtml + * @return DOMDocument + * @since Method available since Release 3.3.0 + */ + public static function loadFile($filename, $isHtml = FALSE) + { + $reporting = error_reporting(0); + $contents = file_get_contents($filename); + error_reporting($reporting); + + if ($contents === FALSE) { + throw new RuntimeException( + sprintf( + 'Could not read "%s".', + $filename + ) + ); + } + + return self::load($contents, $isHtml, $filename); + } + + /** + * Load an $actual document into a DOMDocument. This is called + * from the selector assertions. + * + * If $actual is already a DOMDocument, it is returned with + * no changes. Otherwise, $actual is loaded into a new DOMDocument + * as either HTML or XML, depending on the value of $isHtml. + * + * Note: prior to PHPUnit 3.3.0, this method loaded a file and + * not a string as it currently does. To load a file into a + * DOMDocument, use loadFile() instead. + * + * @param string|DOMDocument $actual + * @param boolean $isHtml + * @param string $filename + * @return DOMDocument + * @since Method available since Release 3.3.0 + * @author Mike Naberezny + * @author Derek DeVries + */ + public static function load($actual, $isHtml = FALSE, $filename = '') + { + if ($actual instanceof DOMDocument) { + return $actual; + } + + $internal = libxml_use_internal_errors(TRUE); + $reporting = error_reporting(0); + $dom = new DOMDocument; + + if ($isHtml) { + $loaded = $dom->loadHTML($actual); + } else { + $loaded = $dom->loadXML($actual); + } + + libxml_use_internal_errors($internal); + error_reporting($reporting); + + if ($loaded === FALSE) { + $message = ''; + + foreach (libxml_get_errors() as $error) { + $message .= $error->message; + } + + if ($filename != '') { + throw new RuntimeException( + sprintf( + 'Could not load "%s".%s', + + $filename, + $message != '' ? "\n" . $message : '' + ) + ); + } else { + throw new RuntimeException($message); + } + } + + return $dom; + } + + /** + * + * + * @param DOMNode $node + * @since Method available since Release 3.3.0 + * @author Mattis Stordalen Flister + */ + public static function removeCharacterDataNodes(DOMNode $node) + { + if ($node->hasChildNodes()) { + for ($i = $node->childNodes->length - 1; $i >= 0; $i--) { + if (($child = $node->childNodes->item($i)) instanceof DOMCharacterData) { + $node->removeChild($child); + } + } + } + } + + /** + * Validate list of keys in the associative array. + * + * @param array $hash + * @param array $validKeys + * @return array + * @throws InvalidArgumentException + * @since Method available since Release 3.3.0 + * @author Mike Naberezny + * @author Derek DeVries + */ + public static function assertValidKeys(array $hash, array $validKeys) + { + $valids = array(); + + // Normalize validation keys so that we can use both indexed and + // associative arrays. + foreach ($validKeys as $key => $val) { + is_int($key) ? $valids[$val] = NULL : $valids[$key] = $val; + } + + $validKeys = array_keys($valids); + + // Check for invalid keys. + foreach ($hash as $key => $value) { + if (!in_array($key, $validKeys)) { + $unknown[] = $key; + } + } + + if (!empty($unknown)) { + throw new InvalidArgumentException( + 'Unknown key(s): ' . implode(', ', $unknown) + ); + } + + // Add default values for any valid keys that are empty. + foreach ($valids as $key => $value) { + if (!isset($hash[$key])) { + $hash[$key] = $value; + } + } + + return $hash; + } + + /** + * Parse a CSS selector into an associative array suitable for + * use with findNodes(). + * + * @param string $selector + * @param mixed $content + * @return array + * @since Method available since Release 3.3.0 + * @author Mike Naberezny + * @author Derek DeVries + */ + public static function convertSelectToTag($selector, $content = TRUE) + { + $selector = trim(preg_replace("/\s+/", " ", $selector)); + + // substitute spaces within attribute value + while (preg_match('/\[[^\]]+"[^"]+\s[^"]+"\]/', $selector)) { + $selector = preg_replace('/(\[[^\]]+"[^"]+)\s([^"]+"\])/', "$1__SPACE__$2", $selector); + } + + $elements = strstr($selector, ' ') ? explode(' ', $selector) : array($selector); + $previousTag = array(); + + foreach (array_reverse($elements) as $element) { + $element = str_replace('__SPACE__', ' ', $element); + + // child selector + if ($element == '>') { + $previousTag = array('child' => $previousTag['descendant']); + continue; + } + + $tag = array(); + + // match element tag + preg_match("/^([^\.#\[]*)/", $element, $eltMatches); + + if (!empty($eltMatches[1])) { + $tag['tag'] = $eltMatches[1]; + } + + // match attributes (\[[^\]]*\]*), ids (#[^\.#\[]*), and classes (\.[^\.#\[]*)) + preg_match_all("/(\[[^\]]*\]*|#[^\.#\[]*|\.[^\.#\[]*)/", $element, $matches); + + if (!empty($matches[1])) { + $classes = array(); + $attrs = array(); + + foreach ($matches[1] as $match) { + // id matched + if (substr($match, 0, 1) == '#') { + $tag['id'] = substr($match, 1); + } + + // class matched + else if (substr($match, 0, 1) == '.') { + $classes[] = substr($match, 1); + } + + // attribute matched + else if (substr($match, 0, 1) == '[' && substr($match, -1, 1) == ']') { + $attribute = substr($match, 1, strlen($match) - 2); + $attribute = str_replace('"', '', $attribute); + + // match single word + if (strstr($attribute, '~=')) { + list($key, $value) = explode('~=', $attribute); + $value = "regexp:/.*\b$value\b.*/"; + } + + // match substring + else if (strstr($attribute, '*=')) { + list($key, $value) = explode('*=', $attribute); + $value = "regexp:/.*$value.*/"; + } + + // exact match + else { + list($key, $value) = explode('=', $attribute); + } + + $attrs[$key] = $value; + } + } + + if ($classes) { + $tag['class'] = join(' ', $classes); + } + + if ($attrs) { + $tag['attributes'] = $attrs; + } + } + + // tag content + if (is_string($content)) { + $tag['content'] = $content; + } + + // determine previous child/descendants + if (!empty($previousTag['descendant'])) { + $tag['descendant'] = $previousTag['descendant']; + } + + else if (!empty($previousTag['child'])) { + $tag['child'] = $previousTag['child']; + } + + $previousTag = array('descendant' => $tag); + } + + return $tag; + } + + /** + * Parse an $actual document and return an array of DOMNodes + * matching the CSS $selector. If an error occurs, it will + * return FALSE. + * + * To only return nodes containing a certain content, give + * the $content to match as a string. Otherwise, setting + * $content to TRUE will return all nodes matching $selector. + * + * The $actual document may be a DOMDocument or a string + * containing XML or HTML, identified by $isHtml. + * + * @param array $selector + * @param string $content + * @param mixed $actual + * @param boolean $isHtml + * @return false|array + * @since Method available since Release 3.3.0 + * @author Mike Naberezny + * @author Derek DeVries + */ + public static function cssSelect($selector, $content, $actual, $isHtml = TRUE) + { + $matcher = self::convertSelectToTag($selector, $content); + $dom = self::load($actual, $isHtml); + $tags = self::findNodes($dom, $matcher); + + return $tags; + } + + /** + * Parse out the options from the tag using DOM object tree. + * + * @param DOMDocument $dom + * @param array $options + * @return array + * @since Method available since Release 3.3.0 + * @author Mike Naberezny + * @author Derek DeVries + */ + public static function findNodes(DOMDocument $dom, array $options) + { + $valid = array( + 'id', 'class', 'tag', 'content', 'attributes', 'parent', + 'child', 'ancestor', 'descendant', 'children' + ); + + $filtered = array(); + $options = self::assertValidKeys($options, $valid); + + // find the element by id + if ($options['id']) { + $options['attributes']['id'] = $options['id']; + } + + if ($options['class']) { + $options['attributes']['class'] = $options['class']; + } + + // find the element by a tag type + if ($options['tag']) { + $elements = $dom->getElementsByTagName($options['tag']); + + foreach ($elements as $element) { + $nodes[] = $element; + } + + if (empty($nodes)) { + return FALSE; + } + + // no tag selected, get them all + } else { + $tags = array( + 'a', 'abbr', 'acronym', 'address', 'area', 'b', 'base', 'bdo', + 'big', 'blockquote', 'body', 'br', 'button', 'caption', 'cite', + 'code', 'col', 'colgroup', 'dd', 'del', 'div', 'dfn', 'dl', + 'dt', 'em', 'fieldset', 'form', 'frame', 'frameset', 'h1', 'h2', + 'h3', 'h4', 'h5', 'h6', 'head', 'hr', 'html', 'i', 'iframe', + 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'link', + 'map', 'meta', 'noframes', 'noscript', 'object', 'ol', 'optgroup', + 'option', 'p', 'param', 'pre', 'q', 'samp', 'script', 'select', + 'small', 'span', 'strong', 'style', 'sub', 'sup', 'table', + 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'title', + 'tr', 'tt', 'ul', 'var' + ); + + foreach ($tags as $tag) { + $elements = $dom->getElementsByTagName($tag); + + foreach ($elements as $element) { + $nodes[] = $element; + } + } + + if (empty($nodes)) { + return FALSE; + } + } + + // filter by attributes + if ($options['attributes']) { + foreach ($nodes as $node) { + $invalid = FALSE; + + foreach ($options['attributes'] as $name => $value) { + // match by regexp if like "regexp:/foo/i" + if (preg_match('/^regexp\s*:\s*(.*)/i', $value, $matches)) { + if (!preg_match($matches[1], $node->getAttribute($name))) { + $invalid = TRUE; + } + } + + // class can match only a part + else if ($name == 'class') { + // split to individual classes + $findClasses = explode(' ', preg_replace("/\s+/", " ", $value)); + $allClasses = explode(' ', preg_replace("/\s+/", " ", $node->getAttribute($name))); + + // make sure each class given is in the actual node + foreach ($findClasses as $findClass) { + if (!in_array($findClass, $allClasses)) { + $invalid = TRUE; + } + } + } + + // match by exact string + else { + if ($node->getAttribute($name) != $value) { + $invalid = TRUE; + } + } + } + + // if every attribute given matched + if (!$invalid) { + $filtered[] = $node; + } + } + + $nodes = $filtered; + $filtered = array(); + + if (empty($nodes)) { + return FALSE; + } + } + + // filter by content + if ($options['content'] !== NULL) { + foreach ($nodes as $node) { + $invalid = FALSE; + + // match by regexp if like "regexp:/foo/i" + if (preg_match('/^regexp\s*:\s*(.*)/i', $options['content'], $matches)) { + if (!preg_match($matches[1], self::getNodeText($node))) { + $invalid = TRUE; + } + } + + // match by exact string + else if (strstr(self::getNodeText($node), $options['content']) === FALSE) { + $invalid = TRUE; + } + + if (!$invalid) { + $filtered[] = $node; + } + } + + $nodes = $filtered; + $filtered = array(); + + if (empty($nodes)) { + return FALSE; + } + } + + // filter by parent node + if ($options['parent']) { + $parentNodes = self::findNodes($dom, $options['parent']); + $parentNode = isset($parentNodes[0]) ? $parentNodes[0] : NULL; + + foreach ($nodes as $node) { + if ($parentNode !== $node->parentNode) { + break; + } + + $filtered[] = $node; + } + + $nodes = $filtered; + $filtered = array(); + + if (empty($nodes)) { + return FALSE; + } + } + + // filter by child node + if ($options['child']) { + $childNodes = self::findNodes($dom, $options['child']); + $childNodes = !empty($childNodes) ? $childNodes : array(); + + foreach ($nodes as $node) { + foreach ($node->childNodes as $child) { + foreach ($childNodes as $childNode) { + if ($childNode === $child) { + $filtered[] = $node; + } + } + } + } + + $nodes = $filtered; + $filtered = array(); + + if (empty($nodes)) { + return FALSE; + } + } + + // filter by ancestor + if ($options['ancestor']) { + $ancestorNodes = self::findNodes($dom, $options['ancestor']); + $ancestorNode = isset($ancestorNodes[0]) ? $ancestorNodes[0] : NULL; + + foreach ($nodes as $node) { + $parent = $node->parentNode; + + while ($parent->nodeType != XML_HTML_DOCUMENT_NODE) { + if ($parent === $ancestorNode) { + $filtered[] = $node; + } + + $parent = $parent->parentNode; + } + } + + $nodes = $filtered; + $filtered = array(); + + if (empty($nodes)) { + return FALSE; + } + } + + // filter by descendant + if ($options['descendant']) { + $descendantNodes = self::findNodes($dom, $options['descendant']); + $descendantNodes = !empty($descendantNodes) ? $descendantNodes : array(); + + foreach ($nodes as $node) { + foreach (self::getDescendants($node) as $descendant) { + foreach ($descendantNodes as $descendantNode) { + if ($descendantNode === $descendant) { + $filtered[] = $node; + } + } + } + } + + $nodes = $filtered; + $filtered = array(); + + if (empty($nodes)) { + return FALSE; + } + } + + // filter by children + if ($options['children']) { + $validChild = array('count', 'greater_than', 'less_than', 'only'); + $childOptions = self::assertValidKeys($options['children'], $validChild); + + foreach ($nodes as $node) { + $childNodes = $node->childNodes; + + foreach ($childNodes as $childNode) { + if ($childNode->nodeType !== XML_CDATA_SECTION_NODE && + $childNode->nodeType !== XML_TEXT_NODE) { + $children[] = $childNode; + } + } + + // we must have children to pass this filter + if (!empty($children)) { + // exact count of children + if ($childOptions['count'] !== NULL) { + if (count($children) !== $childOptions['count']) { + break; + } + } + + // range count of children + else if ($childOptions['less_than'] !== NULL && + $childOptions['greater_than'] !== NULL) { + if (count($children) >= $childOptions['less_than'] || + count($children) <= $childOptions['greater_than']) { + break; + } + } + + // less than a given count + else if ($childOptions['less_than'] !== NULL) { + if (count($children) >= $childOptions['less_than']) { + break; + } + } + + // more than a given count + else if ($childOptions['greater_than'] !== NULL) { + if (count($children) <= $childOptions['greater_than']) { + break; + } + } + + // match each child against a specific tag + if ($childOptions['only']) { + $onlyNodes = self::findNodes($dom, $childOptions['only']); + + // try to match each child to one of the 'only' nodes + foreach ($children as $child) { + $matched = FALSE; + + foreach ($onlyNodes as $onlyNode) { + if ($onlyNode === $child) { + $matched = TRUE; + } + } + + if (!$matched) { + break(2); + } + } + } + + $filtered[] = $node; + } + } + + $nodes = $filtered; + $filtered = array(); + + if (empty($nodes)) { + return; + } + } + + // return the first node that matches all criteria + return !empty($nodes) ? $nodes : array(); + } + + /** + * Recursively get flat array of all descendants of this node. + * + * @param DOMNode $node + * @return array + * @since Method available since Release 3.3.0 + * @author Mike Naberezny + * @author Derek DeVries + */ + protected static function getDescendants(DOMNode $node) + { + $allChildren = array(); + $childNodes = $node->childNodes ? $node->childNodes : array(); + + foreach ($childNodes as $child) { + if ($child->nodeType === XML_CDATA_SECTION_NODE || + $child->nodeType === XML_TEXT_NODE) { + continue; + } + + $children = self::getDescendants($child); + $allChildren = array_merge($allChildren, $children, array($child)); + } + + return isset($allChildren) ? $allChildren : array(); + } + + /** + * Get the text value of this node's child text node. + * + * @param DOMNode $node + * @return string + * @since Method available since Release 3.3.0 + * @author Mike Naberezny + * @author Derek DeVries + */ + protected static function getNodeText(DOMNode $node) + { + $childNodes = $node->childNodes instanceof DOMNodeList ? $node->childNodes : array(); + $text = ''; + + foreach ($childNodes as $child) { + if ($child->nodeType === XML_TEXT_NODE) { + $text .= trim($child->data).' '; + } else { + $text .= self::getNodeText($child); + } + } + + return str_replace(' ', ' ', $text); + } +} +?> diff --git a/tests/SugarTestAccountUtilities.php b/tests/SugarTestAccountUtilities.php new file mode 100755 index 00000000..395de248 --- /dev/null +++ b/tests/SugarTestAccountUtilities.php @@ -0,0 +1,51 @@ +name = $name . $time; + $account->email1 = 'account@'. $time. 'sugar.com'; + if(!empty($id)) + { + $account->new_with_id = true; + $account->id = $id; + } + $account->save(); + self::$_createdAccounts[] = $account; + return $account; + } + + public static function setCreatedAccount($account_ids) { + foreach($account_ids as $account_id) { + $account = new Account(); + $account->id = $account_id; + self::$_createdAccounts[] = $account; + } // foreach + } // fn + + public static function removeAllCreatedAccounts() + { + $account_ids = self::getCreatedAccountIds(); + $GLOBALS['db']->query('DELETE FROM accounts WHERE id IN (\'' . implode("', '", $account_ids) . '\')'); + } + + public static function getCreatedAccountIds() + { + $account_ids = array(); + foreach (self::$_createdAccounts as $account) { + $account_ids[] = $account->id; + } + return $account_ids; + } +} +?> \ No newline at end of file diff --git a/tests/SugarTestCampaignUtilities.php b/tests/SugarTestCampaignUtilities.php new file mode 100755 index 00000000..78c28308 --- /dev/null +++ b/tests/SugarTestCampaignUtilities.php @@ -0,0 +1,44 @@ +name = $name . $time; + $campaign->status = 'Active'; + $campaign->campaign_type = 'Email'; + $campaign->end_date = '2010-11-08'; + if(!empty($id)) + { + $campaign->new_with_id = true; + $campaign->id = $id; + } + $campaign->save(); + self::$_createdCampaigns[] = $campaign; + return $campaign; + } + + public static function removeAllCreatedCampaigns() + { + $campaign_ids = self::getCreatedCampaignIds(); + $GLOBALS['db']->query('DELETE FROM campaigns WHERE id IN (\'' . implode("', '", $campaign_ids) . '\')'); + } + + public static function getCreatedCampaignIds() + { + $campaign_ids = array(); + foreach (self::$_createdCampaigns as $campaign) { + $campaign_ids[] = $campaign->id; + } + return $campaign_ids; + } +} +?> \ No newline at end of file diff --git a/tests/SugarTestContactUtilities.php b/tests/SugarTestContactUtilities.php new file mode 100755 index 00000000..b8874faa --- /dev/null +++ b/tests/SugarTestContactUtilities.php @@ -0,0 +1,58 @@ +first_name = $first_name . $time; + $contact->last_name = $last_name ; + $contact->email1 = 'contact@'. $time. 'sugar.com'; + if(!empty($id)) + { + $contact->new_with_id = true; + $contact->id = $id; + } + $contact->save(); + self::$_createdContacts[] = $contact; + return $contact; + } + + public static function setCreatedContact($contact_ids) { + foreach($contact_ids as $contact_id) { + $contact = new Contact(); + $contact->id = $contact_id; + self::$_createdContacts[] = $contact; + } // foreach + } // fn + + public static function removeAllCreatedContacts() + { + $contact_ids = self::getCreatedContactIds(); + $GLOBALS['db']->query('DELETE FROM contacts WHERE id IN (\'' . implode("', '", $contact_ids) . '\')'); + } + + public static function removeCreatedContactsUsersRelationships(){ + $contact_ids = self::getCreatedContactIds(); + $GLOBALS['db']->query('DELETE FROM contacts_users WHERE contact_id IN (\'' . implode("', '", $contact_ids) . '\')'); + } + + public static function getCreatedContactIds() + { + $contact_ids = array(); + foreach (self::$_createdContacts as $contact) { + $contact_ids[] = $contact->id; + } + return $contact_ids; + } +} +?> \ No newline at end of file diff --git a/tests/SugarTestEmailUtilities.php b/tests/SugarTestEmailUtilities.php new file mode 100755 index 00000000..3ff00462 --- /dev/null +++ b/tests/SugarTestEmailUtilities.php @@ -0,0 +1,67 @@ +name = $name . $time; + $email->type = 'out'; + $email->status = 'sent'; + $email->date_sent = $timedate->to_display_date_time(gmdate("Y-m-d H:i:s", (gmmktime() - (3600 * 24 * 2) ))) ; // Two days ago + if(!empty($id)) + { + $email->new_with_id = true; + $email->id = $id; + } + foreach($override as $key => $value) + { + $email->$key = $value; + } + $email->save(); + if(!empty($override['parent_id']) && !empty($override['parent_type'])) + { + self::createEmailsBeansRelationship($email->id, $override['parent_type'], $override['parent_id']); + } + self::$_createdEmails[] = $email; + return $email; + } + + public static function removeAllCreatedEmails() + { + $email_ids = self::getCreatedEmailIds(); + $GLOBALS['db']->query('DELETE FROM emails WHERE id IN (\'' . implode("', '", $email_ids) . '\')'); + self::removeCreatedEmailBeansRelationships(); + } + + private static function createEmailsBeansRelationship($email_id, $parent_type, $parent_id) + { + $unique_id = create_guid(); + $GLOBALS['db']->query("INSERT INTO emails_beans SET id = '{$unique_id}', email_id = '{$email_id}', bean_id = '{$parent_id}', ". + "bean_module = '{$parent_type}', date_modified = '".gmdate('Y-m-d H:i:s')."', deleted = 0"); + } + + private static function removeCreatedEmailBeansRelationships(){ + $email_ids = self::getCreatedEmailIds(); + $GLOBALS['db']->query('DELETE FROM emails_beans WHERE email_id IN (\'' . implode("', '", $email_ids) . '\')'); + } + + public static function getCreatedEmailIds() + { + $email_ids = array(); + foreach (self::$_createdEmails as $email) { + $email_ids[] = $email->id; + } + return $email_ids; + } +} +?> \ No newline at end of file diff --git a/tests/SugarTestHelper.php b/tests/SugarTestHelper.php new file mode 100755 index 00000000..5b480ab5 --- /dev/null +++ b/tests/SugarTestHelper.php @@ -0,0 +1,103 @@ + 02770, + 'file_mode' => 0777, + 'chown' => '', + 'chgrp' => '', + ); + +$GLOBALS['js_version_key'] = 'testrunner'; + +if ( !isset($_SERVER['SERVER_SOFTWARE']) ) + $_SERVER["SERVER_SOFTWARE"] = 'PHPUnit'; + +// helps silence the license checking when running unit tests. +$_SESSION['VALIDATION_EXPIRES_IN'] = 'valid'; + +$GLOBALS['startTime'] = microtime(true); + +// clean out the cache directory +require_once('modules/Administration/QuickRepairAndRebuild.php'); +$repair = new RepairAndClear(); +$repair->module_list = array(); +$repair->show_output = false; +$repair->clearJsLangFiles(); +$repair->clearJsFiles(); + +// mark that we got by the admin wizard already +$focus = new Administration(); +$focus->retrieveSettings(); +$focus->saveSetting('system','adminwizard',1); + +// include the other test tools +require_once 'SugarTestUserUtilities.php'; +require_once 'SugarTestLangPackCreator.php'; +require_once 'SugarTestThemeUtilities.php'; +require_once 'SugarTestContactUtilities.php'; +require_once 'SugarTestEmailUtilities.php'; +require_once 'SugarTestCampaignUtilities.php'; +require_once 'SugarTestLeadUtilities.php'; +require_once 'SugarTestStudioUtilities.php'; +require_once 'SugarTestMeetingUtilities.php'; +require_once 'SugarTestAccountUtilities.php'; +require_once 'SugarTestTrackerUtility.php'; +require_once 'SugarTestImportUtilities.php'; +require_once 'SugarTestMergeUtilities.php'; + +// define our testcase subclass +class Sugar_PHPUnit_Framework_TestCase extends PHPUnit_Framework_TestCase +{ + protected $backupGlobals = FALSE; +} + +// define a mock logger interface; used for capturing logging messages emited +// the test suite +class SugarMockLogger +{ + private $_messages = array(); + + public function __call($method, $message) + { + $this->messages[] = strtoupper($method) . ': ' . $message[0]; + } + + public function getLastMessage() + { + return end($this->messages); + } + + public function getMessageCount() + { + return count($this->messages); + } +} diff --git a/tests/SugarTestImportUtilities.php b/tests/SugarTestImportUtilities.php new file mode 100755 index 00000000..cdb524ac --- /dev/null +++ b/tests/SugarTestImportUtilities.php @@ -0,0 +1,62 @@ +clearLangCache(); + } + + /** + * Set a string for the app_strings array + * + * @param $key string + * @param $value string + */ + public function setAppString( + $key, + $value + ) + { + $this->_strings['app_strings'][$key] = $value; + } + + /** + * Set a string for the app_list_strings array + * + * @param $key string + * @param $value string + */ + public function setAppListString( + $key, + $value + ) + { + $this->_strings['app_list_strings'][$key] = $value; + } + + /** + * Set a string for the mod_strings array + * + * @param $key string + * @param $value string + * @param $module string + */ + public function setModString( + $key, + $value, + $module + ) + { + $this->_strings['mod_strings'][$module][$key] = $value; + } + + /** + * Saves the created strings + * + * Here, we cheat the system by storing our string overrides in the sugar_cache where + * we normally stored the cached language strings. + */ + public function save() + { + $language = $GLOBALS['current_language']; + if ( isset($this->_strings['app_strings']) ) { + $cache_key = 'app_strings.'.$language; + $app_strings = sugar_cache_retrieve($cache_key); + if ( empty($app_strings) ) + $app_strings = return_application_language($language); + foreach ( $this->_strings['app_strings'] as $key => $value ) + $app_strings[$key] = $value; + sugar_cache_put($cache_key, $app_strings); + $GLOBALS['app_strings'] = $app_strings; + } + + if ( isset($this->_strings['app_list_strings']) ) { + $cache_key = 'app_list_strings.'.$language; + $app_list_strings = sugar_cache_retrieve($cache_key); + if ( empty($app_list_strings) ) + $app_list_strings = return_app_list_strings_language($language); + foreach ( $this->_strings['app_list_strings'] as $key => $value ) + $app_list_strings[$key] = $value; + sugar_cache_put($cache_key, $app_list_strings); + $GLOBALS['app_list_strings'] = $app_list_strings; + } + + if ( isset($this->_strings['mod_strings']) ) { + foreach ( $this->_strings['mod_strings'] as $module => $strings ) { + $cache_key = "LanguageManager.$module.$language"; + $mod_strings = sugar_cache_retrieve($cache_key); + if ( empty($mod_strings) ) + $mod_strings = return_module_language($language, $module); + foreach ( $strings as $key => $value ) + $mod_strings[$key] = $value; + sugar_cache_put($cache_key, $mod_strings); + } + } + } + + /** + * Clear the language string cache in sugar_cache, which will get rid of our + * language file overrides. + */ + protected function clearLangCache() + { + $language = $GLOBALS['current_language']; + + if ( isset($this->_strings['app_strings']) ) { + $cache_key = 'app_strings.'.$language; + sugar_cache_clear($cache_key); + } + + if ( isset($this->_strings['app_list_strings']) ) { + $cache_key = 'app_list_strings.'.$language; + sugar_cache_clear($cache_key); + } + + if ( isset($this->_strings['mod_strings']) ) { + foreach ( $this->_strings['mod_strings'] as $module => $strings ) { + $cache_key = "LanguageManager.$module.$language"; + sugar_cache_clear($cache_key); + } + } + } +} diff --git a/tests/SugarTestLeadUtilities.php b/tests/SugarTestLeadUtilities.php new file mode 100755 index 00000000..d7aae0d6 --- /dev/null +++ b/tests/SugarTestLeadUtilities.php @@ -0,0 +1,58 @@ +first_name = $first_name . $time; + $lead->last_name = $last_name ; + $lead->email1 = 'lead@'. $time. 'sugar.com'; + if(!empty($id)) + { + $lead->new_with_id = true; + $lead->id = $id; + } + $lead->save(); + self::$_createdLeads[] = $lead; + return $lead; + } + + public static function setCreatedLead($lead_ids) { + foreach($lead_ids as $lead_id) { + $lead = new Lead(); + $lead->id = $lead_id; + self::$_createdLeads[] = $lead; + } // foreach + } // fn + + public static function removeAllCreatedLeads() + { + $lead_ids = self::getCreatedLeadIds(); + $GLOBALS['db']->query('DELETE FROM leads WHERE id IN (\'' . implode("', '", $lead_ids) . '\')'); + } + + public static function removeCreatedLeadsUsersRelationships(){ + $lead_ids = self::getCreatedLeadIds(); + $GLOBALS['db']->query('DELETE FROM leads_users WHERE lead_id IN (\'' . implode("', '", $lead_ids) . '\')'); + } + + public static function getCreatedLeadIds() + { + $lead_ids = array(); + foreach (self::$_createdLeads as $lead) { + $lead_ids[] = $lead->id; + } + return $lead_ids; + } +} +?> \ No newline at end of file diff --git a/tests/SugarTestMeetingUtilities.php b/tests/SugarTestMeetingUtilities.php new file mode 100755 index 00000000..465da429 --- /dev/null +++ b/tests/SugarTestMeetingUtilities.php @@ -0,0 +1,46 @@ +name = $name . $time; + if(!empty($id)) + { + $meeting->new_with_id = true; + $meeting->id = $id; + } + $meeting->save(); + self::$_createdMeetings[] = $meeting; + return $meeting; + } + + public static function removeAllCreatedMeetings() + { + $meeting_ids = self::getCreatedMeetingIds(); + $GLOBALS['db']->query('DELETE FROM meetings WHERE id IN (\'' . implode("', '", $meeting_ids) . '\')'); + } + + public static function removeMeetingContacts(){ + $meeting_ids = self::getCreatedMeetingIds(); + $GLOBALS['db']->query('DELETE FROM meetings_contacts WHERE meeting_id IN (\'' . implode("', '", $meeting_ids) . '\')'); + } + + public static function getCreatedMeetingIds() + { + $meeting_ids = array(); + foreach (self::$_createdMeetings as $meeting) { + $meeting_ids[] = $meeting->id; + } + return $meeting_ids; + } +} +?> \ No newline at end of file diff --git a/tests/SugarTestMergeUtilities.php b/tests/SugarTestMergeUtilities.php new file mode 100755 index 00000000..421e37c7 --- /dev/null +++ b/tests/SugarTestMergeUtilities.php @@ -0,0 +1,68 @@ +addField(array('name' => $field_name)); + //$parser->writeWorkingFile(); + $parser->handleSave(false); + unset($parser); + + self::$_fieldsAdded[$module_name][$view][$field_name] = $field_name; + } + + public static function removeAllCreatedFields() + { + foreach(self::$_fieldsAdded as $module_name => $views) + { + foreach($views as $view => $fields) + { + $parser = ParserFactory::getParser($view, $module_name); + foreach($fields as $field_name) + { + $parser->removeField($field_name); + } + $parser->handleSave(false); + unset($parser); + } + } + } + +} +?> \ No newline at end of file diff --git a/tests/SugarTestThemeUtilities.php b/tests/SugarTestThemeUtilities.php new file mode 100755 index 00000000..3bdeb02d --- /dev/null +++ b/tests/SugarTestThemeUtilities.php @@ -0,0 +1,158 @@ + '$themename',"; + $themedef .= "'dirName' => '$themename',"; + $themedef .= "'description' => '$themename',"; + $themedef .= "'version' => array('regex_matches' => array('.*')),"; + $themedef .= ");"; + sugar_file_put_contents("themes/$themename/themedef.php",$themedef); + + self::$_createdThemes[] = $themename; + + SugarThemeRegistry::buildRegistry(); + + return $themename; + } + + public static function createAnonymousOldTheme() + { + $themename = 'TestTheme'.mt_rand(); + + sugar_mkdir("themes/$themename/images",null,true); + sugar_mkdir("themes/$themename/css",null,true); + sugar_mkdir("themes/$themename/js",null,true); + sugar_mkdir("themes/$themename/tpls",null,true); + + sugar_file_put_contents("themes/$themename/css/style.css","h2 { display: inline; }"); + sugar_file_put_contents("themes/$themename/css/yui.css",".yui { display: inline; }"); + sugar_file_put_contents("themes/$themename/js/style.js",'var dog = "cat";'); + sugar_touch("themes/$themename/images/Accounts.gif"); + sugar_touch("themes/$themename/images/fonts.big.icon.gif"); + sugar_touch("themes/$themename/tpls/header.tpl"); + + $themedef = " '$themename',"; + $themedef .= "'dirName' => '$themename',"; + $themedef .= "'description' => '$themename',"; + $themedef .= "'version' => array('regex_matches' => array('5.5.1')),"; + $themedef .= ");"; + sugar_file_put_contents("themes/$themename/themedef.php",$themedef); + + self::$_createdThemes[] = $themename; + + SugarThemeRegistry::buildRegistry(); + + return $themename; + } + + public static function createAnonymousCustomTheme( + $themename = '' + ) + { + if ( empty($themename) ) + $themename = 'TestThemeCustom'.mt_rand(); + + create_custom_directory("themes/$themename/images/"); + create_custom_directory("themes/$themename/css/"); + create_custom_directory("themes/$themename/js/"); + + sugar_touch("custom/themes/$themename/css/style.css"); + sugar_touch("custom/themes/$themename/js/style.js"); + sugar_touch("custom/themes/$themename/images/Accounts.gif"); + sugar_touch("custom/themes/$themename/images/fonts.big.icon.gif"); + + $themedef = " 'custom $themename',"; + $themedef .= "'dirName' => '$themename',"; + $themedef .= "'description' => 'custom $themename',"; + $themedef .= "'version' => array('regex_matches' => array('.*')),"; + $themedef .= ");"; + sugar_file_put_contents("custom/themes/$themename/themedef.php",$themedef); + + self::$_createdThemes[] = $themename; + + SugarThemeRegistry::buildRegistry(); + + return $themename; + } + + public static function createAnonymousChildTheme( + $parentTheme + ) + { + $themename = 'TestThemeChild'.mt_rand(); + + sugar_mkdir("themes/$themename/images",null,true); + sugar_mkdir("themes/$themename/css",null,true); + sugar_mkdir("themes/$themename/js",null,true); + + sugar_file_put_contents("themes/$themename/css/style.css","h3 { display: inline; }"); + sugar_file_put_contents("themes/$themename/css/yui.css",".yui { display: inline; }"); + sugar_file_put_contents("themes/$themename/js/style.js",'var bird = "frog";'); + + $themedef = " '$themename',"; + $themedef .= "'dirName' => '$themename',"; + $themedef .= "'parentTheme' => '".$parentTheme."',"; + $themedef .= "'description' => '$themename',"; + $themedef .= "'version' => array('regex_matches' => array('.*')),"; + $themedef .= ");"; + sugar_file_put_contents("themes/$themename/themedef.php",$themedef); + + self::$_createdThemes[] = $themename; + + SugarThemeRegistry::buildRegistry(); + + return $themename; + } + + public static function removeAllCreatedAnonymousThemes() + { + foreach (self::getCreatedThemeNames() as $name ) { + if ( is_dir('themes/'.$name) ) + rmdir_recursive('themes/'.$name); + if ( is_dir('custom/themes/'.$name) ) + rmdir_recursive('custom/themes/'.$name); + if ( is_dir('cache/themes/'.$name) ) + rmdir_recursive('cache/themes/'.$name); + } + + SugarThemeRegistry::buildRegistry(); + } + + public static function getCreatedThemeNames() + { + return self::$_createdThemes; + } +} + diff --git a/tests/SugarTestTrackerUtility.php b/tests/SugarTestTrackerUtility.php new file mode 100755 index 00000000..58312f4a --- /dev/null +++ b/tests/SugarTestTrackerUtility.php @@ -0,0 +1,77 @@ +query("SELECT category, name, value from config WHERE category = 'tracker' and name != 'prune_interval'"); + while($row = $GLOBALS['db']->fetchByAssoc($result)){ + self::$_trackerSettings[$row['name']] = $row['value']; + $GLOBALS['db']->query("DELETE FROM config WHERE category = 'tracker' AND name = '{$row['name']}'"); + } + } + + public static function restore() + { + foreach(self::$_trackerSettings as $name=>$value) { + $GLOBALS['db']->query("INSERT INTO config (category, name, value) VALUES ('tracker', '{$name}', '{$value}')"); + } + } + + public static function insertTrackerEntry($bean, $action) + { + require_once('modules/Trackers/TrackerManager.php'); + $trackerManager = TrackerManager::getInstance(); + $timeStamp = gmdate($GLOBALS['timedate']->get_db_date_time_format()); + $_REQUEST['action'] = $action; + if($monitor = $trackerManager->getMonitor('tracker')) + { + $monitor->setValue('action', $action); + $monitor->setValue('user_id', $GLOBALS['current_user']->id); + $monitor->setValue('module_name', $bean->module_dir); + $monitor->setValue('date_modified', $timeStamp); + $monitor->setValue('visible', (($action == 'detailview') || ($action == 'editview') + || ($action == 'wirelessdetail') || ($action == 'wirelessedit') + ) ? 1 : 0); + + if (!empty($bean->id)) + { + $monitor->setValue('item_id', $bean->id); + $monitor->setValue('item_summary', $bean->get_summary_text()); + } + + //If visible is true, but there is no bean, do not track (invalid/unauthorized reference) + //Also, do not track save actions where there is no bean id + if($monitor->visible && empty($bean->id)) + { + $trackerManager->unsetMonitor($monitor); + return false; + } + $trackerManager->saveMonitor($monitor, true, true); + if(empty(self::$_monitorId)) + { + self::$_monitorId = $monitor->monitor_id; + } + } + } + + public static function removeAllTrackerEntries() + { + if(!empty(self::$_monitorId)) + { + $GLOBALS['db']->query("DELETE FROM tracker WHERE monitor_id = '".self::$_monitorId."'"); + } + } +} +?> diff --git a/tests/SugarTestUserUtilities.php b/tests/SugarTestUserUtilities.php new file mode 100755 index 00000000..4510f93d --- /dev/null +++ b/tests/SugarTestUserUtilities.php @@ -0,0 +1,58 @@ +user_name = $userId . $time; + $user->user_hash = md5($userId.$time); + $user->first_name = $userId; + $user->last_name = $time; + $user->status='Active'; + if(!empty($id)) + { + $user->new_with_id = true; + $user->id = $id; + } + $user->save(); + $user->fill_in_additional_detail_fields(); + self::$_createdUsers[] = $user; + return $user; + } + + public function removeAllCreatedAnonymousUsers() + { + $user_ids = self::getCreatedUserIds(); + if ( count($user_ids) > 0 ) { + $GLOBALS['db']->query('DELETE FROM users WHERE id IN (\'' . implode("', '", $user_ids) . '\')'); + $GLOBALS['db']->query('DELETE FROM user_preferences WHERE assigned_user_id IN (\'' . implode("', '", $user_ids) . '\')'); + } + self::$_createdUsers = array(); + } + + public static function getCreatedUserIds() + { + $user_ids = array(); + foreach (self::$_createdUsers as $user) + $user_ids[] = $user->id; + + return $user_ids; + } +} \ No newline at end of file diff --git a/tests/codecoverage.xml b/tests/codecoverage.xml new file mode 100755 index 00000000..ba92c550 --- /dev/null +++ b/tests/codecoverage.xml @@ -0,0 +1,34 @@ + + + ./tests/include + ./tests/install + ./tests/modules + ./tests/service + ./tests/tests + + + + ./cache + ./custom + ./examples + ./jscalendar + ./jssource + ./log4php + ./metadata + ./test + ./themes + ./XTemplate + ./config.php + ./config_override.php + + + + + + + + diff --git a/tests/data/Bug39780Test.php b/tests/data/Bug39780Test.php new file mode 100755 index 00000000..e736e2bc --- /dev/null +++ b/tests/data/Bug39780Test.php @@ -0,0 +1,35 @@ +contact = SugarTestContactUtilities::createContact(); + } + + public function tearDown() + { + SugarTestContactUtilities::removeAllCreatedContacts(); + } + + // Test unPopulateDefaultValues to make sure it doesn't generate any notices + /* + * @group bug39780 + */ + public function testSugarBeanUnPopulateDefaultValues() + { + $this->contact->first_name = 'SadekDizzle'; + $this->contact->field_defs['first_name']['default'] = 'SadekSnizzle'; + try{ + $this->contact->unPopulateDefaultValues(); + } + catch(Exception $e){ + $this->assertTrue(false, "SugarBean->unPopulateDefaultValues is generating a notice/warning/fatal: " .$e->getMessage()); + return; + } + + $this->assertTrue(true); + } +} diff --git a/tests/data/Bug40739Test.php b/tests/data/Bug40739Test.php new file mode 100755 index 00000000..a54a3c7b --- /dev/null +++ b/tests/data/Bug40739Test.php @@ -0,0 +1,28 @@ +contact = SugarTestContactUtilities::createContact(); + } + + public function tearDown() + { + SugarTestContactUtilities::removeAllCreatedContacts(); + } + + /* + * @group bug40739 + */ + public function testCreatedByNameOverride() + { + $this->contact->created_by = ''; + $this->contact->created_by_name = 'admin'; + $this->contact->fill_in_additional_detail_fields(); + + $this->assertTrue($this->contact->created_by_name == 'admin', "created_by_name shouldn't have been affected by a blank created_by value"); + } +} diff --git a/tests/data/fixUpFormatting.php b/tests/data/fixUpFormatting.php new file mode 100755 index 00000000..73d10650 --- /dev/null +++ b/tests/data/fixUpFormatting.php @@ -0,0 +1,111 @@ +field_defs = array( + 'id' => array('name' => 'id', 'vname' => 'LBL_ID', 'type' => 'id', 'required' => true, ), + 'name' => array('name' => 'name', 'vname' => 'LBL_NAME', 'type' => 'varchar', 'len' => '255', 'required' => true, ), + 'bool_field' => array('name' => 'bool_field', 'vname' => 'LBL_BOOL_FIELD', 'type' => 'bool', ), + 'int_field' => array('name' => 'int_field', 'vname' => 'LBL_INT_FIELD', 'type' => 'int', ), + 'float_field' => array('name' => 'float_field', 'vname' => 'LBL_FLOAT_FIELD', 'type' => 'float', 'precision' => 2, ), + 'date_field' => array('name' => 'date_field', 'vname' => 'LBL_DATE_FIELD', 'type' => 'date', ), + 'time_field' => array('name' => 'time_field', 'vname' => 'LBL_TIME_FIELD', 'type' => 'time', ), + 'datetime_field' => array('name' => 'datetime_field', 'vname' => 'LBL_DATETIME_FIELD', 'type' => 'datetime', ), + ); + + $myBean->id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; + $myBean->name = 'Fake Bean'; + $myBean->bool_field = 1; + $myBean->int_field = 2001; + $myBean->float_field = 20.01; + $myBean->date_field = '2001-07-28'; + $myBean->time_field = '21:19:37'; + $myBean->datetime_field = '2001-07-28 21:19:37'; + + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + unset($this->time_date); + } + + public function providerBoolFixups() + { + return array( + array(true,1), + array(false,0), + array('',0), + array(1,1), + array(0,0), + array('1',1), + array('0',0), + array('true',1), + array('false',0), + array('on',1), + array('off',0), + array('yes',1), + array('no',0), + ); + } + + /** + * @group bug34562 + * @dataProvider providerBoolFixups + */ + public function testBoolFixups($from, $to) + { + $bean = new SugarBean(); + + $bean->bool_field = $from; + $bean->fixUpFormatting(); + $this->assertEquals($to,$bean->bool_field,'fixUpFormatting did not adjust from ('.gettype($from).') "'.$from.'"'); + } +} \ No newline at end of file diff --git a/tests/expressions/expression_engine_eval.php b/tests/expressions/expression_engine_eval.php new file mode 100755 index 00000000..11165c7f --- /dev/null +++ b/tests/expressions/expression_engine_eval.php @@ -0,0 +1,61 @@ +retrieve(1); + global $current_user, $timezones; + $current_user = $admin; + + try { + $expression = Parser::evaluate(from_html($_REQUEST['expression'])); + print_r($expression->evaluate()); + } catch (Exception $e) { + echo $e->getMessage(); + } +} + diff --git a/tests/expressions/expression_engine_test.html b/tests/expressions/expression_engine_test.html new file mode 100755 index 00000000..f1dd37af --- /dev/null +++ b/tests/expressions/expression_engine_test.html @@ -0,0 +1,219 @@ + + + + + +SUGAR Arithmetic Engine (JS) + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+ +
+ + + +
+ +
+ + + + \ No newline at end of file diff --git a/tests/include/Dashlets/Bug41013Test.php b/tests/include/Dashlets/Bug41013Test.php new file mode 100755 index 00000000..5cb136a5 --- /dev/null +++ b/tests/include/Dashlets/Bug41013Test.php @@ -0,0 +1,56 @@ +_moduleName = 'TestModuleForDashletLoadLanguageTest'.mt_rand(); + + sugar_mkdir("custom/modules/{$this->_moduleName}/metadata/",null,true); + sugar_file_put_contents("custom/modules/{$this->_moduleName}/metadata/dashletviewdefs.php", + '_moduleName.'Dashlet\'][\'searchFields\'] = array(); $dashletData[\''.$this->_moduleName.'Dashlet\'][\'columns\'] = array(\'Foo\'); ?>'); + + } + + public function tearDown() + { + if ( is_dir("custom/modules/{$this->_moduleName}") ) + rmdir_recursive("custom/modules/{$this->_moduleName}"); + + unset($GLOBALS['dashletStrings']); + } + + public function testCanLoadCustomMetadataTwiceInARow() + { + $dashlet = new DashletGenericMock(); + $dashlet->seedBean->module_dir = $this->_moduleName; + + $dashlet->loadCustomMetadata(); + + $this->assertEquals(array('Foo'),$dashlet->columns); + + $dashlet->columns = array(); + + $dashlet->loadCustomMetadata(); + + $this->assertEquals(array('Foo'),$dashlet->columns); + } +} + +class DashletGenericMock extends DashletGeneric +{ + public function __construct() + { + } + + public function loadCustomMetadata() + { + parent::loadCustomMetadata(); + } +} diff --git a/tests/include/Dashlets/DashletLoadLanguageTest.php b/tests/include/Dashlets/DashletLoadLanguageTest.php new file mode 100755 index 00000000..f72c5ab1 --- /dev/null +++ b/tests/include/Dashlets/DashletLoadLanguageTest.php @@ -0,0 +1,111 @@ +_moduleName = 'TestModuleForDashletLoadLanguageTest'.mt_rand(); + } + + public function tearDown() + { + if ( is_dir("modules/{$this->_moduleName}") ) + rmdir_recursive("modules/{$this->_moduleName}"); + if ( is_dir("custom/modules/{$this->_moduleName}") ) + rmdir_recursive("custom/modules/{$this->_moduleName}"); + + unset($GLOBALS['dashletStrings']); + $GLOBALS['current_language'] = $GLOBALS['sugar_config']['default_language']; + } + + public function testCanLoadCurrentLanguageAppStrings() + { + $GLOBALS['current_language'] = 'en_us'; + sugar_mkdir("modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/",null,true); + sugar_file_put_contents("modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/TestModuleDashlet.en_us.lang.php", + ''); + + $dashlet = new Dashlet(0); + $dashlet->loadLanguage('TestModuleDashlet',"modules/{$this->_moduleName}/Dashlets/"); + + $this->assertEquals("bar",$dashlet->dashletStrings["foo"]); + } + + public function testCanLoadCustomLanguageAppStrings() + { + $GLOBALS['current_language'] = 'en_us'; + sugar_mkdir("modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/",null,true); + sugar_file_put_contents("modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/TestModuleDashlet.en_us.lang.php", + ''); + create_custom_directory("modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/"); + sugar_file_put_contents("custom/modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/TestModuleDashlet.en_us.lang.php", + ''); + + $dashlet = new Dashlet(0); + $dashlet->loadLanguage('TestModuleDashlet',"modules/{$this->_moduleName}/Dashlets/"); + + $this->assertEquals("barbar",$dashlet->dashletStrings["foo"]); + } + + public function testCanLoadCustomLanguageAppStringsWhenThereIsNoNoncustomLanguageFile() + { + $GLOBALS['current_language'] = 'en_us'; + create_custom_directory("modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/"); + sugar_file_put_contents("custom/modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/TestModuleDashlet.en_us.lang.php", + ''); + + $dashlet = new Dashlet(0); + $dashlet->loadLanguage('TestModuleDashlet',"modules/{$this->_moduleName}/Dashlets/"); + + $this->assertEquals("barbar",$dashlet->dashletStrings["foo"]); + } + + public function testCanLoadCurrentLanguageAppStringsWhenNotEnglish() + { + $GLOBALS['current_language'] = 'FR_fr'; + sugar_mkdir("modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/",null,true); + sugar_file_put_contents("modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/TestModuleDashlet.en_us.lang.php", + ''); + sugar_mkdir("modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/",null,true); + sugar_file_put_contents("modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/TestModuleDashlet.FR_fr.lang.php", + ''); + + $dashlet = new Dashlet(0); + $dashlet->loadLanguage('TestModuleDashlet',"modules/{$this->_moduleName}/Dashlets/"); + + $this->assertEquals("barrie",$dashlet->dashletStrings["foo"]); + } + + public function testCanLoadEnglishLanguageAppStringsWhenCurrentLanguageDoesNotExist() + { + $GLOBALS['current_language'] = 'FR_fr'; + sugar_mkdir("modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/",null,true); + sugar_file_put_contents("modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/TestModuleDashlet.en_us.lang.php", + ''); + + $dashlet = new Dashlet(0); + $dashlet->loadLanguage('TestModuleDashlet',"modules/{$this->_moduleName}/Dashlets/"); + + $this->assertEquals("bar",$dashlet->dashletStrings["foo"]); + } + + public function testCanLoadCustomEnglishLanguageAppStringsWhenCurrentLanguageDoesNotExist() + { + $GLOBALS['current_language'] = 'FR_fr'; + sugar_mkdir("modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/",null,true); + sugar_file_put_contents("modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/TestModuleDashlet.en_us.lang.php", + ''); + create_custom_directory("modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/"); + sugar_file_put_contents("custom/modules/{$this->_moduleName}/Dashlets/TestModuleDashlet/TestModuleDashlet.en_us.lang.php", + ''); + + $dashlet = new Dashlet(0); + $dashlet->loadLanguage('TestModuleDashlet',"modules/{$this->_moduleName}/Dashlets/"); + + $this->assertEquals("barbarbar",$dashlet->dashletStrings["foo"]); + } +} diff --git a/tests/include/Expressions/Actions/ActionFactory.php b/tests/include/Expressions/Actions/ActionFactory.php new file mode 100755 index 00000000..c4c14dd1 --- /dev/null +++ b/tests/include/Expressions/Actions/ActionFactory.php @@ -0,0 +1,105 @@ + \$this->getActionName(), + "target" => "nothing" + ); + } + + static function getActionName() { + return "testCustomAction"; + } +} +EOQ; + if (!is_dir("custom/" . ActionFactory::$action_directory)) { + sugar_mkdir("custom/" . ActionFactory::$action_directory, null, true); + $this->removeCustomDir = true; + } + file_put_contents("custom/" . ActionFactory::$action_directory . "/testCustomAction.php", $actionContent); + } + + protected function removeCustomAction() + { + unlink("custom/" . ActionFactory::$action_directory . "/testCustomAction.php"); + if ($this->removeCustomDir) + unlink("custom/" . ActionFactory::$action_directory); + } + + public function testGetNewAction() + { + $sva = ActionFactory::getNewAction('SetValue', + array( + 'target' => 'name', + 'value' => 'strlen($name)' + ) + ); + $this->assertType("SetValueAction", $sva); + } + + public function testLoadCustomAction() + { + + $this->createCustomAction(); + ActionFactory::buildActionCache(true); + $customAction = ActionFactory::getNewAction('testCustomAction', array()); + $this->assertType("TestCustomAction", $customAction); + $this->removeCustomAction(); + ActionFactory::buildActionCache(true); + } +} \ No newline at end of file diff --git a/tests/include/Expressions/Expression/Parser/Parser.php b/tests/include/Expressions/Expression/Parser/Parser.php new file mode 100755 index 00000000..20bbc113 --- /dev/null +++ b/tests/include/Expressions/Expression/Parser/Parser.php @@ -0,0 +1,68 @@ +addAction( + ActionFactory::getNewAction('SetValue', array('target' => 'name', 'value' => 'notAFunction(1,1)')) + ); + $focus = new Account(); + $dep->fire($focus); + $dep->setTrigger(new Trigger('falz')); + $dep->fire($focus); + $dep->setTrigger(new Trigger('isAlpha($notAField)')); + $dep->fire($focus); + //fake assert to show the test passed + $this->assertTrue(true); + } catch (Exception $e){ + $this->assertTrue(false, "Parser threw exception: {$e->getMessage()}"); + } + } +} \ No newline at end of file diff --git a/tests/include/JSONTest.php b/tests/include/JSONTest.php new file mode 100755 index 00000000..025c9fc0 --- /dev/null +++ b/tests/include/JSONTest.php @@ -0,0 +1,27 @@ + 'bar', 'bar' => 'foo'); + $json = new JSON(); + $this->assertEquals( + '{"foo":"bar","bar":"foo"}', + $json->encode($array) + ); + } + + public function testCanEncodeBasicObjects() + { + $obj = new stdClass(); + $obj->foo = 'bar'; + $obj->bar = 'foo'; + $json = new JSON(); + $this->assertEquals( + '{"foo":"bar","bar":"foo"}', + $json->encode($obj) + ); + } +} diff --git a/tests/include/Localization/LocalizationTest.php b/tests/include/Localization/LocalizationTest.php new file mode 100755 index 00000000..6fef29f6 --- /dev/null +++ b/tests/include/Localization/LocalizationTest.php @@ -0,0 +1,211 @@ +_locale = new Localization(); + $this->_user = SugarTestUserUtilities::createAnonymousUser(); + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + } + + public function providerGetLocaleFormattedName() + { + return array( + array( + 't s f l', + 'Mason', + 'Hu', + 'Mr.', + 'Saler', + 'Saler Mr. Mason Hu', + ), + array( + 'l f', + 'Mason', + 'Hu', + '', + '', + 'Hu Mason', + ), + + ); + } + + /** + * @dataProvider providerGetLocaleFormattedName + */ + public function testGetLocaleFormattedNameUsingFormatInUserPreference($nameFormat,$firstName,$lastName,$salutation,$title,$expectedOutput) + { + $this->_user->setPreference('default_locale_name_format', $nameFormat); + $outputName = $this->_locale->getLocaleFormattedName($firstName, $lastName, $salutation, $title, '',$this->_user); + $this->assertEquals($expectedOutput, $outputName); + } + + /** + * @dataProvider providerGetLocaleFormattedName + */ + public function testGetLocaleFormattedNameUsingFormatSpecified($nameFormat,$firstName,$lastName,$salutation,$title,$expectedOutput) + { + $outputName = $this->_locale->getLocaleFormattedName($firstName, $lastName, $salutation, $title, $nameFormat,$this->_user); + $this->assertEquals($expectedOutput, $outputName); + } + + /** + * @group bug26803 + */ + public function testGetLocaleFormattedNameWhenNameIsEmpty() + { + $this->_user->setPreference('default_locale_name_format', 'l f'); + $expectedOutput = ' '; + $outputName = $this->_locale->getLocaleFormattedName('', '', '', '', '',$this->_user); + + $this->assertEquals($expectedOutput, $outputName); + } + + /** + * @group bug26803 + */ + public function testGetLocaleFormattedNameWhenNameIsEmptyAndReturningEmptyString() + { + $this->_user->setPreference('default_locale_name_format', 'l f'); + $expectedOutput = ''; + $outputName = $this->_locale->getLocaleFormattedName('', '', '', '', '',$this->_user,true); + + $this->assertEquals($expectedOutput, $outputName); + } + + public function testCurrenciesLoadingCorrectly() + { + global $sugar_config; + + $currencies = $this->_locale->getCurrencies(); + + $this->assertEquals($currencies['-99']['name'],$sugar_config['default_currency_name']); + $this->assertEquals($currencies['-99']['symbol'],$sugar_config['default_currency_symbol']); + $this->assertEquals($currencies['-99']['conversion_rate'],1); + } + + public function testConvertingUnicodeStringBetweenCharsets() + { + $string = "アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモガギグゲゴザジズゼゾダヂヅデド"; + + $convertedString = $this->_locale->translateCharset($string,'UTF-8','EUC-CN'); + $this->assertNotEquals($string,$convertedString); + + // test for this working by being able to convert back and the string match + $convertedString = $this->_locale->translateCharset($convertedString,'EUC-CN','UTF-8'); + $this->assertEquals($string,$convertedString); + } + + public function testCanDetectAsciiEncoding() + { + $string = 'string'; + + $this->assertEquals( + $this->_locale->detectCharset($string), + 'ASCII' + ); + } + + public function testCanDetectUtf8Encoding() + { + $string = 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモガギグゲゴザジズゼゾダヂヅデド'; + + $this->assertEquals( + $this->_locale->detectCharset($string), + 'UTF-8' + ); + } + + public function testGetNameJsCorrectlySpecifiesMissingOrEmptyParameters() + { + global $app_strings; + + $app_strings = return_application_language($GLOBALS['current_language']); + + $first = 'First'; + $last = 'Last'; + $salutation = 'Sal'; + $title = 'Title'; + + $ret = $this->_locale->getNameJs($first,$last,$salutation); + + $this->assertRegExp("/stuff\['s'\] = '$salutation';/",$ret); + $this->assertRegExp("/stuff\['f'\] = '$first';/",$ret); + $this->assertRegExp("/stuff\['l'\] = '$last';/",$ret); + $this->assertRegExp("/stuff\['t'\] = '{$app_strings['LBL_LOCALE_NAME_EXAMPLE_TITLE']}';/",$ret); + + $ret = $this->_locale->getNameJs('',$last,$salutation); + + $this->assertRegExp("/stuff\['s'\] = '$salutation';/",$ret); + $this->assertRegExp("/stuff\['f'\] = '{$app_strings['LBL_LOCALE_NAME_EXAMPLE_FIRST']}';/",$ret); + $this->assertRegExp("/stuff\['l'\] = '$last';/",$ret); + $this->assertRegExp("/stuff\['t'\] = '{$app_strings['LBL_LOCALE_NAME_EXAMPLE_TITLE']}';/",$ret); + } + + public function testGetPrecedentPreferenceWithUserPreference() + { + $backup = $GLOBALS['sugar_config']['export_delimiter']; + $GLOBALS['sugar_config']['export_delimiter'] = 'John is Cool'; + $this->_user->setPreference('export_delimiter','John is Really Cool'); + + $this->assertEquals( + $this->_locale->getPrecedentPreference('export_delimiter',$this->_user), + $this->_user->getPreference('export_delimiter') + ); + + $GLOBALS['sugar_config']['export_delimiter'] = $backup; + } + + public function testGetPrecedentPreferenceWithNoUserPreference() + { + $backup = $GLOBALS['sugar_config']['export_delimiter']; + $GLOBALS['sugar_config']['export_delimiter'] = 'John is Cool'; + + $this->assertEquals( + $this->_locale->getPrecedentPreference('export_delimiter',$this->_user), + $GLOBALS['sugar_config']['export_delimiter'] + ); + + $GLOBALS['sugar_config']['export_delimiter'] = $backup; + } + + /** + * @ticket 33086 + */ + public function testGetPrecedentPreferenceWithUserPreferenceAndSpecifiedConfigKey() + { + $backup = $GLOBALS['sugar_config']['export_delimiter']; + $GLOBALS['sugar_config']['export_delimiter'] = 'John is Cool'; + $this->_user->setPreference('export_delimiter',''); + $GLOBALS['sugar_config']['default_random_setting_for_localization_test'] = 'John is not Cool at all'; + + $this->assertEquals( + $this->_locale->getPrecedentPreference('export_delimiter',$this->_user,'default_random_setting_for_localization_test'), + $GLOBALS['sugar_config']['default_random_setting_for_localization_test'] + ); + + $backup = $GLOBALS['sugar_config']['export_delimiter']; + unset($GLOBALS['sugar_config']['default_random_setting_for_localization_test']); + } + + /** + * @ticket 39171 + */ + public function testGetPrecedentPreferenceForDefaultEmailCharset() + { + $emailSettings = array('defaultOutboundCharset' => 'something fun'); + $this->_user->setPreference('emailSettings',$emailSettings, 0, 'Emails'); + + $this->assertEquals( + $this->_locale->getPrecedentPreference('default_email_charset',$this->_user), + $emailSettings['defaultOutboundCharset'] + ); + } +} diff --git a/tests/include/MVC/Controller/SugarControllerTest.php b/tests/include/MVC/Controller/SugarControllerTest.php new file mode 100755 index 00000000..288d49e1 --- /dev/null +++ b/tests/include/MVC/Controller/SugarControllerTest.php @@ -0,0 +1,180 @@ +setup($module_name); + $controller->do_action = 'ListView'; + $controller->view = 'list'; + $controller->callLegacyCode(); + + $this->assertEquals('classic',$controller->view); + + rmdir_recursive("modules/$module_name"); + } + + public function testCallLegacyCodeIfNewListViewFound() + { + $module_name = 'TestModule'.mt_rand(); + sugar_mkdir("modules/$module_name/views",null,true); + sugar_touch("modules/$module_name/views/view.list.php"); + + $controller = new SugarControllerMock; + $controller->setup($module_name); + $controller->do_action = 'ListView'; + $controller->view = 'list'; + $controller->callLegacyCode(); + + $this->assertEquals('list',$controller->view); + + rmdir_recursive("modules/$module_name"); + } + + /** + * @ticket 41755 + */ + public function testCallLegacyCodeIfLegacyListViewAndNewListViewFound() + { + $module_name = 'TestModule'.mt_rand(); + sugar_mkdir("modules/$module_name/views",null,true); + sugar_touch("modules/$module_name/views/view.list.php"); + sugar_touch("modules/$module_name/ListView.php"); + + $controller = new SugarControllerMock; + $controller->setup($module_name); + $controller->do_action = 'ListView'; + $controller->view = 'list'; + $controller->callLegacyCode(); + + $this->assertEquals('list',$controller->view); + + rmdir_recursive("modules/$module_name"); + } + + public function testCallLegacyCodeIfCustomLegacyListViewAndNewListViewFound() + { + $module_name = 'TestModule'.mt_rand(); + sugar_mkdir("modules/$module_name/views",null,true); + sugar_touch("modules/$module_name/views/view.list.php"); + sugar_mkdir("custom/modules/$module_name",null,true); + sugar_touch("custom/modules/$module_name/ListView.php"); + + $controller = new SugarControllerMock; + $controller->setup($module_name); + $controller->do_action = 'ListView'; + $controller->view = 'list'; + $controller->callLegacyCode(); + + $this->assertEquals('classic',$controller->view); + + rmdir_recursive("modules/$module_name"); + } + + public function testCallLegacyCodeIfLegacyListViewAndCustomNewListViewFound() + { + $module_name = 'TestModule'.mt_rand(); + sugar_mkdir("custom/modules/$module_name/views",null,true); + sugar_touch("custom/modules/$module_name/views/view.list.php"); + sugar_mkdir("modules/$module_name",null,true); + sugar_touch("modules/$module_name/ListView.php"); + + $controller = new SugarControllerMock; + $controller->setup($module_name); + $controller->do_action = 'ListView'; + $controller->view = 'list'; + $controller->callLegacyCode(); + + $this->assertEquals('classic',$controller->view); + + rmdir_recursive("modules/$module_name"); + } + + public function testCallLegacyCodeIfLegacyListViewAndNewListViewFoundAndCustomLegacyListViewFound() + { + $module_name = 'TestModule'.mt_rand(); + sugar_mkdir("modules/$module_name/views",null,true); + sugar_touch("modules/$module_name/views/view.list.php"); + sugar_touch("modules/$module_name/ListView.php"); + sugar_mkdir("custom/modules/$module_name",null,true); + sugar_touch("custom/modules/$module_name/ListView.php"); + + $controller = new SugarControllerMock; + $controller->setup($module_name); + $controller->do_action = 'ListView'; + $controller->view = 'list'; + $controller->callLegacyCode(); + + $this->assertEquals('classic',$controller->view); + + rmdir_recursive("modules/$module_name"); + } + + public function testCallLegacyCodeIfLegacyListViewAndNewListViewFoundAndCustomNewListViewFound() + { + $module_name = 'TestModule'.mt_rand(); + sugar_mkdir("custom/modules/$module_name/views",null,true); + sugar_touch("custom/modules/$module_name/views/view.list.php"); + sugar_mkdir("modules/$module_name/views",null,true); + sugar_touch("modules/$module_name/views/view.list.php"); + sugar_touch("modules/$module_name/ListView.php"); + + $controller = new SugarControllerMock; + $controller->setup($module_name); + $controller->do_action = 'ListView'; + $controller->view = 'list'; + $controller->callLegacyCode(); + + $this->assertEquals('list',$controller->view); + + rmdir_recursive("modules/$module_name"); + } + + public function testCallLegacyCodeIfLegacyListViewAndNewListViewFoundAndCustomLegacyListViewFoundAndCustomNewListViewFound() + { + $module_name = 'TestModule'.mt_rand(); + sugar_mkdir("custom/modules/$module_name/views",null,true); + sugar_touch("custom/modules/$module_name/views/view.list.php"); + sugar_touch("custom/modules/$module_name/ListView.php"); + sugar_mkdir("modules/$module_name/views",null,true); + sugar_touch("modules/$module_name/views/view.list.php"); + sugar_touch("modules/$module_name/ListView.php"); + + $controller = new SugarControllerMock; + $controller->setup($module_name); + $controller->do_action = 'ListView'; + $controller->view = 'list'; + $controller->callLegacyCode(); + + $this->assertEquals('list',$controller->view); + + rmdir_recursive("modules/$module_name"); + } +} + +class SugarControllerMock extends SugarController +{ + public $do_action; + + public function callLegacyCode() + { + return parent::callLegacyCode(); + } +} diff --git a/tests/include/MVC/SugarApplicationTest.php b/tests/include/MVC/SugarApplicationTest.php new file mode 100755 index 00000000..de45cdb0 --- /dev/null +++ b/tests/include/MVC/SugarApplicationTest.php @@ -0,0 +1,142 @@ +retrieveSettings(); + $GLOBALS['system_config'] = $system_config; + $this->_app = new SugarApplication(); + if ( isset($_SESSION['authenticated_user_theme']) ) + unset($_SESSION['authenticated_user_theme']); + } + + private function _loadUser() + { + $GLOBALS['current_user'] = SugarTestUserUtilities::createAnonymousUser(); + $_SESSION[$GLOBALS['current_user']->user_name.'_PREFERENCES']['global']['gridline'] = 'on'; + } + + private function _removeUser() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + } + + public function tearDown() + { + unset($GLOBALS['current_user']); + unset($GLOBALS['moduleList']); + unset($GLOBALS['modInvisListActivities']); + unset($GLOBALS['request_string']); + unset($GLOBALS['adminOnlyList']); + unset($GLOBALS['modListHeader']); + unset($GLOBALS['modInvisList']); + unset($GLOBALS['app_strings']); + unset($GLOBALS['system_config']); + unset($GLOBALS['app_list_strings']); + unset($GLOBALS['mod_strings']); + unset($GLOBALS['theme']); + unset($GLOBALS['image_path']); + unset($GLOBALS['starttTime']); + unset($GLOBALS['sugar_version']); + unset($GLOBALS['sugar_flavor']); + $GLOBALS['current_language'] = $GLOBALS['sugar_config']['default_language']; + } + + public function testSetupPrint() + { + $_GET['foo'] = 'bar'; + $_POST['dog'] = 'cat'; + $this->_app->setupPrint(); + $this->assertEquals($GLOBALS['request_string'], + 'foo=bar&dog=cat&print=true' + ); + } + + public function testLoadDisplaySettingsDefault() + { + $this->_loadUser(); + + $this->_app->loadDisplaySettings(); + + $this->assertEquals($GLOBALS['theme'], + $GLOBALS['sugar_config']['default_theme']); + + $this->_removeUser(); + } + + public function testLoadDisplaySettingsAuthUserTheme() + { + $this->_loadUser(); + + $_SESSION['authenticated_user_theme'] = 'Sugar'; + + $this->_app->loadDisplaySettings(); + + $this->assertEquals($GLOBALS['theme'], + $_SESSION['authenticated_user_theme']); + + $this->_removeUser(); + } + + public function testLoadDisplaySettingsUserTheme() + { + $this->_loadUser(); + + $_REQUEST['usertheme'] = 'Sugar5'; + + $this->_app->loadDisplaySettings(); + + $this->assertEquals($GLOBALS['theme'], + $_REQUEST['usertheme']); + + $this->_removeUser(); + } + + public function testLoadGlobals() + { + $this->_app->controller = + ControllerFactory::getController($this->_app->default_module); + $this->_app->loadGlobals(); + + $this->assertEquals($GLOBALS['currentModule'],$this->_app->default_module); + $this->assertEquals($_REQUEST['module'],$this->_app->default_module); + $this->assertEquals($_REQUEST['action'],$this->_app->default_action); + } + + /** + * @group bug33283 + */ + public function testCheckDatabaseVersion() + { + if ( isset($GLOBALS['sugar_db_version']) ) + $old_sugar_db_version = $GLOBALS['sugar_db_version']; + if ( isset($GLOBALS['sugar_version']) ) + $old_sugar_version = $GLOBALS['sugar_version']; + include 'sugar_version.php'; + $GLOBALS['sugar_version'] = $sugar_version; + + // first test a valid value + $GLOBALS['sugar_db_version'] = $sugar_db_version; + $this->assertTrue($this->_app->checkDatabaseVersion(false)); + + $GLOBALS['sugar_db_version'] = '1.1.1'; + // then test to see if we pull against the cache the valid value + $this->assertTrue($this->_app->checkDatabaseVersion(false)); + + // now retest to be sure we actually do the check again + sugar_cache_put('checkDatabaseVersion_row_count', 0); + $this->assertFalse($this->_app->checkDatabaseVersion(false)); + + if ( isset($old_sugar_db_version) ) + $GLOBALS['sugar_db_version'] = $old_sugar_db_version; + if ( isset($old_sugar_version) ) + $GLOBALS['sugar_version'] = $old_sugar_version; + } +} diff --git a/tests/include/MVC/SugarModuleTest.php b/tests/include/MVC/SugarModuleTest.php new file mode 100755 index 00000000..a48528c3 --- /dev/null +++ b/tests/include/MVC/SugarModuleTest.php @@ -0,0 +1,49 @@ +is_admin = '1'; + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + unset($GLOBALS['beanFiles']); + unset($GLOBALS['beanList']); + } + + public function testLoadBean() + { + $this->assertTrue(SugarModule::get('Accounts')->loadBean() instanceOf Account); + } + + public function testLoadBeanInvalidBean() + { + $this->assertFalse(SugarModule::get('JohnIsACoolGuy')->loadBean()); + } + + public function testModuleImpliments() + { + $this->assertTrue(SugarModule::get('Accounts')->moduleImplements('Company')); + } + + public function testModuleImplimentsInvalidBean() + { + $this->assertFalse(SugarModule::get('JohnIsACoolGuy')->moduleImplements('Person')); + } + + public function testModuleImplimentsWhenModuleDoesNotImplimentTemplate() + { + $this->assertFalse(SugarModule::get('Accounts')->moduleImplements('Person')); + } +} diff --git a/tests/include/MVC/View/Bug40019Test.php b/tests/include/MVC/View/Bug40019Test.php new file mode 100755 index 00000000..7790542b --- /dev/null +++ b/tests/include/MVC/View/Bug40019Test.php @@ -0,0 +1,71 @@ +get_recently_viewed($GLOBALS['current_user']->id, 'Contacts'); + + $expected = $max > 10 ? 10 : $max; + + $this->assertTrue(count($history) == $expected); + } + + // Currently, getBreadCrumbList in BreadCrumbStack.php limits you to 10 + /* + * @group bug40019 + */ + public function testModuleMenuLastViewedForAll() + { + global $sugar_config; + $max = $sugar_config['history_max_viewed']; + + $tracker = new Tracker(); + $history = $tracker->get_recently_viewed($GLOBALS['current_user']->id, ''); + + $expected = $max > 10 ? 10 : $max; + + $this->assertTrue(count($history) == $expected); + } +} \ No newline at end of file diff --git a/tests/include/MVC/View/LoadMenuTest.php b/tests/include/MVC/View/LoadMenuTest.php new file mode 100755 index 00000000..87ee2f19 --- /dev/null +++ b/tests/include/MVC/View/LoadMenuTest.php @@ -0,0 +1,223 @@ +_moduleName = 'TestModule'.mt_rand(); + + $GLOBALS['current_user'] = SugarTestUserUtilities::createAnonymousUser(); + + sugar_mkdir("modules/{$this->_moduleName}",null,true); + } + + public function tearDown() + { + unset($GLOBALS['mod_strings']); + unset($GLOBALS['app_strings']); + + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + + if ( is_dir("modules/{$this->_moduleName}") ) + rmdir_recursive("modules/{$this->_moduleName}"); + if ( is_dir("custom/modules/{$this->_moduleName}") ) + rmdir_recursive("custom/modules/{$this->_moduleName}"); + } + + public function testMenuDoesNotExists() + { + $view = new SugarView; + $module_menu = $view->getMenu($this->_moduleName); + $this->assertTrue(empty($module_menu),'Assert the module menu array is empty'); + } + + public function testMenuExistsCanFindModuleMenu() + { + // Create module menu + if( $fh = @fopen("modules/{$this->_moduleName}/Menu.php", 'w+') ) { + $string = << +EOQ; + fputs( $fh, $string); + fclose( $fh ); + } + + $view = new SugarView; + $module_menu = $view->getMenu($this->_moduleName); + $found_custom_menu = false; + foreach ($module_menu as $menu_entry) { + foreach ($menu_entry as $menu_item) { + if (preg_match('/action=bar/', $menu_item)) { + $found_custom_menu = true; + } + } + } + $this->assertTrue($found_custom_menu, "Assert that menu was detected"); + } + + /** + * @group bug29114 + */ + public function testMenuExistsCanFindModuleExtMenu() + { + // Create module ext menu + sugar_mkdir("custom/modules/{$this->_moduleName}/Ext/Menus/",null,true); + if( $fh = @fopen("custom/modules/{$this->_moduleName}/Ext/Menus/menu.ext.php", 'w+') ) { + $string = << +EOQ; + fputs( $fh, $string); + fclose( $fh ); + } + + $view = new SugarView; + $module_menu = $view->getMenu($this->_moduleName); + $found_custom_menu = false; + foreach ($module_menu as $key => $menu_entry) { + foreach ($menu_entry as $id => $menu_item) { + if (preg_match('/action=foo/', $menu_item)) { + $found_custom_menu = true; + } + } + } + $this->assertTrue($found_custom_menu, "Assert that custom menu was detected"); + } + + /** + * @group bug38935 + */ + public function testMenuExistsCanFindModuleExtMenuWhenModuleMenuDefinedGlobal() + { + // Create module ext menu + sugar_mkdir("custom/modules/{$this->_moduleName}/Ext/Menus/",null,true); + if( $fh = @fopen("custom/modules/{$this->_moduleName}/Ext/Menus/menu.ext.php", 'w+') ) { + $string = << +EOQ; + fputs( $fh, $string); + fclose( $fh ); + } + + $view = new SugarView; + $module_menu = $view->getMenu($this->_moduleName); + $found_custom_menu = false; + foreach ($module_menu as $key => $menu_entry) { + foreach ($menu_entry as $id => $menu_item) { + if (preg_match('/action=foo/', $menu_item)) { + $found_custom_menu = true; + } + } + } + $this->assertTrue($found_custom_menu, "Assert that custom menu was detected"); + } + + public function testMenuExistsCanFindApplicationExtMenu() + { + // Create module ext menu + $backupCustomMenu = false; + if ( !is_dir("custom/application/Ext/Menus/") ) + sugar_mkdir("custom/application/Ext/Menus/",null,true); + if (file_exists('custom/application/Ext/Menus/menu.ext.php')) { + copy('custom/application/Ext/Menus/menu.ext.php', 'custom/application/Ext/Menus/menu.ext.php.backup'); + $backupCustomMenu = true; + } + + if ( $fh = @fopen("custom/application/Ext/Menus/menu.ext.php", 'w+') ) { + $string = << +EOQ; + fputs( $fh, $string); + fclose( $fh ); + } + + $view = new SugarView; + $module_menu = $view->getMenu($this->_moduleName); + $found_application_custom_menu = false; + foreach ($module_menu as $key => $menu_entry) { + foreach ($menu_entry as $id => $menu_item) { + if (preg_match('/action=foobar/', $menu_item)) { + $found_application_custom_menu = true; + } + } + } + $this->assertTrue($found_application_custom_menu, "Assert that application custom menu was detected"); + + if($backupCustomMenu) { + copy('custom/application/Ext/Menus/menu.ext.php.backup', 'custom/application/Ext/Menus/menu.ext.php'); + unlink('custom/application/Ext/Menus/menu.ext.php.backup'); + } + else + unlink('custom/application/Ext/Menus/menu.ext.php'); + } + + public function testMenuExistsCanFindModuleMenuAndModuleExtMenu() + { + // Create module menu + if( $fh = @fopen("modules/{$this->_moduleName}/Menu.php", 'w+') ) { + $string = << +EOQ; + fputs( $fh, $string); + fclose( $fh ); + } + + // Create module ext menu + sugar_mkdir("custom/modules/{$this->_moduleName}/Ext/Menus/",null,true); + if( $fh = @fopen("custom/modules/{$this->_moduleName}/Ext/Menus/menu.ext.php", 'w+') ) { + $string = << +EOQ; + fputs( $fh, $string); + fclose( $fh ); + } + + $view = new SugarView; + $module_menu = $view->getMenu($this->_moduleName); + $found_custom_menu = false; + $found_menu = false; + foreach ($module_menu as $key => $menu_entry) { + foreach ($menu_entry as $id => $menu_item) { + if (preg_match('/action=foo/', $menu_item)) { + $found_menu = true; + } + if (preg_match('/action=bar/', $menu_item)) { + $found_custom_menu = true; + } + } + } + $this->assertTrue($found_menu, "Assert that menu was detected"); + $this->assertTrue($found_custom_menu, "Assert that custom menu was detected"); + } +} + +class ViewLoadMenuTest extends SugarView +{ + public function menuExists( + $module + ) + { + return $this->_menuExists($module); + } +} \ No newline at end of file diff --git a/tests/include/MassUpdateTest.php b/tests/include/MassUpdateTest.php new file mode 100755 index 00000000..0df1a9ab --- /dev/null +++ b/tests/include/MassUpdateTest.php @@ -0,0 +1,72 @@ +addDate($displayname , $varname); + $pos_f = strrpos($result, $GLOBALS['app_strings']['LBL_MASSUPDATE_DATE']); + $this->assertTrue((bool) $pos_f); + } + + /** + * @group bug23900 + */ + public function testAddStatus() + { + $mass = new MassUpdate(); + $options = array ( + '10' => 'ten', + '20' => 'twenty', + '30' => 'thirty', + ); + $result = $mass->addStatus('test_dom', 'test_dom', $options); + preg_match_all('/value=[\'\"].*?[\'\"]/si', $result, $matches); + $this->assertTrue(isset($matches)); + $this->assertTrue($matches[0][0] == "value=''"); + $this->assertTrue($matches[0][1] == "value='10'"); + $this->assertTrue($matches[0][3] == "value='30'"); + } + + /** + * @group bug23900 + */ + public function testAddStatusMulti() + { + $mass = new MassUpdate(); + $options = array ( + '10' => 'ten', + '20' => 'twenty', + '30' => 'thirty', + ); + + $result = $mass->addStatusMulti('test_dom', 'test_dom', $options); + preg_match_all('/value=[\'\"].*?[\'\"]/si', $result, $matches); + $this->assertTrue(isset($matches)); + $this->assertTrue($matches[0][0] == "value=''"); + $this->assertTrue($matches[0][1] == "value='10'"); + $this->assertTrue($matches[0][3] == "value='30'"); + } +} diff --git a/tests/include/OutboundEmail/Bug23140Test.php b/tests/include/OutboundEmail/Bug23140Test.php new file mode 100755 index 00000000..dc32723c --- /dev/null +++ b/tests/include/OutboundEmail/Bug23140Test.php @@ -0,0 +1,207 @@ +_user = SugarTestUserUtilities::createAnonymousUser(); + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + + if ($this->ob != null) + $GLOBALS['db']->query("DELETE FROM outbound_email WHERE id= '{$this->ob->id}'"); + if ($this->userOverideAccont != null) + $GLOBALS['db']->query("DELETE FROM outbound_email WHERE id= '{$this->userOverideAccont->id}'"); + } + + function testSystemAccountMailSettingsChangedUserAccessToUsername() + { + //User not alloweed to access system email username/password + $GLOBALS['db']->query("INSERT INTO config (category,name,value) VALUES ('notify','allow_default_outbound','2') "); + + $newSystemPort = 864; + $newSystemServer = "system.imap.com"; + $newSystemUsername = "sytem_user_name"; + $newSystemPassword = "SYSTEM_PASSWORD"; + + $userID = create_guid(); + $ob = new OutboundEmail(); + $ob->id = $userID; + $ob->new_with_id = TRUE; + $ob->name = 'Sugar Test'; + $ob->type = 'system-override'; + $ob->user_id = $this->_user->id; + $ob->mail_sendtype = "SMTP"; + $ob->mail_smtpuser = "Test User"; + $ob->mail_smtppass = "User Pass"; + $ob->save(); + $this->ob = $ob; + + + $system = $ob->getSystemMailerSettings(); + $system->new_with_id = FALSE; + $system->mail_smtpport = $newSystemPort; + $system->mail_smtpserver = $newSystemServer; + $system->mail_smtpuser = $newSystemUsername; + $system->mail_smtppass = $newSystemPassword; + + $system->saveSystem(); + + $obRetrieved = new OutboundEmail(); + $obRetrieved->retrieve($userID); + + $this->assertEquals($newSystemPort, $obRetrieved->mail_smtpport, "Could not update users sytem-override accounts after system save."); + $this->assertEquals($newSystemServer, $obRetrieved->mail_smtpserver, "Could not update users sytem-override accounts after system save."); + $this->assertEquals($newSystemUsername, $obRetrieved->mail_smtpuser, "Could not update users sytem-override accounts after system save."); + $this->assertEquals($newSystemPassword, $obRetrieved->mail_smtppass, "Could not update users sytem-override accounts after system save."); + + } + + + function testSystemAccountMailSettingsChangedNoUserAccessToUsername() + { + //User not alloweed to access system email username/password + $GLOBALS['db']->query("DELETE FROM config WHERE category='notify' AND name='allow_default_outbound' "); + + $newSystemPort = 864; + $newSystemServer = "system.imap.com"; + + $userID = create_guid(); + $ob = new OutboundEmail(); + $ob->id = $userID; + $ob->new_with_id = TRUE; + $ob->name = 'Sugar Test'; + $ob->type = 'system-override'; + $ob->user_id = $this->_user->id; + $ob->mail_sendtype = "SMTP"; + $ob->mail_smtpuser = "Test User"; + $ob->mail_smtppass = "User Pass"; + $ob->save(); + $this->ob = $ob; + + + $system = $ob->getSystemMailerSettings(); + $system->new_with_id = FALSE; + $system->mail_smtpport = $newSystemPort; + $system->mail_smtpserver = $newSystemServer; + $system->saveSystem(); + + $obRetrieved = new OutboundEmail(); + $obRetrieved->retrieve($userID); + + $this->assertEquals($newSystemPort, $obRetrieved->mail_smtpport, "Could not update users sytem-override accounts after system save."); + $this->assertEquals($newSystemServer, $obRetrieved->mail_smtpserver, "Could not update users sytem-override accounts after system save."); + $this->assertEquals("Test User", $obRetrieved->mail_smtpuser, "Could not update users sytem-override accounts after system save."); + $this->assertEquals("User Pass", $obRetrieved->mail_smtppass, "Could not update users sytem-override accounts after system save."); + } + + + function testUserMailForSystemOverrideRetrieval() + { + $ob = new OutboundEmail(); + $ob->name = 'Sugar Test'; + $ob->type = 'system-override'; + $ob->user_id = $this->_user->id; + $ob->mail_sendtype = "SMTP"; + $ob->mail_smtpuser = "Test User"; + $ob->save(); + $this->ob = $ob; + + $retrievedOb = $ob->getUsersMailerForSystemOverride($this->_user->id); + $this->assertEquals($ob->name, $retrievedOb->name, "Could not retrieve users system override outbound email account"); + $this->assertEquals($ob->type, $retrievedOb->type, "Could not retrieve users system override outbound email account"); + $this->assertEquals($ob->user_id, $retrievedOb->user_id, "Could not retrieve users system override outbound email account"); + $this->assertEquals($ob->mail_sendtype, $retrievedOb->mail_sendtype, "Could not retrieve users system override outbound email account"); + $this->assertEquals("Test User", $retrievedOb->mail_smtpuser, "Could not retrieve users system override outbound email account"); + } + + function testDuplicateSystemAccountForUser() + { + $oe = new OutboundEmail(); + $userOverideAccont = $oe->createUserSystemOverrideAccount($this->_user->id, "TEST USER NAME", "TEST PASSWORD"); + $this->userOverideAccont = $userOverideAccont; + $retrievedOb = $oe->getUsersMailerForSystemOverride($this->_user->id); + + $this->assertEquals("TEST USER NAME", $retrievedOb->mail_smtpuser, "Could not duplicate systems outbound account for user"); + $this->assertEquals($this->_user->id, $retrievedOb->user_id, "Could not duplicate systems outbound account for user"); + $this->assertEquals("TEST PASSWORD", $retrievedOb->mail_smtppass, "Could not duplicate systems outbound account for user"); + $this->assertEquals('system-override', $userOverideAccont->type, "Could not duplicate systems outbound account for user"); + } + + function testIsUserAlloweedAccessToSystemOutboundEmail() + { + $oe = new OutboundEmail(); + $GLOBALS['db']->query("DELETE FROM config WHERE category='notify' AND name='allow_default_outbound' "); + $emptyTest = $oe->isAllowUserAccessToSystemDefaultOutbound(); + $this->assertFalse($emptyTest, "User alloweed access to system outbound email account error"); + + $GLOBALS['db']->query("INSERT INTO config (category,name,value) VALUES ('notify','allow_default_outbound','2') "); + $allowTest = $oe->isAllowUserAccessToSystemDefaultOutbound(); + $this->assertTrue($allowTest, "User alloweed access to system outbound email account error"); + + $GLOBALS['db']->query("DELETE FROM config WHERE category='notify' AND name='allow_default_outbound' "); + $emptyTest = $oe->isAllowUserAccessToSystemDefaultOutbound(); + $this->assertFalse($emptyTest, "User alloweed access to system outbound email account error"); + + } + + + function testIsUserAuthRequiredForOverrideAccount() + { + $oe = new OutboundEmail(); + + $GLOBALS['db']->query("DELETE FROM config WHERE category='notify' AND name='allow_default_outbound' "); + $system = $oe->getSystemMailerSettings(); + + //System does not require auth, no user overide account. + $system->mail_smtpauth_req = 0; + $system->save(FALSE); + + $notRequired = $oe->doesUserOverrideAccountRequireCredentials($this->_user->id); + $this->assertFalse($notRequired, "Test failed for determining if user auth required."); + + //System does require auth, no user overide account. + $system->mail_smtpauth_req = 1; + $system->save(FALSE); + $notRequired = $oe->doesUserOverrideAccountRequireCredentials($this->_user->id); + $this->assertTrue($notRequired, "Test failed for determining if user auth required."); + + //System requires auth and users alloweed to use sys defaults. + $GLOBALS['db']->query("INSERT INTO config (category,name,value) VALUES ('notify','allow_default_outbound','2') "); + $notRequired = $oe->doesUserOverrideAccountRequireCredentials($this->_user->id); + $this->assertFalse($notRequired, "Test failed for determining if user auth required."); + + + //System requires auth but user details are empty and users are not alloweed to use system details.. + $GLOBALS['db']->query("DELETE FROM config WHERE category='notify' AND name='allow_default_outbound' "); + $userOverideAccont = $oe->createUserSystemOverrideAccount($this->_user->id, "", ""); + $this->userOverideAccont = $userOverideAccont; + $notRequired = $oe->doesUserOverrideAccountRequireCredentials($this->_user->id); + $this->assertTrue($notRequired, "Test failed for determining if user auth required."); + + //User has provided all credentials. + $this->userOverideAccont->mail_smtpuser = "TEST USER NAME"; + $this->userOverideAccont->mail_smtppass = "TEST PASSWORD"; + $this->userOverideAccont->new_with_id = FALSE; + $this->userOverideAccont->save(); + $notRequired = $oe->doesUserOverrideAccountRequireCredentials($this->_user->id); + $this->assertFalse($notRequired, "Test failed for determining if user auth required."); + + } + +} +?> \ No newline at end of file diff --git a/tests/include/OutboundEmail/Bug32487Test.php b/tests/include/OutboundEmail/Bug32487Test.php new file mode 100755 index 00000000..b05fe704 --- /dev/null +++ b/tests/include/OutboundEmail/Bug32487Test.php @@ -0,0 +1,59 @@ +outbound_id = uniqid(); + $time = date('Y-m-d H:i:s'); + + $ib = new InboundEmail(); + $ib->is_personal = 1; + $ib->name = "Test"; + $ib->port = 3309; + $ib->mailbox = 'empty'; + $ib->created_by = $current_user->id; + $ib->email_password = "pass"; + $ib->protocol = 'IMAP'; + $stored_options['outbound_email'] = $this->outbound_id; + $ib->stored_options = base64_encode(serialize($stored_options)); + $ib->save(); + $this->ib = $ib; + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + + $GLOBALS['db']->query("DELETE FROM inbound_email WHERE id= '{$this->ib->id}'"); + + unset($this->ib); + } + + function testGetAssoicatedInboundAccountForOutboundAccounts(){ + global $current_user; + $ob = new OutboundEmail(); + $ob->id = $this->outbound_id; + + $results = $ob->getAssociatedInboundAccounts($current_user); + $this->assertEquals($this->ib->id, $results[0], "Could not retrieve the inbound mail accounts for an outbound account"); + + $obEmpty = new OutboundEmail(); + $obEmpty->id = uniqid(); + + $empty_results = $obEmpty->getAssociatedInboundAccounts($current_user); + $this->assertEquals(0, count($empty_results), "Outbound email account returned for unspecified/empty inbound mail account."); + } +} +?> \ No newline at end of file diff --git a/tests/include/Popup/Bug36329Test.php b/tests/include/Popup/Bug36329Test.php new file mode 100755 index 00000000..3ac7c01a --- /dev/null +++ b/tests/include/Popup/Bug36329Test.php @@ -0,0 +1,100 @@ +save_query = isset($sugar_config['save_query']) ? true : false; + $this->current_language = $GLOBALS['current_language']; + + global $current_user; + $current_user = new User(); + $current_user->retrieve('1'); + + global $mod_strings, $app_strings; + $mod_strings = return_module_language('en_us', 'Accounts'); + $app_strings = return_application_language('en_us'); + + $beanList = array(); + $beanFiles = array(); + require('include/modules.php'); + $GLOBALS['beanList'] = $beanList; + $GLOBALS['beanFiles'] = $beanFiles; + + require('sugar_version.php'); + $GLOBALS['sugar_version'] = $sugar_version; + } + + public function tearDown() + { + global $sugar_config; + + if(!$this->save_query) { + unset($sugar_config['save_query']); + } + + $GLOBALS['current_language'] = $this->current_language; + unset($GLOBALS['mod_strings']); + unset($GLOBALS['app_strings']); + unset($GLOBALS['beanList']); + unset($GLOBALS['beanFiles']); + } + + public function test_populate_only_no_query() + { + $GLOBALS['sugar_config']['save_query'] = 'populate_only'; + $_REQUEST['module'] = 'Accounts'; + $_REQUEST['action'] = 'Popup'; + $_REQUEST['mode'] = 'single'; + $_REQUEST['create'] = 'true'; + $_REQUEST['metadata'] = 'undefined'; + require_once('include/MVC/View/SugarView.php'); + require_once('include/MVC/View/views/view.popup.php'); + require_once('include/utils/layout_utils.php'); + $popup = new ViewPopup(); + $popup->module = 'Accounts'; + require_once('modules/Accounts/Account.php'); + $popup->bean = new account(); + ob_start(); + $popup->display(); + $ob_contents = ob_get_contents(); + ob_end_clean(); + $found_text = preg_match('/Perform a search using the search form above/', $ob_contents) ? true : false; + $this->assertTrue($found_text); + } + + + public function test_populate_only_with_query() + { + $GLOBALS['sugar_config']['save_query'] = 'populate_only'; + global $app_strings; + $_REQUEST['module'] = 'Accounts'; + $_REQUEST['action'] = 'Popup'; + $_REQUEST['mode'] = 'single'; + $_REQUEST['create'] = 'true'; + $_REQUEST['metadata'] = 'undefined'; + $_REQUEST['name_advanced'] = 'Test'; + $_REQUEST['query'] = 'true'; + require_once('include/MVC/View/SugarView.php'); + require_once('include/MVC/View/views/view.popup.php'); + require_once('include/utils/layout_utils.php'); + $popup = new ViewPopup(); + $popup->module = 'Accounts'; + require_once('modules/Accounts/Account.php'); + $popup->bean = new account(); + ob_start(); + $popup->display(); + $ob_contents = ob_get_contents(); + ob_end_clean(); + $found_text = preg_match('/Perform a search using the search form above/', $ob_contents) ? true : false; + $this->assertFalse($found_text); + } +} \ No newline at end of file diff --git a/tests/include/SearchForm/SugarSpotTest.php b/tests/include/SearchForm/SugarSpotTest.php new file mode 100755 index 00000000..48270afb --- /dev/null +++ b/tests/include/SearchForm/SugarSpotTest.php @@ -0,0 +1,55 @@ +setAppListString('moduleList',array('Foo'=>'Bar')); + $langpack->save(); + + $result = array( + 'Foo' => array( + 'data' => array( + array( + 'ID' => '1', + 'NAME' => 'recordname', + ), + ), + 'pageData' => array( + 'offsets' => array( + 'total' => 1, + 'next' => 0, + ), + 'bean' => array( + 'moduleDir' => 'Foo', + ), + ), + ), + ); + + $sugarSpot = $this->getMock('SugarSpot', array('_performSearch')); + $sugarSpot->expects($this->any()) + ->method('_performSearch') + ->will($this->returnValue($result)); + + $returnValue = $sugarSpot->searchAndDisplay('',''); + + $this->assertNotContains('
Foo
',$returnValue); + $this->assertContains('
Bar
',$returnValue); + } +} diff --git a/tests/include/Smarty/plugins/FunctionMultienumToArrayTest.php b/tests/include/Smarty/plugins/FunctionMultienumToArrayTest.php new file mode 100755 index 00000000..181f5452 --- /dev/null +++ b/tests/include/Smarty/plugins/FunctionMultienumToArrayTest.php @@ -0,0 +1,55 @@ +_smarty = new Sugar_Smarty; + } + + public function providerPassedString() + { + return array( + array("Employee^,^Boss","Cold Call",array('Employee','Boss')), + array("^Employee^,^Boss^","Cold Call",array('Employee','Boss')), + array("^Employee^","Cold Call",array('Employee')), + array("Employee","Cold Call",array('Employee')), + array("","^Cold Call^",array("Cold Call")), + array(array("Employee"),"Cold Call",array("Employee")), + array(NULL,array("Employee"),array("Employee")), + ); + } + + /** + * @group bug21574 + * @dataProvider providerPassedString + */ + public function testPassedString( + $string, + $default, + $result + ) + { + $params = array(); + $params['string'] = $string; + $params['default'] = $default; + + $this->assertEquals($result, smarty_function_multienum_to_array($params, $this->_smarty)); + } + + public function testAssignSmartyVariable() + { + $params = array(); + $params['string'] = "^Employee^"; + $params['default'] = "Cold Call"; + $params['assign'] = "multi"; + smarty_function_multienum_to_array($params, $this->_smarty); + + $this->assertEquals( + $this->_smarty->get_template_vars($params['assign']), + array("Employee") + ); + } +} \ No newline at end of file diff --git a/tests/include/Smarty/plugins/FunctionSugarHelpTest.php b/tests/include/Smarty/plugins/FunctionSugarHelpTest.php new file mode 100755 index 00000000..881485ae --- /dev/null +++ b/tests/include/Smarty/plugins/FunctionSugarHelpTest.php @@ -0,0 +1,45 @@ +_smarty = new Sugar_Smarty; + } + + public function providerSpecialCharactersHandledInTextParameter() + { + return array( + array( + 'dog "the" bounty hunter & friends are cool', + 'dog "the" bounty hunter & friends are <b>cool</b>', + ), + array( + "dog 'the' bounty hunter", + "dog \'the\' bounty hunter" + ), + ); + } + + /** + * @dataProvider providerSpecialCharactersHandledInTextParameter + */ + public function testSpecialCharactersHandledInTextParameter( + $string, + $returnedString + ) + { + $this->assertContains($returnedString, smarty_function_sugar_help(array('text'=>$string),$this->_smarty)); + } + + public function testExtraParametersAreAdded() + { + $string = 'my string'; + + $output = smarty_function_sugar_help(array('text'=>$string,'foo'=>'bar'),$this->_smarty); + + $this->assertContains(",foo,bar",$output); + } +} diff --git a/tests/include/Smarty/plugins/FunctionSugarLinkTest.php b/tests/include/Smarty/plugins/FunctionSugarLinkTest.php new file mode 100755 index 00000000..7be1ba69 --- /dev/null +++ b/tests/include/Smarty/plugins/FunctionSugarLinkTest.php @@ -0,0 +1,82 @@ +_smarty = new Sugar_Smarty; + } + + public function testReturnModuleLinkOnly() + { + $string = 'my string'; + + $output = smarty_function_sugar_link( + array('module'=>'Dog','link_only'=>'1'), + $this->_smarty); + + $this->assertContains("index.php?module=Dog&action=index",$output); + } + + public function testReturnModuleLinkWithAction() + { + $output = smarty_function_sugar_link( + array('module'=>'Dog','action'=>'cat','link_only'=>'1'), + $this->_smarty); + + $this->assertContains("index.php?module=Dog&action=cat",$output); + } + + public function testReturnModuleLinkWithActionAndExtraParams() + { + $output = smarty_function_sugar_link( + array('module'=>'Dog','action'=>'cat','extraparams'=>'foo=bar','link_only'=>'1'), + $this->_smarty); + + $this->assertContains("index.php?module=Dog&action=cat&foo=bar",$output); + } + + /** + * @group bug33909 + */ + public function testReturnLinkWhenPassingData() + { + $data = array( + '63edeacd-6ba5-b658-5e2a-4af9a5d682be', + 'http://localhost', + 'all', + 'iFrames', + 'Foo', + ); + + + $output = smarty_function_sugar_link( + array('module'=>'Dog','data'=>$data,'link_only'=>'1'), + $this->_smarty); + + $this->assertContains("index.php?module=iFrames&action=index&record=63edeacd-6ba5-b658-5e2a-4af9a5d682be&tab=true",$output); + } + + public function testCreatingFullLink() + { + $output = smarty_function_sugar_link( + array( + 'module'=>'Dog', + 'action'=>'cat', + 'id'=>'foo1', + 'class'=>'foo4', + 'style'=>'color:red;', + 'title'=>'foo2', + 'accesskey'=>'B', + 'options'=>'scope="row"', + 'label'=>'foo3', + ), + $this->_smarty); + + $this->assertContains( + '
foo3',$output); + + } +} diff --git a/tests/include/Smarty/plugins/FunctionSugarTranslateTest.php b/tests/include/Smarty/plugins/FunctionSugarTranslateTest.php new file mode 100755 index 00000000..40f749e4 --- /dev/null +++ b/tests/include/Smarty/plugins/FunctionSugarTranslateTest.php @@ -0,0 +1,59 @@ +setModString('LBL_TEST_JS_ESCAPED_STRING', $string, 'Contacts'); + $langpack->save(); + + $smarty = new Sugar_Smarty; + + $this->assertEquals($returnedString, smarty_function_sugar_translate( + array( + 'label' => 'LBL_TEST_JS_ESCAPED_STRING', + 'module' => 'Contacts', + 'for_js' => true, + ), + $smarty) + ); + } +} diff --git a/tests/include/SubPanel/Bug40171Test.php b/tests/include/SubPanel/Bug40171Test.php new file mode 100755 index 00000000..25b91aa2 --- /dev/null +++ b/tests/include/SubPanel/Bug40171Test.php @@ -0,0 +1,136 @@ +bean = new Contact(); + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + + foreach ($this->filename_check as $filename) { + @unlink($filename); + } + require_once('ModuleInstall/ModuleInstaller.php'); + $moduleInstaller = new ModuleInstaller(); + $moduleInstaller->silent = true; // make sure that the ModuleInstaller->log() function doesn't echo while rebuilding the layoutdefs + $moduleInstaller->rebuild_layoutdefs(); + } + + public function testSubpanelOverride() + { + // Create Subpanel 1 + $subpanel_1 = array( + 'order' => 100, + 'module' => 'Cases', + 'subpanel_name' => 'default', + 'sort_order' => 'asc', + 'sort_by' => 'id', + 'title_key' => 'LBL_CONTACTS_CASES_1_FROM_CASES_TITLE', + 'get_subpanel_data' => 'contacts_cases_1', + 'top_buttons' => + array ( + 0 => array ( + 'widget_class' => 'SubPanelTopButtonQuickCreate', + ), + 1 => array ( + 'widget_class' => 'SubPanelTopSelectButton', + 'mode' => 'MultiSelect', + ), + ), + ); + $subpanel_list_fields_1['list_fields'] = array ( + 'priority' => + array ( + 'type' => 'enum', + 'vname' => 'LBL_PRIORITY', + 'sortable' => false, + 'width' => '10%', + 'default' => true, + ), + ); + $subpanel_def_1 = new aSubPanel("contacts_cases_1", $subpanel_1, $this->bean); + $subpanel_1 = new SubPanel('Contacts', 'fab4', $subpanel_def_1->_instance_properties['subpanel_name'], $subpanel_def_1); + $subpanel_1->saveSubPanelDefOverride($subpanel_def_1, 'list_fields', $subpanel_list_fields_1); + + $path_1 = 'custom/modules/'. $subpanel_def_1->_instance_properties['module'] . '/metadata/subpanels'; + $filename_1 = $subpanel_def_1->parent_bean->object_name . "_subpanel_" . $subpanel_def_1->name; + $extname_1 = '_override'.$subpanel_def_1->parent_bean->object_name . "_subpanel_" . $subpanel_def_1->name; + + // Create SubPane 2 + $subpanel_2 = array( + 'order' => 100, + 'module' => 'Cases', + 'subpanel_name' => 'default', + 'sort_order' => 'asc', + 'sort_by' => 'id', + 'title_key' => 'LBL_CONTACTS_CASES_2_FROM_CASES_TITLE', + 'get_subpanel_data' => 'contacts_cases_2', + 'top_buttons' => + array ( + 0 => array ( + 'widget_class' => 'SubPanelTopButtonQuickCreate', + ), + 1 => array ( + 'widget_class' => 'SubPanelTopSelectButton', + 'mode' => 'MultiSelect', + ), + ), + ); + $subpanel_list_fields_2 = array ( + 'case_number' => + array ( + 'vname' => 'LBL_LIST_NUMBER', + 'width' => '6%', + 'default' => true, + ), + ); + $subpanel_def_2 = new aSubPanel("contacts_cases_2", $subpanel_2, $this->bean); + $subpanel_2 = new SubPanel('Contacts', 'fab4', $subpanel_def_2->_instance_properties['subpanel_name'], $subpanel_def_2); + $subpanel_2->saveSubPanelDefOverride($subpanel_def_2, 'list_fields', $subpanel_list_fields_2); + + $path_2 = 'custom/modules/'. $subpanel_def_2->_instance_properties['module'] . '/metadata/subpanels'; + $filename_2 = $subpanel_def_1->parent_bean->object_name . "_subpanel_" . $subpanel_def_2->name; + $extname_2 = '_override'.$subpanel_def_1->parent_bean->object_name . "_subpanel_" . $subpanel_def_2->name; + + // Check files genertaed by subpanel overriding : layout override and subpanel overire + $this->filename_check[] = 'custom/Extension/modules/'. $subpanel_def_1->parent_bean->module_dir . "/Ext/Layoutdefs/$extname_1.php"; + $this->assertTrue(file_exists(end($this->filename_check))); + $this->filename_check[] = $path_1.'/' . $filename_1 .'.php'; + $this->assertTrue(file_exists(end($this->filename_check))); + $this->filename_check[] = 'custom/Extension/modules/'. $subpanel_def_2->parent_bean->module_dir . "/Ext/Layoutdefs/$extname_2.php"; + $this->assertTrue(file_exists(end($this->filename_check))); + $this->filename_check[] = $path_2.'/' . $filename_2 .'.php'; + $this->assertTrue(file_exists(end($this->filename_check))); + + // laout_defs are reloaded in saveSubPanelDefOverride method, we lauched it + global $layout_defs; + + // Check override_subpanel_name are differents + $this->assertTrue(isset($layout_defs['Contacts']['subpanel_setup']['contacts_cases_1']['override_subpanel_name'])); + $this->assertTrue(isset($layout_defs['Contacts']['subpanel_setup']['contacts_cases_2']['override_subpanel_name'])); + $this->assertNotEquals($layout_defs['Contacts']['subpanel_setup']['contacts_cases_1']['override_subpanel_name'], $layout_defs['Contacts']['subpanel_setup']['contacts_cases_2']['override_subpanel_name']); + + } + + +} diff --git a/tests/include/SubPanel/Bug41738Test.php b/tests/include/SubPanel/Bug41738Test.php new file mode 100755 index 00000000..fa7fd922 --- /dev/null +++ b/tests/include/SubPanel/Bug41738Test.php @@ -0,0 +1,106 @@ +bean = new Opportunity(); + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + } + + public function testSubpanelCollectionWithSpecificQuery() + { + $subpanel = array( + 'order' => 20, + 'sort_order' => 'desc', + 'sort_by' => 'date_entered', + 'type' => 'collection', + 'subpanel_name' => 'history', //this values is not associated with a physical file. + 'top_buttons' => array(), + 'collection_list' => array( + 'meetings' => array( + 'module' => 'Meetings', + 'subpanel_name' => 'ForHistory', + 'get_subpanel_data' => 'function:subpanelCollectionWithSpecificQueryMeetings', + 'generate_select'=>false, + 'function_parameters' => array( + 'bean_id'=>$this->bean->id, + 'import_function_file' => __FILE__ + ), + ), + 'tasks' => array( + 'module' => 'Tasks', + 'subpanel_name' => 'ForHistory', + 'get_subpanel_data' => 'function:subpanelCollectionWithSpecificQueryTasks', + 'generate_select'=>false, + 'function_parameters' => array( + 'bean_id'=>$this->bean->id, + 'import_function_file' => __FILE__ + ), + ), + ) + ); + $subpanel_def = new aSubPanel("testpanel", $subpanel, $this->bean); + $query = $this->bean->get_union_related_list($this->bean, "", '', "", 0, 5, -1, 0, $subpanel_def); + $result = $this->bean->db->query($query["query"]); + $this->assertTrue($result != false, "Bad query: {$query['query']}"); + } + + +} + + +function subpanelCollectionWithSpecificQueryMeetings($params) +{ + $query = "SELECT meetings.id , meetings.name , meetings.status , 0 reply_to_status , ' ' contact_name , ' ' contact_id , ' ' contact_name_owner , ' ' contact_name_mod , meetings.parent_id , meetings.parent_type , meetings.date_modified , jt1.user_name assigned_user_name , jt1.created_by assigned_user_name_owner , 'Users' assigned_user_name_mod, ' ' filename , meetings.assigned_user_id , 'meetings' panel_name + FROM meetings + LEFT JOIN users jt1 ON jt1.id= meetings.assigned_user_id AND jt1.deleted=0 AND jt1.deleted=0 + WHERE ( meetings.parent_type = \"Opportunities\" + AND meetings.deleted=0 + AND (meetings.status='Held' OR meetings.status='Not Held') + AND meetings.parent_id IN( + SELECT o.id + FROM opportunities o + INNER JOIN opportunities_contacts oc on o.id = oc.opportunity_id + AND oc.contact_id = '".$params['bean_id']."') + )"; + + return $query ; +} + +function subpanelCollectionWithSpecificQueryTasks($params) +{ + $query = "SELECT tasks.id , tasks.name , tasks.status , 0 reply_to_status , ' ' contact_name , ' ' contact_id , ' ' contact_name_owner , ' ' contact_name_mod , tasks.parent_id , tasks.parent_type , tasks.date_modified , jt1.user_name assigned_user_name , jt1.created_by assigned_user_name_owner , 'Users' assigned_user_name_mod, ' ' filename , tasks.assigned_user_id , 'tasks' panel_name + FROM tasks + LEFT JOIN users jt1 ON jt1.id= tasks.assigned_user_id AND jt1.deleted=0 AND jt1.deleted=0 + WHERE ( tasks.parent_type = \"Opportunities\" + AND tasks.deleted=0 + AND (tasks.status='Completed' OR tasks.status='Deferred') + AND tasks.parent_id IN( + SELECT o.id + FROM opportunities o + INNER JOIN opportunities_contacts oc on o.id = oc.opportunity_id + AND oc.contact_id = '".$params['bean_id']."') + )"; + + return $query ; +} + + diff --git a/tests/include/SubPanel/GetUnionRelatedTest.php b/tests/include/SubPanel/GetUnionRelatedTest.php new file mode 100755 index 00000000..c42f6311 --- /dev/null +++ b/tests/include/SubPanel/GetUnionRelatedTest.php @@ -0,0 +1,79 @@ +bean = new Contact(); + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + } + + public function testGetUnionRelatedList() + { + $subpanel = array( + 'order' => 20, + 'sort_order' => 'desc', + 'sort_by' => 'date_entered', + 'type' => 'collection', + 'subpanel_name' => 'history', //this values is not associated with a physical file. + 'top_buttons' => array(), + 'collection_list' => array( + 'meetings' => array( + 'module' => 'Meetings', + 'subpanel_name' => 'ForHistory', + 'get_subpanel_data' => 'meetings', + ), + 'emails' => array( + 'module' => 'Emails', + 'subpanel_name' => 'ForHistory', + 'get_subpanel_data' => 'emails', + 'get_distinct_data' => true, + ), + 'linkedemails_contacts' => array( + 'module' => 'Emails', + 'subpanel_name' => 'ForHistory', + 'generate_select'=>true, + 'get_distinct_data' => true, + 'get_subpanel_data' => 'function:GetUnionRelatedTest_get_select', + 'function_parameters' => array('import_function_file' => __FILE__), + ), + ) + ); + $subpanel_def = new aSubPanel("testpanel", $subpanel, $this->bean); + $query = $this->bean->get_union_related_list($this->bean, "", '', "", 0, 5, -1, 0, $subpanel_def); + $result = $this->bean->db->query($query["query"]); + $this->assertTrue($result != false, "Bad query: {$query["query"]}"); + } +} + +function GetUnionRelatedTest_get_select() +{ + $return_array['select']='SELECT DISTINCT emails.id'; + $return_array['from']='FROM emails '; + $return_array['join'] = " JOIN emails_email_addr_rel eear ON eear.email_id = emails.id AND eear.deleted=0 + JOIN email_addr_bean_rel eabr ON eabr.email_address_id=eear.email_address_id AND eabr.bean_module = 'Contacts' + AND eabr.deleted=0 AND eabr.bean_id = '1'"; + $return_array['where']=""; + $return_array['join_tables'] = array(); + return $return_array; +} diff --git a/tests/include/SugarEmailAddress/Bug40068Test.php b/tests/include/SugarEmailAddress/Bug40068Test.php new file mode 100755 index 00000000..ee7dd97f --- /dev/null +++ b/tests/include/SugarEmailAddress/Bug40068Test.php @@ -0,0 +1,39 @@ +assertRegExp($sea->regex,$email); + } + else { + $this->assertNotRegExp($sea->regex,$email); + } + } +} diff --git a/tests/include/SugarEmailAddress/SugarEmailAddressRegexTest.php b/tests/include/SugarEmailAddress/SugarEmailAddressRegexTest.php new file mode 100755 index 00000000..f1889165 --- /dev/null +++ b/tests/include/SugarEmailAddress/SugarEmailAddressRegexTest.php @@ -0,0 +1,32 @@ +assertRegExp($sea->regex,$email); + } + else { + $this->assertNotRegExp($sea->regex,$email); + } + } +} diff --git a/tests/include/SugarFields/Fields/Enum/SugarFieldEnumTest.php b/tests/include/SugarFields/Fields/Enum/SugarFieldEnumTest.php new file mode 100755 index 00000000..567d8269 --- /dev/null +++ b/tests/include/SugarFields/Fields/Enum/SugarFieldEnumTest.php @@ -0,0 +1,39 @@ + 'priority', + 'vname' => 'LBL_PRIORITY', + 'type' => 'enum', + 'options' => 'case_priority_dom', + 'len'=>25, + 'audited'=>true, + 'comment' => 'The priority of the case', + ); + $field_value = "P2"; + + require_once('include/SugarFields/SugarFieldHandler.php'); + $sfr = SugarFieldHandler::getSugarField('enum'); + + $this->assertEquals(trim($sfr->formatField($field_value,$fieldDef)),'Medium'); + } +} \ No newline at end of file diff --git a/tests/include/SugarFields/Fields/Relate/SugarFieldRelateTest.php b/tests/include/SugarFields/Fields/Relate/SugarFieldRelateTest.php new file mode 100755 index 00000000..dea43b9f --- /dev/null +++ b/tests/include/SugarFields/Fields/Relate/SugarFieldRelateTest.php @@ -0,0 +1,132 @@ +setPreference('default_locale_name_format','l f'); + + $vardef = array('name' => 'contact_name'); + $value = 'John Mertic'; + + $sfr = new SugarFieldRelate('relate'); + + $this->assertEquals( + $sfr->formatField($value,$vardef), + 'Mertic John' + ); + } + + /** + * @group bug35265 + */ + public function testFormatContactNameWithoutFirstName() + { + $GLOBALS['current_user']->setPreference('default_locale_name_format','l f'); + + $vardef = array('name' => 'contact_name'); + $value = 'Mertic'; + + $sfr = new SugarFieldRelate('relate'); + + $this->assertEquals( + trim($sfr->formatField($value,$vardef)), + 'Mertic' + ); + } + + /** + * @group bug35265 + */ + public function testFormatContactNameThatIsEmpty() + { + $GLOBALS['current_user']->setPreference('default_locale_name_format','l f'); + + $vardef = array('name' => 'contact_name'); + $value = ''; + + $sfr = new SugarFieldRelate('relate'); + + $this->assertEquals( + trim($sfr->formatField($value,$vardef)), + '' + ); + } + + public function testFormatOtherField() + { + $GLOBALS['current_user']->setPreference('default_locale_name_format','l f'); + + $vardef = array('name' => 'account_name'); + $value = 'John Mertic'; + + $sfr = new SugarFieldRelate('relate'); + + $this->assertEquals( + $sfr->formatField($value,$vardef), + 'John Mertic' + ); + } + + /** + * @group bug38548 + */ + public function testGetSearchViewSmarty(){ + $vardef = array ( + 'name' => 'assigned_user_id', + 'rname' => 'user_name', + 'id_name' => 'assigned_user_id', + 'vname' => 'LBL_ASSIGNED_TO_ID', + 'group'=>'assigned_user_name', + 'type' => 'relate', + 'table' => 'users', + 'module' => 'Users', + 'reportable'=>true, + 'isnull' => 'false', + 'dbType' => 'id', + 'audited'=>true, + 'comment' => 'User ID assigned to record', + 'duplicate_merge'=>'disabled' + ); + $displayParams = array(); + $sfr = new SugarFieldRelate('relate'); + $output = $sfr->getSearchViewSmarty(array(), $vardef, $displayParams, 0); + $this->assertContains('name="{$Array.assigned_user_id', $output, 'Testing that the name property is in the form for thr assigned_user_id field'); + + $vardef = array ( + 'name' => 'account_name', + 'rname' => 'name', + 'id_name' => 'account_id', + 'vname' => 'LBL_ACCOUNT_NAME', + 'type' => 'relate', + 'table' => 'accounts', + 'join_name'=>'accounts', + 'isnull' => 'true', + 'module' => 'Accounts', + 'dbType' => 'varchar', + 'link'=>'accounts', + 'len' => '255', + 'source'=>'non-db', + 'unified_search' => true, + 'required' => true, + 'importable' => 'required', + 'required' => true, + ); + $displayParams = array(); + $sfr = new SugarFieldRelate('relate'); + $output = $sfr->getSearchViewSmarty(array(), $vardef, $displayParams, 0); + $this->assertNotContains('name="{$Array.account_id', $output, 'Testing that the name property for account_id is not in the form.'); + } +} \ No newline at end of file diff --git a/tests/include/SugarFolders/Bug33404Test.php b/tests/include/SugarFolders/Bug33404Test.php new file mode 100755 index 00000000..f05df7bf --- /dev/null +++ b/tests/include/SugarFolders/Bug33404Test.php @@ -0,0 +1,74 @@ +_user = SugarTestUserUtilities::createAnonymousUser(); + $this->folder = new SugarFolder(); + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + + $GLOBALS['db']->query("DELETE FROM folders_subscriptions WHERE assigned_user_id='{$this->_user->id}'"); + + unset($this->folder); + } + + function testInsertFolderSubscription(){ + global $current_user; + + $id1 = create_guid(); + $id2 = create_guid(); + + $this->folder->insertFolderSubscription($id1,$this->_user->id); + $this->folder->insertFolderSubscription($id2,$this->_user->id); + + $result = $GLOBALS['db']->query("SELECT count(*) as cnt FROM folders_subscriptions where assigned_user_id='{$this->_user->id}'"); + $rs = $GLOBALS['db']->fetchByAssoc($result); + + $this->assertEquals(2, $rs['cnt'], "Could not insert folder subscriptions properly" ); + } + + + + function testClearSubscriptionsForFolder() + { + global $current_user; + + $random_user_id1 = create_guid(); + $random_user_id2 = create_guid(); + $random_user_id3 = create_guid(); + + $folderID = create_guid(); + + $this->folder->insertFolderSubscription($folderID,$random_user_id1); + $this->folder->insertFolderSubscription($folderID,$random_user_id2); + $this->folder->insertFolderSubscription($folderID,$random_user_id3); + + $result1 = $GLOBALS['db']->query("SELECT count(*) as cnt FROM folders_subscriptions where folder_id='{$folderID}' "); + $rs1 = $GLOBALS['db']->fetchByAssoc($result1); + $this->assertEquals(3, $rs1['cnt'], "Could not clear folder subscriptions, test setup failed while inserting folder subscriptionss"); + + //Test deletion of subscriptions. + $this->folder->clearSubscriptionsForFolder($folderID); + $result = $GLOBALS['db']->query("SELECT count(*) as cnt FROM folders_subscriptions where folder_id='{$folderID}' "); + $rs = $GLOBALS['db']->fetchByAssoc($result); + + $this->assertEquals(0, $rs['cnt'], "Could not clear folder subscriptions"); + } +} +?> \ No newline at end of file diff --git a/tests/include/SugarFolders/Bug33906Test.php b/tests/include/SugarFolders/Bug33906Test.php new file mode 100755 index 00000000..29cf21d1 --- /dev/null +++ b/tests/include/SugarFolders/Bug33906Test.php @@ -0,0 +1,54 @@ +_user = SugarTestUserUtilities::createAnonymousUser(); + $GLOBALS['current_user'] = $this->_user; + $this->folder = new SugarFolder(); + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + + $GLOBALS['db']->query("DELETE FROM folders_subscriptions WHERE assigned_user_id='{$this->_user->id}'"); + $GLOBALS['db']->query("DELETE FROM folders_subscriptions WHERE folder_id='{$this->folder->id}'"); + $GLOBALS['db']->query("DELETE FROM folders WHERE id='{$this->folder->id}'"); + + unset($this->folder); + } + + public function testSaveFolderNoSubscriptions() + { + global $current_user; + $this->folder->save(); + + $result = $GLOBALS['db']->query("SELECT count(*) as cnt FROM folders_subscriptions where folder_id='{$this->folder->id}'"); + $rs = $GLOBALS['db']->fetchByAssoc($result); + + $this->assertGreaterThan(0, $rs['cnt'], "Could not create folder subscriptions properly." ); + } + + public function testSaveFolderWithSubscriptions() + { + global $current_user; + $this->folder->save(FALSE); + + $result = $GLOBALS['db']->query("SELECT count(*) as cnt FROM folders_subscriptions where folder_id='{$this->folder->id}'"); + $rs = $GLOBALS['db']->fetchByAssoc($result); + + $this->assertEquals(0, $rs['cnt'], "Created folder subscriptions when none should have been created." ); + } +} \ No newline at end of file diff --git a/tests/include/SugarFolders/SugarFoldersTest.php b/tests/include/SugarFolders/SugarFoldersTest.php new file mode 100755 index 00000000..4e7d5c00 --- /dev/null +++ b/tests/include/SugarFolders/SugarFoldersTest.php @@ -0,0 +1,312 @@ +_user = SugarTestUserUtilities::createAnonymousUser(); + $GLOBALS['current_user'] = $this->_user; + $this->folder = new SugarFolder(); + $this->additionalFolders = array(); + $this->emails = array(); + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + + $GLOBALS['db']->query("DELETE FROM folders_subscriptions WHERE assigned_user_id='{$this->_user->id}'"); + $this->_clearFolder($this->folder->id); + + foreach ($this->additionalFolders as $additionalID) + $this->_clearFolder($additionalID); + + foreach ($this->emails as $emailID) + $GLOBALS['db']->query("DELETE FROM emails WHERE id='$emailID'"); + + unset($this->folder); + } + + /** + * Test the Set Folder method. + * + */ + function testSetFolder() + { + //Set folder + $this->folder->id = create_guid(); + $this->folder->new_with_id = TRUE; + + $fields = array('name' => 'TEST_FOLDER','parent_folder' => 'PRNT_FOLDER', + ); + + $this->folder->setFolder($fields); + + //Retrieve newly created folder + $error_message = "Unable to set folder."; + $this->folder->retrieve($this->folder->id); + + $this->assertEquals($fields['name'], $this->folder->name, $error_message ); + $this->assertEquals($fields['parent_folder'], $this->folder->parent_folder, $error_message ); + $this->assertEquals($this->_user->id, $this->folder->assign_to_id, $error_message ); + + //Check for folder subscriptions create for global user + $sub_ids = $this->folder->getSubscriptions($GLOBALS['current_user']); + $this->assertEquals(1, count($sub_ids), $error_message); + $this->assertEquals($this->folder->id, $sub_ids[0], $error_message); + + } + + /** + * Test sugar folder subscriptions: create, clear, insert, clear specific folder. + * + */ + function testFolderSubscriptions() + { + $this->_createNewSugarFolder(); + $error_message = "Unable to create|insert|delete sugar folder subscriptions."; + + //Clear subscriptions + $this->folder->clearSubscriptions(); + $subs = $this->folder->getSubscriptions($GLOBALS['current_user']); + $this->assertEquals(0, count($subs), $error_message); + + //Add a subscription + $this->folder->insertFolderSubscription($this->folder->id,$GLOBALS['current_user']->id); + $subs = $this->folder->getSubscriptions($GLOBALS['current_user']); + $this->assertEquals(1, count($subs), $error_message); + + //Clear subscriptions for a paricular folder + $this->folder->clearSubscriptionsForFolder($this->folder->id); + $subs = $this->folder->getSubscriptions($GLOBALS['current_user']); + $this->assertEquals(0, count($subs), $error_message); + } + + /** + * Test the getParentIDRecursive function which is used to find a grouping of folders. + * + */ + function testgetParentIDRecursive() + { + $f1 = new SugarFolder(); + $f12 = new SugarFolder(); + $f3 = new SugarFolder(); + + $f1->id = create_guid(); + $f1->new_with_id = TRUE; + + $f12->id = create_guid(); + $f12->new_with_id = TRUE; + + $f3->id = create_guid(); + $f3->new_with_id = TRUE; + + $f12->parent_folder = $f1->id; + $f1->save(); + $f12->save(); + $f3->save(); + + $this->additionalFolders[] = $f1->id; + $this->additionalFolders[] = $f12->id; + $this->additionalFolders[] = $f3->id; + + + $parentIDs = $this->folder->getParentIDRecursive($f12->id); //Includes itself in the return list. + $this->assertEquals(2, count($parentIDs), "Unable to retrieve parent ids recursively"); + + $parentIDs = $this->folder->getParentIDRecursive($f3->id); //Includes itself in the return list. + $this->assertEquals(1, count($parentIDs), "Unable to retrieve parent ids recursively"); + + //Find the children by going the other way. + $childrenArray = array(); + $this->folder->findAllChildren($f1->id,$childrenArray); + $this->assertEquals(1, count($childrenArray), "Unable to retrieve child ids recursively"); + + $childrenArray = array(); + $this->folder->findAllChildren($f3->id,$childrenArray); + $this->assertEquals(0, count($childrenArray), "Unable to retrieve child ids recursively"); + } + + /** + * Test to ensure that for a new user, the My Email, My Drafts, Sent Email, etc. folders can be retrieved. + * + */ + function testGetUserFolders() + { + $GLOBALS['mod_strings'] = return_module_language($GLOBALS['current_language'], "Emails"); + require_once('modules/Emails/EmailUI.php'); + $emailUI = new EmailUI(); + $emailUI->preflightUser($GLOBALS['current_user']); + $error_message = "Unable to get user folders"; + $rootNode = new ExtNode('',''); + + $folderOpenState = ""; + $ret = $this->folder->getUserFolders($rootNode, $folderOpenState, $GLOBALS['current_user'], true); + + $this->assertEquals(1, count($ret), $error_message); + $this->assertEquals($GLOBALS['mod_strings']['LNK_MY_INBOX'], $ret[0]['text'], $error_message); + //Should contain 'My Drafts' and 'My Sent Mail' + $this->assertEquals(2, count($ret[0]['children']), $error_message); + + } + + /** + * Test the addBean, getCountUnread,getCountItems functions. + * + */ + function testAddBean() + { + $emailParams = array('status' => 'unread'); + $email = $this->_createEmailObject($emailParams); + $this->emails[] = $email->id; + + $this->_createNewSugarFolder(); + + $cnt = $this->folder->getCountUnread($this->folder->id); + $this->assertEquals(0, $cnt, "Unable to execute addBean function properly."); + + $this->folder->addBean($email,$GLOBALS['current_user']); + + $cnt = $this->folder->getCountUnread($this->folder->id); + $this->assertEquals(1, $cnt, "Unable to execute addBean function properly."); + + //Create a second email obj with status read + $emailParams = array('status' => 'read'); + $email = $this->_createEmailObject($emailParams); + $this->emails[] = $email->id; + $this->folder->addBean($email,$GLOBALS['current_user']); + + $cnt = $this->folder->getCountItems($this->folder->id); + $this->assertEquals(2, $cnt, "Unable to execute getCountItems function properly."); + + + } + + /** + * Tests sugar folder methods that deal with emails. + * + */ + function testFolderEmailMethods() + { + + $emailParams = array('status' => 'read'); + $email = $this->_createEmailObject($emailParams); + $this->emails[] = $email->id; + + $this->_createNewSugarFolder(); + $this->folder->addBean($email,$GLOBALS['current_user']); + + $emailExists = $this->folder->checkEmailExistForFolder($email->id); + $this->assertTrue($emailExists, "Unable to check for emails with a specific folder"); + + //Remove the specific email from our folder. + + $this->folder->deleteEmailFromFolder($email->id); + $emailExists = $this->folder->checkEmailExistForFolder($email->id); + $this->assertFalse($emailExists, "Unable to check for emails with a specific folder."); + + //Move the Email bean from one folder to another + $f3 = new SugarFolder(); + $f3->id = create_guid(); + $f3->new_with_id = TRUE; + $f3->save(); + $this->additionalFolders[] = $f3->id; + + $this->folder->addBean($email,$GLOBALS['current_user']); + + $emailExists = $f3->checkEmailExistForFolder($email->id); + $this->assertFalse($emailExists); + + $this->folder->move($this->folder->id, $f3->id,$email->id); + $emailExists = $f3->checkEmailExistForFolder($email->id); + $this->assertTrue($emailExists, "Unable to move Emails bean to a different sugar folder"); + + } + + /** + * Test retreiving a list of emails for a particular folder. + * + */ + function testGetListItemsForEmailXML() + { + //Create the my Emails Folder + $GLOBALS['mod_strings'] = return_module_language($GLOBALS['current_language'], "Emails"); + require_once('modules/Emails/EmailUI.php'); + $emailUI = new EmailUI(); + $emailUI->preflightUser($GLOBALS['current_user']); + $error_message = "Unable to get list items for email."; + $rootNode = new ExtNode('',''); + + $folderOpenState = ""; + $ret = $this->folder->getUserFolders($rootNode, $folderOpenState, $GLOBALS['current_user'], true); + + $this->assertEquals(1, count($ret), $error_message); + $folderID = $ret[0]['id']; + + //Create the Email Object + $emailParams = array('status' => 'unread','assigned_user_id' => $GLOBALS['current_user']->id); + $email = $this->_createEmailObject($emailParams); + $this->emails[] = $email->id; + + //Add Email Object to My Email Folder + $my_email = new SugarFolder(); + $my_email->retrieve($folderID); + $my_email->addBean($email,$GLOBALS['current_user']); + + //Make sure the email was added to the folder. + $emailExists = $my_email->checkEmailExistForFolder($email->id); + $this->assertTrue($emailExists, $error_message); + //Get the list of emails. + $emailList = $my_email->getListItemsForEmailXML($folderID); + + $this->assertEquals($email->id,$emailList['out'][0]['uid'],$error_message ); + + } + + + function _createEmailObject($additionalParams = array() ) + { + global $timedate; + + $em = new Email(); + $em->name = 'tst_' . uniqid(); + $em->type = 'inbound'; + $em->intent = 'pick'; + $em->date_sent = $timedate->to_display_date_time(gmdate("Y-m-d H:i:s", (gmmktime() + (3600 * 24 * 2) ))) ; //Two days from today + + foreach ($additionalParams as $k => $v) + $em->$k = $v; + + $em->save(); + + return $em; + } + + function _createNewSugarFolder() + { + $this->folder->id = create_guid(); + $this->folder->new_with_id = TRUE; + $this->folder->name = "UNIT TEST"; + $this->folder->save(); + + } + + private function _clearFolder($folder_id) + { + $GLOBALS['db']->query("DELETE FROM folders_subscriptions WHERE assigned_user_id='{$this->_user->id}'"); + $GLOBALS['db']->query("DELETE FROM folders_subscriptions WHERE folder_id='{$folder_id}'"); + $GLOBALS['db']->query("DELETE FROM folders WHERE id='{$folder_id}'"); + } +} +?> \ No newline at end of file diff --git a/tests/include/SugarLogger/SugarLoggerTest.php b/tests/include/SugarLogger/SugarLoggerTest.php new file mode 100755 index 00000000..8d358b3e --- /dev/null +++ b/tests/include/SugarLogger/SugarLoggerTest.php @@ -0,0 +1,71 @@ +get('logger.level'); + if (!empty($level)) + $GLOBALS['log']->setLevel($level); + } + + public function providerWriteLogEntries() + { + return array( + array('debug','debug','foo1',true,'[DEBUG] foo1'), + array('debug','info','foo2',true,'[INFO] foo2'), + array('debug','warn','foo3',true,'[WARN] foo3'), + array('debug','error','foo4',true,'[ERROR] foo4'), + array('debug','fatal','foo5',true,'[FATAL] foo5'), + array('debug','security','foo6',true,'[SECURITY] foo6'), + array('fatal','warn','foo7',false,'[WARN] foo7'), + ); + } + + /** + * @dataProvider providerWriteLogEntries + */ + public function testWriteLogEntries( + $currentLevel, + $logLevel, + $logMessage, + $shouldMessageBeWritten, + $messageWritten + ) + { + $GLOBALS['log']->setLevel($currentLevel); + $GLOBALS['log']->$logLevel($logMessage); + + $config = SugarConfig::getInstance(); + $ext = $config->get('logger.file.ext'); + $logfile = $config->get('logger.file.name'); + $log_dir = $config->get('log_dir'); + $log_dir = $log_dir . (empty($log_dir)?'':'/'); + + $logFile = file_get_contents($log_dir . $logfile . $ext); + + if ( $shouldMessageBeWritten ) + $this->assertContains($messageWritten,$logFile); + else + $this->assertNotContains($messageWritten,$logFile); + } + + public function testAssertLogging() + { + $GLOBALS['log']->setLevel('debug'); + $GLOBALS['log']->assert('this was asserted true',true); + $GLOBALS['log']->assert('this was asserted false',false); + + $config = SugarConfig::getInstance(); + $ext = $config->get('logger.file.ext'); + $logfile = $config->get('logger.file.name'); + $log_dir = $config->get('log_dir'); + $log_dir = $log_dir . (empty($log_dir)?'':'/'); + + $logFile = file_get_contents($log_dir . $logfile . $ext); + + $this->assertContains('[DEBUG] this was asserted false',$logFile); + $this->assertNotContains('[DEBUG] this was asserted true',$logFile); + } +} diff --git a/tests/include/SugarObjects/BasicTemplateTest.php b/tests/include/SugarObjects/BasicTemplateTest.php new file mode 100755 index 00000000..9037929f --- /dev/null +++ b/tests/include/SugarObjects/BasicTemplateTest.php @@ -0,0 +1,70 @@ +_bean = new Basic; + } + + public function tearDown() + { + unset($this->_bean); + } + + public function testNameIsReturnedAsSummaryText() + { + $this->_bean->name = 'teststring'; + $this->assertEquals($this->_bean->get_summary_text(),$this->_bean->name); + } + + /** + * @group bug27361 + */ + public function testSettingImportableFieldDefAttributeTrueAsAString() + { + $this->_bean->field_defs['date_entered']['importable'] = 'true'; + $this->assertTrue(array_key_exists('date_entered',$this->_bean->get_importable_fields()), + 'Field date_entered should be importable'); + } + + /** + * @group bug27361 + */ + public function testSettingImportableFieldDefAttributeTrueAsABoolean() + { + $this->_bean->field_defs['date_entered']['importable'] = true; + $this->assertTrue(array_key_exists('date_entered',$this->_bean->get_importable_fields()), + 'Field date_entered should be importable'); + } + + /** + * @group bug27361 + */ + public function testSettingImportableFieldDefAttributeFalseAsAString() + { + $this->_bean->field_defs['date_entered']['importable'] = 'false'; + $this->assertFalse(array_key_exists('date_entered',$this->_bean->get_importable_fields()), + 'Field date_entered should not be importable'); + } + + /** + * @group bug27361 + */ + public function testSettingImportableFieldDefAttributeFalseAsABoolean() + { + $this->_bean->field_defs['date_entered']['importable'] = false; + $this->assertFalse(array_key_exists('date_entered',$this->_bean->get_importable_fields()), + 'Field date_entered should not be importable'); + } + + public function testGetBeanFieldsAsAnArray() + { + $this->_bean->date_entered = '2009-01-01 12:00:00'; + $array = $this->_bean->toArray(); + $this->assertEquals($array['date_entered'],$this->_bean->date_entered); + } +} diff --git a/tests/include/SugarObjects/PersonTemplateTest.php b/tests/include/SugarObjects/PersonTemplateTest.php new file mode 100755 index 00000000..bbfd8767 --- /dev/null +++ b/tests/include/SugarObjects/PersonTemplateTest.php @@ -0,0 +1,46 @@ +_bean = new Person; + $GLOBALS['current_user'] = SugarTestUserUtilities::createAnonymousUser(); + } + + public function tearDown() + { + unset($this->_bean); + unset($GLOBALS['current_user']); + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + } + + public function testNameIsReturnedAsSummaryText() + { + $GLOBALS['current_user']->setPreference('default_locale_name_format', 'l f'); + + $this->_bean->first_name = 'Test'; + $this->_bean->last_name = 'Contact'; + $this->_bean->title = ''; + $this->_bean->salutation = ''; + $this->assertEquals($this->_bean->get_summary_text(),'Contact Test'); + } + + /** + * @group bug38648 + */ + public function testNameIsReturnedAsSummaryTextWhenSalutationIsInvalid() + { + $GLOBALS['current_user']->setPreference('default_locale_name_format', 's l f'); + + $this->_bean->salutation = 'Tester'; + $this->_bean->first_name = 'Test'; + $this->_bean->last_name = 'Contact'; + $this->_bean->title = ''; + $this->assertEquals($this->_bean->get_summary_text(),'Contact Test'); + } +} diff --git a/tests/include/SugarObjects/SugarConfigTest.php b/tests/include/SugarObjects/SugarConfigTest.php new file mode 100755 index 00000000..249a76ed --- /dev/null +++ b/tests/include/SugarObjects/SugarConfigTest.php @@ -0,0 +1,213 @@ +_old_sugar_config = $GLOBALS['sugar_config']; + $GLOBALS['sugar_config'] = array(); + } + + public function tearDown() + { + $config = SugarConfig::getInstance(); + $config->clearCache(); + $GLOBALS['sugar_config'] = $this->_old_sugar_config; + } + + /** + * Stores a key/value pair in the config + * + * @internal override this in sub-classes if you are testing with the + * config data stored somewhere other than the $sugar_config + * super global + * @param string $key + * @param string $value + */ + private function _addKeyValueToConfig( + $key, + $value + ) + { + $GLOBALS['sugar_config'][$key] = $value; + } + + private function _generateRandomValue() + { + $this->_random = 'Some Random Foobar: ' . rand(10000, 20000); + return $this->_getLastRandomValue(); + } + + private function _getLastRandomValue() + { + return $this->_random; + } + + public function testGetInstanceReturnsASugarConfigObject() + { + $this->assertTrue(SugarConfig::getInstance() instanceOf SugarConfig, 'Returned object is not a SugarConfig object'); + } + + public function testGetInstanceReturnsASingleton() + { + $one = SugarConfig::getInstance(); + $two = SugarConfig::getInstance(); + $this->assertSame($one, $two); + } + + public function testReadsGlobalSugarConfigArray() + { + for ($i = 0; $i < 10; $i++) { + $anonymous_key = 'key-' . $i; + $random_value = rand(10000, 20000); + $rawConfigArray[$anonymous_key] = $random_value; + $this->_addKeyValueToConfig($anonymous_key, $random_value); + } + + $config = SugarConfig::getInstance(); + foreach ($rawConfigArray as $key => $value) { + $this->assertEquals( + $config->get($key), $value, + "SugarConfig::get({$key}) should be equal to {$value}, got " . $config->get($key) + ); + } + } + + public function testAllowDotNotationForSubValuesWithinTheConfig() + { + $random_value = 'Some Random Integer: ' . rand(1000, 2000); + $this->_addKeyValueToConfig('grandparent', array( + 'parent' => array( + 'child' => $random_value, + ), + )); + + $config = SugarConfig::getInstance(); + $this->assertEquals($random_value, $config->get('grandparent.parent.child')); + } + + public function testReturnsNullOnUnknownKey() + { + $config = SugarConfig::getInstance(); + $this->assertNull($config->get('unknown-and-unknowable')); + } + + public function testReturnsNullOnUnknownKeyWithinAHeirarchy() + { + $this->_addKeyValueToConfig('grandparent', array( + 'parent' => array( + 'child' => 'foobar', + ), + )); + $config= SugarConfig::getInstance(); + + $this->assertNull($config->get('some-unknown-grandparent.parent.child')); + $this->assertNull($config->get('grandparent.some-unknown-parent.child')); + $this->assertNull($config->get('grandparent.parent.some-unknown-child')); + } + + public function testAllowSpecifyingDefault() + { + $config = SugarConfig::getInstance(); + + $random = rand(10000, 20000); + $this->assertSame($random, $config->get('unknown-and-unknowable', $random)); + } + + public function testAllowSpecifyingDefaultForSubValues() + { + $this->_addKeyValueToConfig('grandparent', array( + 'parent' => array( + 'child' => 'foobar', + ), + )); + $config = SugarConfig::getInstance(); + + $this->assertEquals( + $this->_generateRandomValue(), + $config->get( + 'some-unknown-grandparent.parent.child', + $this->_getLastRandomValue() + ) + ); + $this->assertEquals( + $this->_generateRandomValue(), + $config->get( + 'grandparent.some-unknown-parent.child', + $this->_getLastRandomValue() + ) + ); + $this->assertEquals( + $this->_generateRandomValue(), + $config->get( + 'grandparent.parent.some-unknown-child', + $this->_getLastRandomValue() + ) + ); + } + + public function testStoresValuesInMemoryAfterFirstLookup() + { + $this->_addKeyValueToConfig('foobar', 'barfoo'); + + $config = SugarConfig::getInstance(); + $this->assertEquals($config->get('foobar'), 'barfoo'); + + $this->_addKeyValueToConfig('foobar', 'foobar'); + $this->assertEquals($config->get('foobar'), 'barfoo', 'should still be equal "barfoo": got ' . $config->get('foobar')); + } + + public function testCanClearsCachedValues() + { + $this->_addKeyValueToConfig('foobar', 'barfoo'); + + $config = SugarConfig::getInstance(); + $this->assertEquals($config->get('foobar'), 'barfoo', 'sanity check'); + $this->_addKeyValueToConfig('foobar', 'foobar'); + $this->assertEquals($config->get('foobar'), 'barfoo', 'sanity check'); + + $config->clearCache(); + $this->assertEquals($config->get('foobar'), 'foobar', 'after clearCache() call, new value should be used'); + } + + public function testCanCherryPickKeyToClear() + { + $this->_addKeyValueToConfig('foobar', 'barfoo'); + $this->_addKeyValueToConfig('barfoo', 'barfoo'); + + $config = SugarConfig::getInstance(); + $this->assertEquals($config->get('foobar'), 'barfoo', 'sanity check, got: ' . $config->get('foobar')); + $this->assertEquals($config->get('barfoo'), 'barfoo', 'sanity check'); + + $this->_addKeyValueToConfig('foobar', 'foobar'); + $this->_addKeyValueToConfig('barfoo', 'foobar'); + $this->assertEquals($config->get('foobar'), 'barfoo', 'should still be equal to "barfoo", got: ' . $config->get('barfoo')); + $this->assertEquals($config->get('barfoo'), 'barfoo', 'should still be equal to "barfoo", got: ' . $config->get('barfoo')); + + $config->clearCache('barfoo'); + $this->assertEquals($config->get('barfoo'), 'foobar', 'should be equal to "foobar" after cherry picked for clearing'); + $this->assertEquals($config->get('foobar'), 'barfoo', 'should not be effected by cherry picked clearCache() call'); + } + + public function testDemonstrateGrabbingSiblingNodes() + { + $this->_addKeyValueToConfig('foobar', array( + 'foo' => array( + array( + 'first' => 'one', + ), + array( + 'first' => 'uno', + ), + ), + )); + + $config = SugarConfig::getInstance(); + $this->assertEquals($config->get('foobar.foo.0.first'), 'one'); + $this->assertEquals($config->get('foobar.foo.1.first'), 'uno'); + } +} + diff --git a/tests/include/SugarObjects/SugarRegistryTest.php b/tests/include/SugarObjects/SugarRegistryTest.php new file mode 100755 index 00000000..d92ef2d6 --- /dev/null +++ b/tests/include/SugarObjects/SugarRegistryTest.php @@ -0,0 +1,91 @@ +_old_reporting = error_reporting(E_ALL); + $this->_old_globals = $GLOBALS; + unset($GLOBALS); + } + + public function tearDown() + { + error_reporting($this->_old_reporting); + $GLOBALS = $this->_old_globals; + unset($this->_old_globals); + } + + public function testGetInstanceReturnsAnInstanceOfSugarRegistry() + { + $this->assertTrue(SugarRegistry::getInstance() instanceOf SugarRegistry,'Returned object is not a SugarRegistry instance'); + } + + public function testGetInstanceReturnsSameObject() + { + $one = SugarRegistry::getInstance(); + $two = SugarRegistry::getInstance(); + $this->assertSame($one, $two); + } + + public function testParameterPassedToGetInstanceSpecifiesInstanceName() + { + $foo1 = SugarRegistry::getInstance('foo'); + $foo2 = SugarRegistry::getInstance('foo'); + $this->assertSame($foo1, $foo2); + + $bar = SugarRegistry::getInstance('bar'); + $this->assertNotSame($foo1, $bar); + } + + public function testCanSetAndGetValues() + { + $random = rand(100, 200); + $r = SugarRegistry::getInstance(); + $r->integer = $random; + $this->assertEquals($random, $r->integer); + $this->assertEquals($random, SugarRegistry::getInstance()->integer); + } + + public function testIssetReturnsTrueFalse() + { + $r = SugarRegistry::getInstance(); + $this->assertFalse(isset($r->foo)); + $this->assertFalse(isset(SugarRegistry::getInstance()->foo)); + + $r->foo = 'bar'; + $this->assertTrue(isset($r->foo)); + $this->assertTrue(isset(SugarRegistry::getInstance()->foo)); + } + + public function testUnsetRemovesValueFromRegistry() + { + $r = SugarRegistry::getInstance(); + $r->foo = 'bar'; + unset($r->foo); + $this->assertFalse(isset($r->foo)); + $this->assertFalse(isset(SugarRegistry::getInstance()->foo)); + } + + public function testReturnsNullOnAnyUnknownValue() + { + $r = SugarRegistry::getInstance(); + $this->assertNull($r->unknown); + $this->assertNull(SugarRegistry::getInstance()->unknown); + } + + public function testAddToGlobalsPutsRefsToAllRegistryObjectsInGlobalSpace() + { + $r = SugarRegistry::getInstance(); + $r->foo = 'bar'; + + $this->assertFalse(isset($GLOBALS['foo']), 'sanity check'); + $r->addToGlobals(); + $this->assertTrue(isset($GLOBALS['foo'])); + } +} + diff --git a/tests/include/SugarTheme/SugarThemeRegistryTest.php b/tests/include/SugarTheme/SugarThemeRegistryTest.php new file mode 100755 index 00000000..1b3444a3 --- /dev/null +++ b/tests/include/SugarTheme/SugarThemeRegistryTest.php @@ -0,0 +1,129 @@ +_themeName = SugarTestThemeUtilities::createAnonymousTheme(); + + SugarThemeRegistry::buildRegistry(); + } + + public function tearDown() + { + SugarTestThemeUtilities::removeAllCreatedAnonymousThemes(); + } + + public function testThemesRegistered() + { + $this->assertTrue(SugarThemeRegistry::exists($this->_themeName)); + } + + public function testGetThemeObject() + { + $object = SugarThemeRegistry::get($this->_themeName); + + $this->assertType('SugarTheme',$object); + $this->assertEquals($object->__toString(),$this->_themeName); + } + + public function testSetCurrentTheme() + { + SugarThemeRegistry::set($this->_themeName); + + $this->assertType('SugarTheme',SugarThemeRegistry::current()); + $this->assertEquals(SugarThemeRegistry::current()->__toString(),$this->_themeName); + } + + public function testInListOfAvailableThemes() + { + if ( isset($GLOBALS['sugar_config']['disabled_themes']) ) { + $disabled_themes = $GLOBALS['sugar_config']['disabled_themes']; + unset($GLOBALS['sugar_config']['disabled_themes']); + } + + $themes = SugarThemeRegistry::availableThemes(); + $this->assertTrue(isset($themes[$this->_themeName])); + $themes = SugarThemeRegistry::unAvailableThemes(); + $this->assertTrue(!isset($themes[$this->_themeName])); + $themes = SugarThemeRegistry::allThemes(); + $this->assertTrue(isset($themes[$this->_themeName])); + + if ( isset($disabled_themes) ) + $GLOBALS['sugar_config']['disabled_themes'] = $disabled_themes; + } + + public function testDisabledThemeNotInListOfAvailableThemes() + { + if ( isset($GLOBALS['sugar_config']['disabled_themes']) ) { + $disabled_themes = $GLOBALS['sugar_config']['disabled_themes']; + unset($GLOBALS['sugar_config']['disabled_themes']); + } + + $GLOBALS['sugar_config']['disabled_themes'] = $this->_themeName; + + $themes = SugarThemeRegistry::availableThemes(); + $this->assertTrue(!isset($themes[$this->_themeName])); + $themes = SugarThemeRegistry::unAvailableThemes(); + $this->assertTrue(isset($themes[$this->_themeName])); + $themes = SugarThemeRegistry::allThemes(); + $this->assertTrue(isset($themes[$this->_themeName])); + + if ( isset($disabled_themes) ) + $GLOBALS['sugar_config']['disabled_themes'] = $disabled_themes; + } + + public function testCustomThemeLoaded() + { + $customTheme = SugarTestThemeUtilities::createAnonymousCustomTheme($this->_themeName); + + SugarThemeRegistry::buildRegistry(); + + $this->assertEquals( + SugarThemeRegistry::get($customTheme)->name, + 'custom ' . $customTheme + ); + } + + public function testDefaultThemedefFileHandled() + { + create_custom_directory('themes/default/'); + sugar_file_put_contents('custom/themes/default/themedef.php',' false);'); + + SugarThemeRegistry::buildRegistry(); + + $this->assertEquals( + SugarThemeRegistry::get($this->_themeName)->group_tabs, + false + ); + + unlink('custom/themes/default/themedef.php'); + } + + public function testClearCacheAllThemes() + { + SugarThemeRegistry::get($this->_themeName)->getCSSURL('style.css'); + $this->assertTrue(isset(SugarThemeRegistry::get($this->_themeName)->_cssCache['style.css']), + 'File style.css should exist in cache'); + + SugarThemeRegistry::clearAllCaches(); + SugarThemeRegistry::buildRegistry(); + + $this->assertFalse(isset(SugarThemeRegistry::get($this->_themeName)->_cssCache['style.css']), + 'File style.css shouldn\'t exist in cache'); + } + + /** + * @group bug35307 + */ + public function testOldThemeIsNotRecognized() + { + $themename = SugarTestThemeUtilities::createAnonymousOldTheme(); + + $this->assertNull(SugarThemeRegistry::get($themename)); + } +} diff --git a/tests/include/SugarTheme/SugarThemeTest.php b/tests/include/SugarTheme/SugarThemeTest.php new file mode 100755 index 00000000..65130fc0 --- /dev/null +++ b/tests/include/SugarTheme/SugarThemeTest.php @@ -0,0 +1,395 @@ +_themeDef = $themedef; + SugarThemeRegistry::add($this->_themeDef); + $this->_themeObject = SugarThemeRegistry::get($this->_themeDef['dirName']); + + $themedef = array(); + include('themes/'.SugarTestThemeUtilities::createAnonymousChildTheme($this->_themeObject->__toString()).'/themedef.php'); + + $this->_themeDefChild = $themedef; + SugarThemeRegistry::add($this->_themeDefChild); + $this->_themeObjectChild = SugarThemeRegistry::get($this->_themeDefChild['dirName']); + + // test assumes developerMode is off, so css minifying happens + if ( isset($GLOBALS['sugar_config']['developerMode']) ) + $this->_olddeveloperMode = $GLOBALS['sugar_config']['developerMode']; + $GLOBALS['sugar_config']['developerMode'] = false; + } + + public function testMagicIssetWorks() + { + $this->assertTrue(isset($this->_themeObject->dirName)); + } + + public function tearDown() + { + $themesToRemove = array($this->_themeObject->__toString(),$this->_themeObjectChild->__toString()); + + SugarTestThemeUtilities::removeAllCreatedAnonymousThemes(); + + if ( $this->_olddeveloperMode ) + $GLOBALS['sugar_config']['developerMode'] = $this->_olddeveloperMode; + else + unset($GLOBALS['sugar_config']['developerMode']); + } + + public function testCaching() + { + $this->_themeObject->getCSSURL("style.css"); + $themename = $this->_themeObject->__toString(); + $pathname = "cache/themes/{$themename}/css/style.css"; + + // test if it's in the local cache + $this->assertTrue(isset($this->_themeObject->_cssCache['style.css'])); + $this->assertEquals($this->_themeObject->_cssCache['style.css'],$pathname); + + // destroy object + $this->_themeObject->__destruct(); + unset($this->_themeObject); + + // now recreate object + SugarThemeRegistry::add($this->_themeDef); + $this->_themeObject = SugarThemeRegistry::get($this->_themeDef['dirName']); + + // should still be in local cache + $this->assertTrue(isset($this->_themeObject->_cssCache['style.css'])); + $this->assertEquals($this->_themeObject->_cssCache['style.css'],$pathname); + + // now, let's tell the theme we want to clear the cache on destroy + $this->_themeObject->clearCache(); + + // destroy object + $this->_themeObject->__destruct(); + unset($this->_themeObject); + + // now recreate object + SugarThemeRegistry::add($this->_themeDef); + $this->_themeObject = SugarThemeRegistry::get($this->_themeDef['dirName']); + + // should not be in local cache + $this->assertFalse(isset($this->_themeObject->_cssCache['style.css'])); + } + + public function testCreateInstance() + { + foreach ( $this->_themeDef as $key => $value ) + $this->assertEquals($this->_themeObject->$key,$value); + } + + public function testGetFilePath() + { + $this->assertEquals($this->_themeObject->getFilePath(), + 'themes/'.$this->_themeDef['name']); + } + + public function testGetImagePath() + { + $this->assertEquals($this->_themeObject->getImagePath(), + 'themes/'.$this->_themeDef['name'].'/images'); + } + + public function testGetCSSPath() + { + $this->assertEquals($this->_themeObject->getCSSPath(), + 'themes/'.$this->_themeDef['name'].'/css'); + } + + public function testGetCSS() + { + $matches = array(); + preg_match_all('/href="([^"]+)"/',$this->_themeObject->getCSS(),$matches); + $i = 0; + + $this->assertRegExp('/themes\/'.$this->_themeObject->__toString().'\/css\/yui.css/',$matches[1][$i++]); + $this->assertRegExp('/themes\/'.$this->_themeObject->__toString().'\/css\/deprecated.css/',$matches[1][$i++]); + $this->assertRegExp('/themes\/'.$this->_themeObject->__toString().'\/css\/style.css/',$matches[1][$i++]); + + $output = file_get_contents('cache/themes/'.$this->_themeObject->__toString().'/css/style.css'); + $this->assertRegExp('/h2\{display:inline\}/',$output); + } + + public function testGetCSSWithParams() + { + $matches = array(); + preg_match_all('/href="([^"]+)"/',$this->_themeObject->getCSS('blue','small'),$matches); + $i = 0; + + $this->assertRegExp('/themes\/'.$this->_themeObject->__toString().'\/css\/yui.css/',$matches[1][$i++]); + $this->assertRegExp('/themes\/'.$this->_themeObject->__toString().'\/css\/deprecated.css/',$matches[1][$i++]); + $this->assertRegExp('/themes\/'.$this->_themeObject->__toString().'\/css\/style.css/',$matches[1][$i++]); + + $output = file_get_contents('cache/themes/'.$this->_themeObject->__toString().'/css/style.css'); + $this->assertRegExp('/h2\{display:inline\}/',$output); + } + + public function testGetCSSWithCustomStyleCSS() + { + create_custom_directory('themes/'.$this->_themeObject->__toString().'/css/'); + sugar_file_put_contents('custom/themes/'.$this->_themeObject->__toString().'/css/style.css','h3 { color: red; }'); + + $matches = array(); + preg_match_all('/href="([^"]+)"/',$this->_themeObject->getCSS(),$matches); + $i = 0; + + $this->assertRegExp('/themes\/'.$this->_themeObject->__toString().'\/css\/yui.css/',$matches[1][$i++]); + $this->assertRegExp('/themes\/'.$this->_themeObject->__toString().'\/css\/deprecated.css/',$matches[1][$i++]); + $this->assertRegExp('/themes\/'.$this->_themeObject->__toString().'\/css\/style.css/',$matches[1][$i++]); + + $output = file_get_contents('cache/themes/'.$this->_themeObject->__toString().'/css/style.css'); + $this->assertRegExp('/h2\{display:inline\}h3\{color:red\}/',$output); + } + + public function testGetCSSWithParentTheme() + { + $matches = array(); + preg_match_all('/href="([^"]+)"/',$this->_themeObjectChild->getCSS(),$matches); + $i = 0; + + $this->assertRegExp('/themes\/'.$this->_themeObjectChild->__toString().'\/css\/yui.css/',$matches[1][$i++]); + $this->assertRegExp('/themes\/'.$this->_themeObjectChild->__toString().'\/css\/deprecated.css/',$matches[1][$i++]); + $this->assertRegExp('/themes\/'.$this->_themeObjectChild->__toString().'\/css\/style.css/',$matches[1][$i++]); + + $output = file_get_contents('cache/themes/'.$this->_themeObjectChild->__toString().'/css/style.css'); + $this->assertRegExp('/h2\{display:inline\}h3\{display:inline\}/',$output); + } + + public function testGetCSSURLWithInvalidFileSpecifed() + { + $this->assertFalse($this->_themeObject->getCSSURL('ThisFileDoesNotExist.css')); + } + + public function testGetCSSURLAddsJsPathIfSpecified() + { + // check one may not hit cache + $this->assertRegExp('/style\.css\?/',$this->_themeObject->getCSSURL('style.css')); + // check two definitely should hit cache + $this->assertRegExp('/style\.css\?/',$this->_themeObject->getCSSURL('style.css')); + // check three for the jspath not being added + $this->assertNotContains('?',$this->_themeObject->getCSSURL('style.css',false)); + } + + public function testGetJS() + { + $matches = array(); + preg_match_all('/src="([^"]+)"/',$this->_themeObject->getJS(),$matches); + $i = 0; + + $this->assertRegExp('/themes\/'.$this->_themeObject->__toString().'\/js\/style-min.js/',$matches[1][$i++]); + + $output = file_get_contents('cache/themes/'.$this->_themeObject->__toString().'/js/style-min.js'); + $this->assertRegExp('/var dog="cat";/',$output); + } + + public function testGetJSCustom() + { + create_custom_directory('themes/'.$this->_themeObject->__toString().'/js/'); + sugar_file_put_contents('custom/themes/'.$this->_themeObject->__toString().'/js/style.js','var x = 1;'); + + $matches = array(); + preg_match_all('/src="([^"]+)"/',$this->_themeObject->getJS(),$matches); + $i = 0; + + $this->assertRegExp('/themes\/'.$this->_themeObject->__toString().'\/js\/style-min.js/',$matches[1][$i++]); + + $output = file_get_contents('cache/themes/'.$this->_themeObject->__toString().'/js/style-min.js'); + $this->assertRegExp('/var dog="cat";/',$output); + $this->assertRegExp('/var x=1;/',$output); + } + + public function testGetJSWithParentTheme() + { + $matches = array(); + preg_match_all('/src="([^"]+)"/',$this->_themeObjectChild->getJS(),$matches); + $i = 0; + + $this->assertRegExp('/themes\/'.$this->_themeObjectChild->__toString().'\/js\/style-min.js/',$matches[1][$i++]); + + $output = file_get_contents('cache/themes/'.$this->_themeObjectChild->__toString().'/js/style-min.js'); + $this->assertRegExp('/var dog="cat";var bird="frog";/',$output); + } + + public function testGetJSURLWithInvalidFileSpecifed() + { + $this->assertFalse($this->_themeObject->getJSURL('ThisFileDoesNotExist.js')); + } + + public function testGetJSURLAddsJsPathIfSpecified() + { + // check one may not hit cache + $this->assertRegExp('/style-min\.js\?/',$this->_themeObject->getJSURL('style.js')); + // check two definitely should hit cache + $this->assertRegExp('/style-min\.js\?/',$this->_themeObject->getJSURL('style.js')); + // check three for the jspath not being added + $this->assertNotContains('?',$this->_themeObject->getJSURL('style.js',false)); + } + + public function testGetImageURL() + { + $this->assertEquals('themes/'.$this->_themeObject->__toString().'/images/Accounts.gif', + $this->_themeObject->getImageURL('Accounts.gif',false)); + } + + public function testGetImageURLWithInvalidFileSpecifed() + { + $this->assertFalse($this->_themeObject->getImageURL('ThisFileDoesNotExist.gif')); + } + + public function testGetImageURLCustom() + { + create_custom_directory('themes/'.$this->_themeObject->__toString().'/images/'); + sugar_touch('custom/themes/'.$this->_themeObject->__toString().'/images/Accounts.gif'); + + $this->assertEquals('custom/themes/'.$this->_themeObject->__toString().'/images/Accounts.gif', + $this->_themeObject->getImageURL('Accounts.gif',false)); + } + + public function testGetImageURLCustomDifferentExtension() + { + create_custom_directory('themes/'.$this->_themeObject->__toString().'/images/'); + sugar_touch('custom/themes/'.$this->_themeObject->__toString().'/images/Accounts.png'); + + $this->assertEquals('custom/themes/'.$this->_themeObject->__toString().'/images/Accounts.png', + $this->_themeObject->getImageURL('Accounts.gif',false)); + } + + public function testGetImageURLDefault() + { + $this->assertEquals('themes/default/images/Emails.gif',$this->_themeObject->getImageURL('Emails.gif',false)); + } + + public function testGetImageURLDefaultCustom() + { + create_custom_directory('themes/default/images/'); + sugar_touch('custom/themes/default/images/Emails.gif'); + + $this->assertEquals('custom/themes/default/images/Emails.gif', + $this->_themeObject->getImageURL('Emails.gif',false)); + + unlink('custom/themes/default/images/Emails.gif'); + } + + public function testGetImageURLNotFound() + { + $this->assertEquals('',$this->_themeObject->getImageURL('NoImageByThisName.gif',false)); + } + + public function testGetImageURLAddsJsPathIfSpecified() + { + // check one may not hit cache + $this->assertRegExp('/Accounts\.gif\?/',$this->_themeObject->getImageURL('Accounts.gif')); + // check two definitely should hit cache + $this->assertRegExp('/Accounts\.gif\?/',$this->_themeObject->getImageURL('Accounts.gif')); + // check three for the jspath not being added + $this->assertNotContains('?',$this->_themeObject->getImageURL('Accounts.gif',false)); + } + + public function testGetImageURLWithParentTheme() + { + $this->assertEquals('themes/'.$this->_themeObject->__toString().'/images/Accounts.gif', + $this->_themeObjectChild->getImageURL('Accounts.gif',false)); + } + + public function testGetTemplate() + { + $this->assertEquals('themes/'.$this->_themeObject->__toString().'/tpls/header.tpl', + $this->_themeObject->getTemplate('header.tpl')); + } + + public function testGetTemplateCustom() + { + create_custom_directory('themes/'.$this->_themeObject->__toString().'/tpls/'); + sugar_touch('custom/themes/'.$this->_themeObject->__toString().'/tpls/header.tpl'); + + $this->assertEquals('custom/themes/'.$this->_themeObject->__toString().'/tpls/header.tpl', + $this->_themeObject->getTemplate('header.tpl')); + } + + public function testGetTemplateDefaultCustom() + { + create_custom_directory('themes/default/tpls/'); + sugar_touch('custom/themes/default/tpls/SomeDefaultTemplate.tpl'); + + $this->assertEquals('custom/themes/default/tpls/SomeDefaultTemplate.tpl', + $this->_themeObject->getTemplate('SomeDefaultTemplate.tpl')); + + unlink('custom/themes/default/tpls/SomeDefaultTemplate.tpl'); + } + + public function testGetTemplateWithParentTheme() + { + $this->assertEquals('themes/'.$this->_themeObject->__toString().'/tpls/header.tpl', + $this->_themeObjectChild->getTemplate('header.tpl')); + } + + public function testGetTemplateNotFound() + { + $this->assertFalse($this->_themeObject->getTemplate('NoTemplateWithThisName.tpl')); + } + + public function testGetAllImages() + { + $images = $this->_themeObject->getAllImages(); + + $this->assertEquals( + $this->_themeObject->getImageURL('Emails.gif',false), + $images['Emails.gif']); + } + + public function testGetAllImagesWhenImageIsInParentTheme() + { + $images = $this->_themeObjectChild->getAllImages(); + + $this->assertEquals( + $this->_themeObjectChild->getImageURL('Accounts.gif',false), + $images['Accounts.gif']); + + $this->assertContains( + $this->_themeObject->getImagePath(), + $images['Accounts.gif']); + } + + public function testGetImageSpecifyingWidthAndHeightAndOtherAttributes() + { + $this->assertEquals( + $this->_themeObject->getImage('Emails','alt="foo"',20,30), + "_themeObject->getImageURL('Emails.gif') ."\" width=\"20\" height=\"30\" alt=\"foo\" />" + ); + + // check again to see if caching of the image size works as expected + $this->assertEquals( + $this->_themeObject->getImage('Emails','alt="foo"',30,40), + "_themeObject->getImageURL('Emails.gif') ."\" width=\"20\" height=\"30\" alt=\"foo\" />" + ); + } + + public function testGetImageDetectingImageHeightAndWidth() + { + $size = getimagesize($this->_themeObject->getImageURL('Contacts.gif',false)); + + $this->assertEquals( + $this->_themeObject->getImage('Contacts'), + "_themeObject->getImageURL('Contacts.gif') ."\" width=\"{$size[0]}\" height=\"{$size[1]}\" />" + ); + } + + public function testGetImageWithInvalidImage() + { + $this->assertFalse($this->_themeObject->getImage('ThisImageDoesNotExist')); + } +} diff --git a/tests/include/TimeDateTest.php b/tests/include/TimeDateTest.php new file mode 100755 index 00000000..2ab3f1af --- /dev/null +++ b/tests/include/TimeDateTest.php @@ -0,0 +1,783 @@ + '2005-10-25 07:00:00', "df" => 'd-m-Y', 'tz' => 'America/Los_Angeles', "display" => '25-10-2005', "dbdate" => "2005-10-25 00:00:00"), + // add times + array("db" => '2005-10-26 06:42:00', "df" => 'd-m-Y', "tf" => 'h.iA', 'tz' => 'America/Los_Angeles', "display" => '25-10-2005 11.42PM', "dbdate" => "2005-10-25 23:42:00"), + // GMT+0 timezone + array("db" => '2005-11-25 00:00:00', "df" => 'd-m-Y', 'tz' => 'Europe/London', "display" => '25-11-2005', "dbdate" => "2005-11-25 00:00:00"), + // GMT+1 + array("db" => '2005-11-24 23:00:00', "dbdate" => "2005-11-25", "df" => 'd;m;Y', 'tz' => 'Europe/Oslo', "display" => '25;11;2005', "dbdate" => "2005-11-25 00:00:00"), + // DST in effect + array("db" => '2005-10-24 23:00:00', "dbdate" => "2005-10-25", "df" => 'd-m-Y', 'tz' => 'Europe/London', "display" => '25-10-2005', "dbdate" => "2005-10-25 00:00:00"), + // different format + array("db" => '1997-10-25 07:00:00', "df" => 'Y-m-d', 'tz' => 'America/Los_Angeles', "display" => '1997-10-25', "dbdate" => "1997-10-25 00:00:00"), + array("db" => '1997-01-25 00:00:00', "df" => 'm-d-Y', 'tz' => 'Europe/London', "display" => '01-25-1997', "dbdate" => "1997-01-25 00:00:00"), + // with times + array("db" => '2005-10-25 10:42:24', "df" => 'd/m/Y', "tf" => "H:i:s", 'tz' => 'America/Los_Angeles', "display" => '25/10/2005 03:42:24', "dbdate" => "2005-10-25 03:42:24"), + array("db" => '2005-10-25 02:42:24', "df" => 'd/m/Y', "tf" => "H:i:s", 'tz' => 'Europe/London', "display" => '25/10/2005 03:42:24', "dbdate" => "2005-10-25 03:42:24"), + array("db" => '2005-10-25 01:42:24', "df" => 'd/m/Y', "tf" => "H:i:s", 'tz' => 'Asia/Jerusalem', "display" => '25/10/2005 03:42:24', "dbdate" => "2005-10-25 03:42:24"), + // FAIL! FIXME: same format leads to no TZ conversion + array("db" => '2005-10-25 10:42:24', "df" => 'Y-m-d', "tf" => "H:i:s", 'tz' => 'America/Los_Angeles', "display" => '2005-10-25 03:42:24', "dbdate" => "2005-10-25 03:42:24"), + // short times + array("db" => '2005-10-25 10:42:00', "df" => 'd/m/Y', "tf" => "H:i", 'tz' => 'America/Los_Angeles', "display" => '25/10/2005 03:42', "dbdate" => "2005-10-25 03:42:00"), + array("db" => '2005-10-25 22:00:00', "df" => 'd/m/Y', "tf" => "ha", 'tz' => 'America/Los_Angeles', "display" => '25/10/2005 03pm', "dbdate" => "2005-10-25 15:00:00"), + array("db" => '2005-10-25 10:00:00', "df" => 'd/m/Y', "tf" => "h", 'tz' => 'America/Los_Angeles', "display" => '25/10/2005 03', "dbdate" => "2005-10-25 03:00:00"), + array("db" => '2005-10-25 20:00:00', "df" => 'd/m/Y', "tf" => "H", 'tz' => 'America/Los_Angeles', "display" => '25/10/2005 13', "dbdate" => "2005-10-25 13:00:00"), + ); + + protected $time_tests = array( + // full time + array("db" => "11:45:00", "display" => "11:45"), + array("db" => "05:17:28", "tf" => "H.i.s", "display" => "05.17.28"), + // short ones + array("db" => "17:34:00", "tf" => "H:i", "display" => "17:34"), + array("db" => "11:42:00", "tf" => "h.iA", "display" => "11.42AM"), + array("db" => "15:00:00", "tf" => "ha", "display" => "03pm"), + array("db" => "15:00:00", "tf" => "H", "display" => "15"), + // FIXME: is this a valid format? it doesn't allow roundtrip + array("db" => "03:00:00", "tf" => "h", "display" => "03"), + // weirdo + array("db" => "16:42:34", "tf" => "s:i:H", "display" => "34:42:16"), + ); + + public function setUp() + { + $GLOBALS['current_user'] = SugarTestUserUtilities::createAnonymousUser(); + $this->time_date = new TimeDate(); + $this->_noUserCache(); + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + unset($this->time_date); + } + + protected function _noUserCache() + { + $this->time_date->allow_cache = false; + } + + protected function _setPrefs($datef, $timef, $tz) { + $GLOBALS['current_user']->setPreference('datef', $datef); + $GLOBALS['current_user']->setPreference('timef', $timef); + $GLOBALS['current_user']->setPreference('timezone', $tz); + // new object to avoid TZ caching + $this->time_date = new TimeDate(); + $this->_noUserCache(); + } + + protected function _dateOnly($datetime) + { + // FIXME: assumes dates have no spaces + $dt = explode(' ', $datetime); + return $dt[0]; + } + + protected function _timeOnly($datetime) + { + // FIXME: assumes dates have no spaces + $dt = explode(' ', $datetime); + if(count($dt) > 1) { + return $dt[1]; + } + return $datetime; + } + + /** + * test conversion from local datetime to DB datetime + */ + public function testToDbFormats() + { + foreach($this->date_tests as $datetest) { + $tf = isset($datetest["tf"]) ? $datetest["tf"] : self::DEFAULT_TIME_FORMAT; + $this->_setPrefs($datetest["df"], $tf, $datetest["tz"]); + $this->assertEquals($datetest["db"], + $this->time_date->to_db($datetest["display"]), + "Broken conversion for '{$datetest["df"]} $tf' with date '{$datetest["display"]}' and TZ {$datetest["tz"]}"); + } + } + + /** + * test conversion from full local datetime to DB date + */ + public function testToDbDateFormatsWithOffset() + { + foreach($this->date_tests as $datetest) { + $tf = isset($datetest["tf"]) ? $datetest["tf"] : self::DEFAULT_TIME_FORMAT; + $this->_setPrefs($datetest["df"], $tf, $datetest["tz"]); + $this->assertEquals( + $this->_dateOnly($datetest["db"]), + $this->time_date->to_db_date($datetest["display"], true), + "Broken conversion for '{$datetest["df"]} $tf' with date '{$datetest["display"]}' and TZ {$datetest["tz"]}"); + } + } + + /** + * test conversion from local date to DB date, no TZ handling + */ + public function testToDbDateFormatsNoOffset() + { + foreach($this->date_tests as $datetest) { + $tf = isset($datetest["tf"]) ? $datetest["tf"] : self::DEFAULT_TIME_FORMAT; + $this->_setPrefs($datetest["df"], $tf, $datetest["tz"]); + $this->assertEquals( + $this->_dateOnly($datetest["dbdate"]), + $this->time_date->to_db_date($this->_dateOnly($datetest["display"]), false), + "Broken conversion for '{$datetest["df"]} $tf' with date '{$datetest["display"]}' and TZ {$datetest["tz"]}"); + } + } + + /** + * test conversion from full local datetime to DB time + */ + public function testToDbTimeFormatsWithTz() + { + foreach($this->date_tests as $datetest) { + $tf = isset($datetest["tf"]) ? $datetest["tf"] : self::DEFAULT_TIME_FORMAT; + $this->_setPrefs($datetest["df"], $tf, $datetest["tz"]); + $this->assertEquals( + $this->_timeOnly($datetest["db"]), + $this->time_date->to_db_time($datetest["display"], true), + "Broken conversion for '{$datetest["df"]} $tf' with date '{$datetest["display"]}' and TZ {$datetest["tz"]}"); + } + } + + /** + * test conversion from local time to DB time, no TZ handling + */ + public function testToDbTimeFormatsNoTz() + { + foreach($this->time_tests as $datetest) { + $tf = isset($datetest["tf"]) ? $datetest["tf"] : self::DEFAULT_TIME_FORMAT; + $this->_setPrefs('Y-m-d', $tf, ''); + $this->assertEquals( + $datetest["db"], + $this->time_date->to_db_time($datetest["display"], false), + "Broken conversion for '$tf' with date '{$datetest["display"]}'"); + } + } + + /** + * test conversion from local date+time to DB date+time, no TZ handling + */ + public function testToDbDateTimeFormats() + { + foreach($this->date_tests as $datetest) { + $tf = isset($datetest["tf"]) ? $datetest["tf"] : self::DEFAULT_TIME_FORMAT; + $this->_setPrefs($datetest["df"], $tf, $datetest["tz"]); + $dt = explode(' ', $datetest["display"]); + if(count($dt) > 1) { + list($date, $time) = $dt; + } else { + $date = $dt[0]; + $z = new DateTime("@0", new DateTimeZone("GMT")); + $time = $z->format($tf); + } + $this->assertEquals( + explode(' ',$datetest["dbdate"]), + $this->time_date->to_db_date_time($date, $time), + "Broken conversion for '{$datetest["df"]} $tf' with date '{$datetest["display"]}' and TZ {$datetest["tz"]}"); + } + } + + + /** + * test conversion from DB date+time to local date+time with TZ handling + */ + public function testToDisplayDateTimeFormats() + { + foreach($this->date_tests as $datetest) { + if(!isset($datetest["tf"])) { + $tf = null; + } else { + $tf = $datetest["tf"]; + } + $df = $datetest["df"]." ".$tf; + $this->_setPrefs($datetest["df"], $tf, $datetest["tz"]); + $result = $this->time_date->to_display_date_time($datetest["db"], true, true, $GLOBALS['current_user']); + if(!isset($datetest["tf"])) { + $result = $this->_dateOnly($result); + } + $this->assertEquals( + $datetest["display"], + $result, + "Broken conversion for '$df' with date '{$datetest["db"]}' and TZ {$datetest["tz"]}"); + } + } + + /** + * test conversion from DB date+time to local date+time without TZ handling + */ + public function testToDisplayFormatsNoTz() + { + foreach($this->date_tests as $datetest) { + if(!isset($datetest["tf"])) { + $tf = null; + } else { + $tf = $datetest["tf"]; + } + $df = $datetest["df"]." ".$tf; + $this->_setPrefs($datetest["df"], $tf, $datetest["tz"]); + $result = $this->time_date->to_display($datetest["dbdate"], $this->time_date->get_db_date_time_format(), $df); + if(!isset($datetest["tf"])) { + $result = $this->_dateOnly($result); + } + $this->assertEquals( + $datetest["display"], + $result, + "Broken conversion for '$df' with date '{$datetest["db"]}' and TZ {$datetest["tz"]}"); + } + } + + /** + * test conversion from DB time to local time without TZ conversion + */ + public function testToDisplayTimeFormatsNoTZ() + { + foreach($this->time_tests as $datetest) { + $tf = isset($datetest["tf"]) ? $datetest["tf"] : self::DEFAULT_TIME_FORMAT; + $this->_setPrefs('Y-m-d', $tf, ''); + $this->assertEquals( + $datetest["display"], + $this->time_date->to_display_time($datetest["db"], true, false), + "Broken conversion for '$tf' with date '{$datetest["db"]}'"); + } + } + + /** + * test conversion from DB time to local time with TZ conversion + */ + public function testToDisplayTimeFormatsWithTZ() + { + foreach($this->date_tests as $datetest) { + if(!isset($datetest["tf"])) continue; + $this->_setPrefs($datetest["df"], $datetest["tf"], $datetest["tz"]); + $result = $this->time_date->to_display_time($datetest["db"], true, true); + $result = $this->_timeOnly($result); + $this->assertEquals( + $this->_timeOnly($datetest["display"]), + $result, + "Broken conversion for '{$datetest["tf"]}' with date '{$datetest["db"]}' and TZ {$datetest["tz"]}"); + } + } + + + /** + * test conversion from DB date to local date without TZ handling + */ + public function testToDisplayDateFormatsNoTz() + { + foreach($this->date_tests as $datetest) { + if(!isset($datetest["tf"])) { + $tf = null; + } else { + $tf = $datetest["tf"]; + } + $df = $datetest["df"]." ".$tf; + $this->_setPrefs($datetest["df"], $tf, $datetest["tz"]); + $result = $this->time_date->to_display_date($this->_dateOnly($datetest["dbdate"]), false); + $this->assertEquals( + $this->_dateOnly($datetest["display"]), + $this->_dateOnly($result), + "Broken conversion for '{$datetest["df"]}' with date '{$datetest["dbdate"]}' and TZ {$datetest["tz"]}"); + } + } + + /** + * test conversion from DB date to local date with TZ handling + */ + public function testToDisplayDateFormatsWithTz() + { + foreach($this->date_tests as $datetest) { + if(!isset($datetest["tf"])) { + $tf = null; + } else { + $tf = $datetest["tf"]; + } + $df = $datetest["df"]." ".$tf; + $this->_setPrefs($datetest["df"], $tf, $datetest["tz"]); + $result = $this->time_date->to_display_date($datetest["db"], true); + $this->assertEquals( + $this->_dateOnly($datetest["display"]), + $this->_dateOnly($result), + "Broken conversion for '{$datetest["df"]}' with date '{$datetest["dbdate"]}' and TZ {$datetest["tz"]}"); + } + } + + /** + * test midnight formatting + */ + public function testGetMidnight() + { + if(!is_callable(array($this->time_date, "get_default_midnight"))) { + $this->markTestSkipped("Method is no longer public"); + } + $times = array( + array("tf" => "H:i", "time" => "00:00"), + array("tf" => "H:i:s", "time" => "00:00:00"), + array("tf" => "h:i", "time" => "12:00"), + array("tf" => "h:i:s", "time" => "12:00:00"), + array("tf" => "h`iA", "time" => "12`00AM"), + array("tf" => "h`i`sa", "time" => "12`00`00am"), + ); + foreach($times as $timetest) { + $this->_setPrefs('', $timetest["tf"], "America/Los_Angeles"); + $this->assertEquals($timetest["time"], $this->time_date->get_default_midnight(true), + "Bad midnight value for {$timetest["time"]} format {$timetest["tf"]}"); + } + } + + public function testSwapFormatsWithTheSameDateFormat() + { + $original_date = '2005-12-25'; + $original_format = 'Y-m-d'; + $new_format = $original_format; + $expected_new_date = $original_date; + + $new_date = $this->time_date->swap_formats($original_date, + $original_format, $new_format); + + $this->assertEquals($expected_new_date, $new_date); + } + + public function testSwapFormatsFromMdyFormatToDmyFormat() + { + $original_date = '12-25-2005'; + $original_format = 'm-d-Y'; + $new_format = 'd-m-Y'; + $expected_new_date = '25-12-2005'; + + $new_date = $this->time_date->swap_formats($original_date, + $original_format, $new_format); + + $this->assertEquals($expected_new_date, $new_date, + "Convert from $original_format to $new_format failed."); + } + + public function testSwapFormatsWithTheSameDatetimeFormat() + { + $original_date = '2005-12-25 12:55:35'; + $original_format = 'Y-m-d H:i:s'; + $new_format = $original_format; + $expected_new_date = $original_date; + + $new_date = $this->time_date->swap_formats($original_date, + $original_format, $new_format); + + $this->assertEquals($expected_new_date, $new_date, + 'Same datetime format not returned.'); + } + + public function testSwapFormatsFromYmdhiFormatToYmdhisFormat() + { + $original_date = '2005-12-25 12:55'; + $original_format = 'Y-m-d H:i'; + $new_format = 'Y-m-d H:i:s'; + $expected_new_date = '2005-12-25 12:55:00'; + + $new_date = $this->time_date->swap_formats($original_date, + $original_format, $new_format); + + $this->assertEquals($expected_new_date, $new_date); + } + + public function testSwapFormatsFromYmdhiFormatToYmdhiaFormat() + { + $original = '2005-12-25 13:55'; + $original_format = 'Y-m-d H:i'; + $new_format = 'Y-m-d h:ia'; + $expected = '2005-12-25 01:55pm'; + + $new = $this->time_date->swap_formats($original, + $original_format, $new_format); + + $this->assertEquals($expected, $new); + } + + public function testAllDateFormatSwappingCombinations() + { + $orig_formats_and_dates = array( + 'Y-m-d' => '2006-12-23', + 'm-d-Y' => '12-23-2006', + 'd-m-Y' => '23-12-2006', + 'Y/m/d' => '2006/12/23', + 'm/d/Y' => '12/23/2006', + 'd/m/Y' => '23/12/2006'); + + $new_formats_and_dates = $orig_formats_and_dates; + + foreach($orig_formats_and_dates as $orig_format => $orig_date) + { + foreach($new_formats_and_dates as $new_format => $expected_date) + { + $new_date = $this->time_date->swap_formats($orig_date, + $orig_format, $new_format); + + $this->assertEquals($expected_date, $new_date, + "Convert from $orig_format to $new_format failed."); + + if($expected_date != $new_date) + { + return; + } + } + } + } + + /** + * @group bug17528 + */ + public function testSwapDatetimeFormatToDbFormat() + { + $date = '10-25-2007 12:00am'; + $format = $this->time_date->get_date_time_format(); + $db_format = $this->time_date->get_db_date_time_format(); + + $this->assertEquals( + $this->time_date->swap_formats( + $date, + 'm-d-Y h:ia', + $this->time_date->get_db_date_time_format() + ), + '2007-10-25 00:00:00' + ); + } + + /** + * @group bug17528 + */ + public function testTodbCanHandleDdmmyyyyFormats() + { + $old_pattern = $GLOBALS['current_user']->getPreference('datef'); + $GLOBALS['current_user']->setPreference('datef','d-m-Y'); + $db_date_pattern = '/2007-10-25 [0-9]{2}:[0-9]{2}:[0-9]{2}/'; + $this->assertRegExp( + $db_date_pattern, + $this->time_date->to_db('25-10-2007') + ); + + $this->_noUserCache(); + $GLOBALS['current_user']->setPreference('datef','m-d-Y'); + $this->assertRegExp( + $db_date_pattern, + $this->time_date->to_db('10-25-2007') + ); + $GLOBALS['current_user']->setPreference('datef',$old_pattern); + } + + /** + * @group bug17528 + */ + public function testTodbCanHandleMmddyyyyFormats() + { + $old_date = $GLOBALS['current_user']->getPreference('datef'); + + $GLOBALS['current_user']->setPreference('datef','m-d-Y'); + $db_date_pattern = '/2007-10-25 [0-9]{2}:[0-9]{2}:[0-9]{2}/'; + $this->assertRegExp( + $db_date_pattern, + $this->time_date->to_db('10-25-2007') + ); + + $GLOBALS['current_user']->setPreference('datef',$old_date); + } + + /** + * @group bug17528 + */ + public function testTodbdateCanHandleDdmmyyyyFormats() + { + $old_date = $GLOBALS['current_user']->getPreference('datef'); + + $GLOBALS['current_user']->setPreference('datef','d-m-Y'); + $this->assertEquals( + $this->time_date->to_db_date('25-10-2007'), + '2007-10-25' + ); + + $GLOBALS['current_user']->setPreference('datef',$old_date); + } + + /** + * @group bug17528 + */ + public function testTodbdateCanHandleMmddyyyyFormats() + { + $old_date = $GLOBALS['current_user']->getPreference('datef'); + $GLOBALS['current_user']->setPreference('datef','m-d-Y'); + $this->assertEquals( + '2007-10-25', + $this->time_date->to_db_date('10-25-2007') + ); + + $GLOBALS['current_user']->setPreference('datef',$old_date); + } + + public function testConvertMmddyyyyFormatToYyyymmdd() + { + $this->assertEquals( + '2007-11-02', + $this->time_date->swap_formats( + '11-02-2007', + 'm-d-Y', + 'Y-m-d' + ) + ); + } + + public function testGeneratingDefaultMidnight() + { + if(!is_callable(array($this->time_date, "get_default_midnight"))) { + $this->markTestSkipped("Method is no longer public"); + } + $old_time = $GLOBALS['current_user']->getPreference('timef'); + + $GLOBALS['current_user']->setPreference('timef','H:i:s'); + $this->assertEquals( + '00:00:00', + $this->time_date->get_default_midnight(true) + ); + + $GLOBALS['current_user']->setPreference('timef','h:ia'); + $this->assertEquals( + '12:00am', + $this->time_date->get_default_midnight(true) + ); + + $GLOBALS['current_user']->setPreference('timef',$old_time); + } + + public function providerGetDateFromRules() + { + return array( + array('2009',10,1,0,7200,"2009-10-04 02:00:00"), + array('2009',4,1,0,7200,"2009-04-05 02:00:00"), + array('2010',3,24,5,7200,"2010-03-26 02:00:00"), + array('2010',9,12,0,7200,"2010-09-12 02:00:00"), + ); + } + + /** + * @dataProvider providerGetDateFromRules + */ + public function testGetDateFromRules( + $year, + $startMonth, + $startDate, + $weekday, + $startTime, + $returnValue + ) + { + if(!is_callable(array($this->time_date, "getDateFromRules"))) { + $this->markTestSkipped("Method is no longer public"); + } + $this->assertEquals( + $this->time_date->getDateFromRules($year, $startMonth, $startDate, $weekday, $startTime), + $returnValue + ); + } + + /** + * tests for check_matching_format + */ + public function testCheckMatchingFormats() + { + foreach($this->date_tests as $datetest) { + if(isset($datetest["tf"])) { + $df = $this->time_date->merge_date_time($df = $datetest["df"], $datetest["tf"]); + } else { + $df = $datetest["df"]; + } + $this->assertTrue($this->time_date->check_matching_format($datetest["display"], $df), + "Broken match for '$df' with date '{$datetest["display"]}'"); + } + + // Some bad dates not detected by current code, it's too lenient + $badtests = array( + array("format" => "Y-m-d", "date" => ""), + array("format" => "Y-m-d", "date" => "blah-blah-blah"), + array("format" => "Y-m-d", "date" => "1-2"), + array("format" => "Y-m-d", "date" => "2007-10"), + //FIXME: array("format" => "Y-m-d", "date" => "200-10-25"), + array("format" => "Y-m-d", "date" => "2007-101-25"), + array("format" => "Y-m-d", "date" => "2007-Oct-25"), + //FIXME: array("format" => "Y-m-d", "date" => "2007-10-250"), + array("format" => "d-m-Y", "date" => "2007-10-25"), + array("format" => "d-m-Y", "date" => "10/25/2007"), + //FIXME: array("format" => "Y-m-d", "date" => "here: 2007-20-25"), + //FIXME: array("format" => "Y-m-d", "date" => "2007-20-25 here"), + ); + foreach($badtests as $datetest) { + $this->assertFalse($this->time_date->check_matching_format($datetest["date"], $datetest["format"]), + "Broken match for '{$datetest["format"]}' with date '{$datetest["date"]}'"); + } + } + + /** + * test fetching user settings + */ + public function testGetUserSettings() + { + $this->_setPrefs('d/m/Y', 'h:i:sA', "America/Lima"); + $this->assertEquals('dd/mm/yyyy', $this->time_date->get_user_date_format()); + //FIXME: $this->assertEquals('11:00:00PM', $this->time_date->get_user_time_format()); + $tz = $this->time_date->getUserTimeZone(); + $this->assertEquals(-300, $tz["gmtOffset"]); +// $this->assertEquals(60, $tz["dstOffset"]); + } + + /** + * test getting GMT dates + */ + public function testGetGMT() + { + $gmt = $this->time_date->get_gmt_db_datetime(); + $dt = strptime($gmt, "%Y-%m-%d %H:%M:%S"); + $this->assertEquals($dt['tm_year']+1900, gmdate("Y")); + $this->assertEquals($dt['tm_mon']+1, gmdate("m")); + $this->assertEquals($dt['tm_mday'], gmdate("d")); + + $gmt = $this->time_date->get_gmt_db_date(); + $dt = strptime($gmt, "%Y-%m-%d"); + $this->assertEquals($dt['tm_year']+1900, gmdate("Y")); + $this->assertEquals($dt['tm_mon']+1, gmdate("m")); + $this->assertEquals($dt['tm_mday'], gmdate("d")); + } + + /** + * test getting DB date formats indifferent ways + */ + public function testGetDB() + { + $this->assertEquals(gmdate($this->time_date->merge_date_time($this->time_date->get_db_date_format(), + $this->time_date->get_db_time_format())), + $this->time_date->get_gmt_db_datetime()); + } + + public function testGetCalFormats() + { + $cal_tests = array( + array("df" => "Y-m-d", "caldf" => "%Y-%m-%d", "tf" => "H:i:s", "caltf" => "%H:%M:%S"), + array("df" => "d/m/Y", "caldf" => "%d/%m/%Y", "tf" => "h:i:sa", "caltf" => "%I:%M:%S%P"), + array("df" => "m/d/Y", "caldf" => "%m/%d/%Y", "tf" => "H:i", "caltf" => "%H:%M"), + array("df" => "Y-m-d", "caldf" => "%Y-%m-%d", "tf" => "h:iA", "caltf" => "%I:%M%p"), + ); + foreach($cal_tests as $datetest) { + $this->_setPrefs($datetest["df"], $datetest["tf"], "America/Los_Angeles"); + $this->assertEquals( + $datetest["caldf"], + $this->time_date->get_cal_date_format(), + "Bad cal date format for '{$datetest["df"]}'"); + $this->assertEquals( + $datetest["caltf"], + $this->time_date->get_cal_time_format(), + "Bad cal time format for '{$datetest["tf"]}'"); + $this->assertEquals( + $this->time_date->merge_date_time($datetest["caldf"], $datetest["caltf"]), + $this->time_date->get_cal_date_time_format(), + "Bad cal datetime format for '{$datetest["df"]} {$datetest["tf"]}'"); + } + } + + /** + * test for handleOffsetMax + */ + public function testDayMinMax() + { + $day_tests = array( + array("date" => "2010-05-19", "start" => "2010-05-19 07:00:00", "end" => "2010-05-20 06:59:59", 'tz' => 'America/Los_Angeles'), + array("date" => "2010-01-19", "start" => "2010-01-19 08:00:00", "end" => "2010-01-20 07:59:59", 'tz' => 'America/Los_Angeles'), + array("date" => "2010-05-19", "start" => "2010-05-18 23:00:00", "end" => "2010-05-19 22:59:59", 'tz' => 'Europe/London'), + array("date" => "2010-01-19", "start" => "2010-01-19 00:00:00", "end" => "2010-01-19 23:59:59", 'tz' => 'Europe/London'), + array("date" => "2010-05-19", "start" => "2010-05-18 22:00:00", "end" => "2010-05-19 21:59:59", 'tz' => 'Europe/Oslo'), + ); + foreach($day_tests as $datetest) { + $this->_setPrefs('', '', $datetest["tz"]); + $dates = $this->time_date->handleOffsetMax($datetest["date"], ''); + $this->assertEquals($datetest["start"], $dates["min"], + "Bad min result for {$datetest["date"]} tz {$datetest["tz"]}"); + $this->assertEquals($datetest["end"], $dates["max"], + "Bad max result for {$datetest["date"]} tz {$datetest["tz"]}"); + } + } + + /** + * test for getDayStartEndGMT + */ + public function testGetDayStartEnd() + { + $day_tests = array( + array("date" => "05/19/2010", "start" => "2010-05-19 07:00:00", "end" => "2010-05-20 06:59:59", 'tz' => 'America/Los_Angeles'), + array("date" => "01/19/2010", "start" => "2010-01-19 08:00:00", "end" => "2010-01-20 07:59:59", 'tz' => 'America/Los_Angeles'), + array("date" => "05/19/2010", "start" => "2010-05-18 23:00:00", "end" => "2010-05-19 22:59:59", 'tz' => 'Europe/London'), + array("date" => "01/19/2010", "start" => "2010-01-19 00:00:00", "end" => "2010-01-19 23:59:59", 'tz' => 'Europe/London'), + array("date" => "05/19/2010", "start" => "2010-05-18 22:00:00", "end" => "2010-05-19 21:59:59", 'tz' => 'Europe/Oslo'), + ); + foreach($day_tests as $datetest) { + $this->_setPrefs('m/d/Y', '', $datetest["tz"]); + $dates = $this->time_date->getDayStartEndGMT($datetest["date"], ''); + $this->assertEquals($datetest["start"], $dates["start"], + "Bad min result for {$datetest["date"]} tz {$datetest["tz"]}"); + $this->assertEquals($datetest["end"], $dates["end"], + "Bad max result for {$datetest["date"]} tz {$datetest["tz"]}"); + } + } + + /** + * test for merge_time_meridiem + */ + public function testMergeAmPm() + { + $ampm_tests = array( + array("date" => "05:17:28", "mer" => "am", "tf" => "H:i:s", "display" => "05:17:28"), + array("date" => "05:17:28", "mer" => "am", "tf" => "h:i:sa", "display" => "05:17:28am"), + // short ones + array("date" => "17:34", "mer" => "pm", "tf" => "H:i", "display" => "17:34"), + array("date" => "11:42", "mer" => "PM", "tf" => "h:iA", "display" => "11:42PM"), + array("date" => "11:42", "mer" => "pm", "tf" => "h:iA", "display" => "11:42pm"), + array("date" => "03", "mer" => "AM", "tf" => "ha", "display" => "03AM"), + array("date" => "15", "mer" => "AM", "tf" => "H", "display" => "15"), + ); + foreach($ampm_tests as $datetest) { + $amdate = $this->time_date->merge_time_meridiem($datetest["date"], $datetest["tf"], $datetest["mer"]); + $this->assertEquals($datetest["display"], $amdate, + "Bad min result for {$datetest["date"]} format {$datetest["tf"]}"); + } + } + + public function providerSplitDateTime() + { + return array( + array("2009-10-04 02:00:00","2009-10-04","02:00:00"), + array("10/04/2010 2:00pm","10/04/2010","2:00pm"), + array("10-04-2010 2:00","10-04-2010","2:00"), + ); + } + + /** + * @dataProvider providerSplitDateTime + */ + public function testSplitDateTime( + $datetime, + $date, + $time + ) + { + $this->assertEquals($date,$this->time_date->getDatePart($datetime)); + $this->assertEquals($time,$this->time_date->getTimePart($datetime)); + } +} diff --git a/tests/include/connectors/ConnectorsTestUtility.php b/tests/include/connectors/ConnectorsTestUtility.php new file mode 100755 index 00000000..82d6dfda --- /dev/null +++ b/tests/include/connectors/ConnectorsTestUtility.php @@ -0,0 +1,33 @@ +read()) { + // Skip pointers + if ($entry == '.' || $entry == '..') { + continue; + } + + // Recurse + self::rmdirr("$dirname/$entry"); + } + + // Clean up + $dir->close(); + return rmdir($dirname); + } + +} +?> \ No newline at end of file diff --git a/tests/include/database/DBHelperTest.php b/tests/include/database/DBHelperTest.php new file mode 100755 index 00000000..a688fc8d --- /dev/null +++ b/tests/include/database/DBHelperTest.php @@ -0,0 +1,614 @@ +_db = &DBManagerFactory::getInstance(); + $this->_helper = $this->_db->getHelper(); + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + $this->_db->disconnect(); + } + + public function testCreateTableSQL() + { + $sql = $this->_helper->createTableSQL(new Contact); + + $this->assertRegExp("/create\s*table\s*contacts/i",$sql); + } + + public function testCreateTableSQLParams() + { + $bean = new Contact; + + $sql = $this->_helper->createTableSQLParams( + $bean->getTableName(), + $bean->getFieldDefinitions(), + $bean->getIndices()); + + $this->assertRegExp("/create\s*table\s*contacts/i",$sql); + } + + public function testInsertSQL() + { + $sql = $this->_helper->insertSQL(new Contact); + + $this->assertRegExp("/insert\s*into\s*contacts/i",$sql); + } + + /** + * ticket 38216 + */ + public function testInsertSQLProperlyDecodesHtmlEntities() + { + $bean = new Contact; + $bean->last_name = '"Test"'; + + $sql = $this->_helper->insertSQL($bean); + + $this->assertNotContains(""",$sql); + } + + public function testUpdateSQL() + { + $sql = $this->_helper->updateSQL(new Contact, array("id" => "1")); + + $this->assertRegExp("/update\s*contacts\s*set/i",$sql); + $this->assertRegExp("/where\s*contacts.id\s*=\s*'1'/i",$sql); + } + + /** + * ticket 38216 + */ + public function testUpdateSQLProperlyDecodesHtmlEntities() + { + $bean = new Contact; + $bean->last_name = '"Test"'; + + $sql = $this->_helper->updateSQL($bean, array("id" => "1")); + + $this->assertNotContains(""",$sql); + } + + public function testDeleteSQL() + { + $sql = $this->_helper->deleteSQL(new Contact, array("id" => "1")); + + $this->assertRegExp("/update\s*contacts\s*set\s*deleted\s*=\s*1/i",$sql); + $this->assertRegExp("/where\s*contacts.id\s*=\s*'1'/i",$sql); + } + + public function testRetrieveSQL() + { + $sql = $this->_helper->retrieveSQL(new Contact, array("id" => "1")); + + $this->assertRegExp("/select\s*\*\s*from\s*contacts/i",$sql); + $this->assertRegExp("/where\s*contacts.id\s*=\s*'1'/i",$sql); + } + + public function testRetrieveViewSQL() + { + // TODO: write this test + } + + public function testCreateIndexSQL() + { + $sql = $this->_helper->createIndexSQL( + new Contact, + array('id' => array('name'=>'id')), + 'idx_id'); + + $this->assertRegExp("/create\s*unique\s*index\s*idx_id\s*on\s*contacts\s*\(\s*id\s*\)/i",$sql); + + $sql = $this->_helper->createIndexSQL( + new Contact, + array('id' => array('name'=>'id')), + 'idx_id', + false); + + $this->assertRegExp("/create\s*index\s*idx_id\s*on\s*contacts\s*\(\s*id\s*\)/i",$sql); + + $sql = $this->_helper->createIndexSQL( + new Contact, + array('id' => array('name'=>'id'),'deleted' => array('name'=>'deleted')), + 'idx_id'); + + $this->assertRegExp("/create\s*unique\s*index\s*idx_id\s*on\s*contacts\s*\(\s*id\s*,\s*deleted\s*\)/i",$sql); + } + + public function testGetFieldType() + { + $fieldDef = array( + 'dbType' => 'varchar', + 'dbtype' => 'int', + 'type' => 'char', + 'Type' => 'bool', + 'data_type' => 'email', + ); + + $this->assertEquals($this->_helper->getFieldType($fieldDef),'varchar'); + unset($fieldDef['dbType']); + $this->assertEquals($this->_helper->getFieldType($fieldDef),'int'); + unset($fieldDef['dbtype']); + $this->assertEquals($this->_helper->getFieldType($fieldDef),'char'); + unset($fieldDef['type']); + $this->assertEquals($this->_helper->getFieldType($fieldDef),'bool'); + unset($fieldDef['Type']); + $this->assertEquals($this->_helper->getFieldType($fieldDef),'email'); + } + public function testGetAutoIncrement() + { + $case = new aCase(); + $case->name = "foo"; + $case->save(); + $case->retrieve($case->id); + $lastAuto = $case->case_number; + $this->assertEquals($lastAuto + 1, $this->_helper->getAutoIncrement("cases", "case_number")); + $case->deleted = true; + $case->save(); + } + public function testSetAutoIncrementStart() + { + $case = new aCase(); + $case->name = "foo"; + $case->save(); + $case->retrieve($case->id); + $lastAuto = $case->case_number; + $case->deleted = true; + $case->save(); + $newAuto = $lastAuto + 5; + $this->_helper->setAutoIncrementStart("cases", "case_number", $newAuto); + $case2 = new aCase(); + $case2->name = "foo2"; + $case2->save(); + $case2->retrieve($case2->id); + $this->assertEquals($newAuto, $case2->case_number); + $case2->deleted = true; + $case2->save(); + } + public function testAddColumnSQL() + { + $sql = $this->_helper->addColumnSQL( + 'contacts', + array('foo' => array('name'=>'foo','type'=>'varchar')) + ); + + $this->assertRegExp("/alter\s*table\s*contacts/i",$sql); + } + + public function testAlterColumnSQL() + { + $sql = $this->_helper->alterColumnSQL( + 'contacts', + array('foo' => array('name'=>'foo','type'=>'varchar')) + ); + + $this->assertRegExp("/alter\s*table\s*contacts/i",$sql); + } + + public function testDropTableSQL() + { + $sql = $this->_helper->dropTableSQL(new Contact); + + $this->assertRegExp("/drop\s*table.*contacts/i",$sql); + } + + public function testDropTableNameSQL() + { + $sql = $this->_helper->dropTableNameSQL('contacts'); + + $this->assertRegExp("/drop\s*table.*contacts/i",$sql); + } + + public function testDeleteColumnSQL() + { + $sql = $this->_helper->deleteColumnSQL( + new Contact, + array('foo' => array('name'=>'foo','type'=>'varchar')) + ); + $this->assertRegExp("/alter\s*table\s*contacts\s*drop\s*column\s*foo/i",$sql); + } + + public function testDropColumnSQL() + { + $sql = $this->_helper->dropColumnSQL( + 'contacts', + array('foo' => array('name'=>'foo','type'=>'varchar')) + ); + $this->assertRegExp("/alter\s*table\s*contacts\s*drop\s*column\s*foo/i",$sql); + } + + public function testMassageValue() + { + $this->assertEquals( + $this->_helper->massageValue(123,array('name'=>'foo','type'=>'int')), + 123 + ); + if ( $this->_db->dbType == 'mssql' + ) + $this->assertEquals( + $this->_helper->massageValue("'dog'",array('name'=>'foo','type'=>'varchar')), + "'''dog'''" + ); + else + $this->assertEquals( + $this->_helper->massageValue("'dog'",array('name'=>'foo','type'=>'varchar')), + "'\'dog\''" + ); + } + + public function testGetColumnType() + { + $this->assertEquals( + $this->_helper->getColumnType('int'), + 'int' + ); + } + + public function testIsFieldArray() + { + $this->assertTrue( + $this->_helper->isFieldArray(array('name'=>'foo','type'=>array('int'))) + ); + + $this->assertFalse( + $this->_helper->isFieldArray(array('name'=>'foo','type'=>'int')) + ); + + $this->assertTrue( + $this->_helper->isFieldArray(array('name'=>'foo')) + ); + + $this->assertFalse( + $this->_helper->isFieldArray(1) + ); + } + + public function testSaveAuditRecords() + { + // TODO: write this test + } + + public function testGetDataChanges() + { + // TODO: write this test + } + + public function testQuote() + { + $this->assertEquals( + $this->_helper->quote('foobar'), + "'".$this->_db->quote('foobar')."'" + ); + } + + public function testEscapeQuote() + { + $this->assertEquals( + $this->_helper->escape_quote('foobar'), + $this->_db->quote('foobar') + ); + } + + public function testGetIndices() + { + $indices = $this->_helper->get_indices('contacts'); + + foreach ( $indices as $index ) { + $this->assertTrue(!empty($index['name'])); + $this->assertTrue(!empty($index['type'])); + $this->assertTrue(!empty($index['fields'])); + } + } + + public function testAddDropConstraint() + { + $tablename = 'test' . date("YmdHis"); + $sql = $this->_helper->add_drop_constraint( + $tablename, + array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + ), + false + ); + + $this->assertRegExp("/idx_foo/i",$sql); + $this->assertRegExp("/foo/i",$sql); + + $tablename = 'test' . date("YmdHis"); + $sql = $this->_helper->add_drop_constraint( + $tablename, + array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + ), + true + ); + + $this->assertRegExp("/idx_foo/i",$sql); + $this->assertRegExp("/foo/i",$sql); + $this->assertRegExp("/drop/i",$sql); + } + + public function testRenameIndex() + { + // TODO: write this test + } + + public function testNumberOfColumns() + { + $tablename = 'test' . date("YmdHis"); + $this->_db->createTableParams($tablename, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array() + ); + + $this->assertEquals($this->_helper->number_of_columns($tablename),1); + + $this->_db->dropTableName($tablename); + } + + public function testGetColumns() + { + $vardefs = $this->_helper->get_columns('contacts'); + + $this->assertTrue(isset($vardefs['id'])); + $this->assertTrue(isset($vardefs['id']['name'])); + $this->assertTrue(isset($vardefs['id']['type'])); + } + + public function testMassageFieldDefs() + { + // TODO: write this test + } + + /** + * @group bug22921 + */ + public function testEmptyPrecision() + { + $sql = $this->_helper->alterColumnSQL( + 'contacts', + array('compensation_min' => + array( + 'required' => false, + 'name' => 'compensation_min', + 'vname' => 'LBL_COMPENSATION_MIN', + 'type' => 'float', + 'massupdate' => 0, + 'comments' => '', + 'help' => '', + 'importable' => 'true', + 'duplicate_merge' => 'disabled', + 'duplicate_merge_dom_value' => 0, + 'audited' => 0, + 'reportable' => 1, + 'len' => '18', + 'precision' => '', + ), + ) + ); + + $this->assertNotRegExp("/float\s*\(18,\s*\)/i",$sql); + $this->assertRegExp("/float\s*\(18\)/i",$sql); + } + + /** + * @group bug22921 + */ + public function testBlankSpacePrecision() + { + $sql = $this->_helper->alterColumnSQL( + 'contacts', + array('compensation_min' => + array( + 'required' => false, + 'name' => 'compensation_min', + 'vname' => 'LBL_COMPENSATION_MIN', + 'type' => 'float', + 'massupdate' => 0, + 'comments' => '', + 'help' => '', + 'importable' => 'true', + 'duplicate_merge' => 'disabled', + 'duplicate_merge_dom_value' => 0, + 'audited' => 0, + 'reportable' => 1, + 'len' => '18', + 'precision' => ' ', + ), + ) + ); + + $this->assertNotRegExp("/float\s*\(18,\s*\)/i",$sql); + $this->assertRegExp("/float\s*\(18\)/i",$sql); + } + + /** + * @group bug22921 + */ + public function testSetPrecision() + { + $sql = $this->_helper->alterColumnSQL( + 'contacts', + array('compensation_min' => + array( + 'required' => false, + 'name' => 'compensation_min', + 'vname' => 'LBL_COMPENSATION_MIN', + 'type' => 'float', + 'massupdate' => 0, + 'comments' => '', + 'help' => '', + 'importable' => 'true', + 'duplicate_merge' => 'disabled', + 'duplicate_merge_dom_value' => 0, + 'audited' => 0, + 'reportable' => 1, + 'len' => '18', + 'precision' => '2', + ), + ) + ); + + if ( $this->_db->dbType == 'mssql' ) + $this->assertRegExp("/float\s*\(18\)/i",$sql); + else + $this->assertRegExp("/float\s*\(18,2\)/i",$sql); + } + + /** + * @group bug22921 + */ + public function testSetPrecisionInLen() + { + $sql = $this->_helper->alterColumnSQL( + 'contacts', + array('compensation_min' => + array( + 'required' => false, + 'name' => 'compensation_min', + 'vname' => 'LBL_COMPENSATION_MIN', + 'type' => 'float', + 'massupdate' => 0, + 'comments' => '', + 'help' => '', + 'importable' => 'true', + 'duplicate_merge' => 'disabled', + 'duplicate_merge_dom_value' => 0, + 'audited' => 0, + 'reportable' => 1, + 'len' => '18,2', + ), + ) + ); + if ( $this->_db->dbType == 'mssql' ) + $this->assertRegExp("/float\s*\(18\)/i",$sql); + else + $this->assertRegExp("/float\s*\(18,2\)/i",$sql); + } + + /** + * @group bug22921 + */ + public function testEmptyPrecisionMassageFieldDef() + { + $fielddef = array( + 'required' => false, + 'name' => 'compensation_min', + 'vname' => 'LBL_COMPENSATION_MIN', + 'type' => 'float', + 'massupdate' => 0, + 'comments' => '', + 'help' => '', + 'importable' => 'true', + 'duplicate_merge' => 'disabled', + 'duplicate_merge_dom_value' => 0, + 'audited' => 0, + 'reportable' => 1, + 'len' => '18', + 'precision' => '', + ); + $this->_helper->massageFieldDef($fielddef,'mytable'); + + $this->assertEquals("18",$fielddef['len']); + } + + /** + * @group bug22921 + */ + public function testBlankSpacePrecisionMassageFieldDef() + { + $fielddef = array( + 'required' => false, + 'name' => 'compensation_min', + 'vname' => 'LBL_COMPENSATION_MIN', + 'type' => 'float', + 'massupdate' => 0, + 'comments' => '', + 'help' => '', + 'importable' => 'true', + 'duplicate_merge' => 'disabled', + 'duplicate_merge_dom_value' => 0, + 'audited' => 0, + 'reportable' => 1, + 'len' => '18', + 'precision' => ' ', + ); + $this->_helper->massageFieldDef($fielddef,'mytable'); + + $this->assertEquals("18",$fielddef['len']); + } + + /** + * @group bug22921 + */ + public function testSetPrecisionMassageFieldDef() + { + $fielddef = array( + 'required' => false, + 'name' => 'compensation_min', + 'vname' => 'LBL_COMPENSATION_MIN', + 'type' => 'float', + 'massupdate' => 0, + 'comments' => '', + 'help' => '', + 'importable' => 'true', + 'duplicate_merge' => 'disabled', + 'duplicate_merge_dom_value' => 0, + 'audited' => 0, + 'reportable' => 1, + 'len' => '18', + 'precision' => '2', + ); + $this->_helper->massageFieldDef($fielddef,'mytable'); + + $this->assertEquals("18,2",$fielddef['len']); + } + + /** + * @group bug22921 + */ + public function testSetPrecisionInLenMassageFieldDef() + { + $fielddef = array( + 'required' => false, + 'name' => 'compensation_min', + 'vname' => 'LBL_COMPENSATION_MIN', + 'type' => 'float', + 'massupdate' => 0, + 'comments' => '', + 'help' => '', + 'importable' => 'true', + 'duplicate_merge' => 'disabled', + 'duplicate_merge_dom_value' => 0, + 'audited' => 0, + 'reportable' => 1, + 'len' => '18,2', + ); + $this->_helper->massageFieldDef($fielddef,'mytable'); + + $this->assertEquals("18,2",$fielddef['len']); + } +} diff --git a/tests/include/database/DBManagerFactoryTest.php b/tests/include/database/DBManagerFactoryTest.php new file mode 100755 index 00000000..49f24b53 --- /dev/null +++ b/tests/include/database/DBManagerFactoryTest.php @@ -0,0 +1,112 @@ +_oldSugarConfig = $GLOBALS['sugar_config']; + } + + public function tearDown() + { + $GLOBALS['sugar_config'] = $this->_oldSugarConfig; + } + + public function testGetInstance() + { + $db = &DBManagerFactory::getInstance(); + + $this->assertTrue($db instanceOf DBManager,"Should return a DBManger object"); + } + + public function testGetInstanceCheckMysqlDriverChoosen() + { + if ( $GLOBALS['db']->dbType != 'mysql' ) + $this->markTestSkipped('Only applies to SQL Server'); + + $db = &DBManagerFactory::getInstance(); + + if ( function_exists('mysqli_connect') ) + $this->assertTrue($db instanceOf MysqliManager,"Should return a MysqliManager object"); + else + $this->assertTrue($db instanceOf MysqlManager,"Should return a MysqlManager object"); + } + + /** + * @group bug27781 + */ + public function testGetInstanceMssqlDefaultSelection() + { + if ( $GLOBALS['db']->dbType != 'mssql' ) + $this->markTestSkipped('Only applies to SQL Server'); + + $GLOBALS['sugar_config']['db_mssql_force_driver'] = ''; + + $db = &DBManagerFactory::getInstance(); + + if ( function_exists('sqlsrv_connect') ) + $this->assertTrue($db instanceOf SqlsrvManager,"Should return a SqlsrvManager object"); + elseif ( is_freetds() ) + $this->assertTrue($db instanceOf FreeTDSManager,"Should return a FreeTDSManager object"); + else + $this->assertTrue($db instanceOf MssqlManager,"Should return a MssqlManager object"); + } + + /** + * @group bug27781 + */ + public function testGetInstanceMssqlForceFreetdsSelection() + { + if ( $GLOBALS['db']->dbType != 'mssql' || !is_freetds() ) + $this->markTestSkipped('Only applies to SQL Server FreeTDS'); + + $GLOBALS['sugar_config']['db_mssql_force_driver'] = 'freetds'; + + $db = &DBManagerFactory::getInstance(); + + $this->assertTrue($db instanceOf FreeTDSManager,"Should return a FreeTDSManager object"); + } + + /** + * @group bug27781 + */ + public function testGetInstanceMssqlForceMssqlSelection() + { + if ( $GLOBALS['db']->dbType != 'mssql' || !function_exists('mssql_connect') ) + $this->markTestSkipped('Only applies to SQL Server with the Native PHP mssql Driver'); + + $GLOBALS['sugar_config']['db_mssql_force_driver'] = 'mssql'; + + $db = &DBManagerFactory::getInstance(); + + if ( is_freetds() ) + $this->assertTrue($db instanceOf MssqlManager,"Should return a MssqlManager object"); + elseif ( function_exists('mssql_connect') ) + $this->assertTrue($db instanceOf MssqlManager,"Should return a MssqlManager object"); + else + $this->assertTrue($db instanceOf SqlsrvManager,"Should return a SqlsrvManager object"); + } + + /** + * @group bug27781 + */ + public function testGetInstanceMssqlForceSqlsrvSelection() + { + if ( $GLOBALS['db']->dbType != 'mssql' || !function_exists('sqlsrv_connect') ) + $this->markTestSkipped('Only applies to SQL Server'); + + $GLOBALS['sugar_config']['db_mssql_force_driver'] = 'sqlsrv'; + + $db = &DBManagerFactory::getInstance(); + + if ( is_freetds() && !function_exists('sqlsrv_connect') ) + $this->assertTrue($db instanceOf FreeTDSManager,"Should return a FreeTDSManager object"); + elseif ( function_exists('mssql_connect') && !function_exists('sqlsrv_connect') ) + $this->assertTrue($db instanceOf MssqlManager,"Should return a MssqlManager object"); + else + $this->assertTrue($db instanceOf SqlsrvManager,"Should return a SqlsrvManager object"); + } +} diff --git a/tests/include/database/DBManagerTest.php b/tests/include/database/DBManagerTest.php new file mode 100755 index 00000000..e372f894 --- /dev/null +++ b/tests/include/database/DBManagerTest.php @@ -0,0 +1,1375 @@ +_db = DBManagerFactory::getInstance(); + $GLOBALS['app_strings'] = return_application_language($GLOBALS['current_language']); + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + unset($GLOBALS['app_strings']); + } + + private function _createRecords( + $num + ) + { + $beanIds = array(); + for ( $i = 0; $i < $num; $i++ ) { + $bean = new Contact(); + $bean->id = "$i-test" . date("YmdHis"); + $bean->last_name = "foobar"; + $this->_db->insert($bean); + $beanIds[] = $bean->id; + } + + return $beanIds; + } + + private function _removeRecords( + array $ids + ) + { + foreach ($ids as $id) + $this->_db->query("DELETE From contacts where id = '{$id}'"); + } + + public function testGetTableName() + { + $this->_db->createTableParams('MyTableName',array('foo'=>'foo'),array()); + + $this->assertEquals($this->_db->getTableName(),'MyTableName'); + } + + public function testGetDatabase() + { + if ( $this->_db instanceOf MysqliManager ) + $this->assertType('Mysqli',$this->_db->getDatabase()); + else + $this->assertTrue(is_resource($this->_db->getDatabase())); + } + + public function testGetHelper() + { + $this->assertType('DBHelper',$this->_db->getHelper()); + } + + public function testCheckError() + { + $this->assertFalse($this->_db->checkError()); + } + + public function testCheckErrorNoConnection() + { + $this->_db->disconnect(); + $this->assertTrue($this->_db->checkError()); + $this->_db = &DBManagerFactory::getInstance(); + } + + public function testGetQueryTime() + { + $this->_db->version(); + $this->assertTrue($this->_db->getQueryTime() > 0); + } + + public function testCheckConnection() + { + $this->_db->checkConnection(); + if ( $this->_db instanceOf MysqliManager ) + $this->assertType('Mysqli',$this->_db->getDatabase()); + else + $this->assertTrue(is_resource($this->_db->getDatabase())); + } + + public function testInsert() + { + $bean = new Contact(); + $bean->last_name = 'foobar' . date("YmdHis"); + $bean->id = 'test' . date("YmdHis"); + $this->_db->insert($bean); + + $result = $this->_db->query("select id, last_name from contacts where id = '{$bean->id}'"); + $row = $this->_db->fetchByAssoc($result); + $this->assertEquals($row['last_name'],$bean->last_name); + $this->assertEquals($row['id'],$bean->id); + + $this->_db->query("delete from contacts where id = '{$row['id']}'"); + } + + public function testUpdate() + { + $bean = new Contact(); + $bean->last_name = 'foobar' . date("YmdHis"); + $bean->id = 'test' . date("YmdHis"); + $this->_db->insert($bean); + $id = $bean->id; + + $bean = new Contact(); + $bean->last_name = 'newfoobar' . date("YmdHis"); + $this->_db->update($bean,array('id'=>$id)); + + $result = $this->_db->query("select id, last_name from contacts where id = '{$id}'"); + $row = $this->_db->fetchByAssoc($result); + $this->assertEquals($row['last_name'],$bean->last_name); + $this->assertEquals($row['id'],$id); + + $this->_db->query("delete from contacts where id = '{$row['id']}'"); + } + + public function testDelete() + { + $bean = new Contact(); + $bean->last_name = 'foobar' . date("YmdHis"); + $bean->id = 'test' . date("YmdHis"); + $this->_db->insert($bean); + $id = $bean->id; + + $bean = new Contact(); + $this->_db->delete($bean,array('id'=>$id)); + + $result = $this->_db->query("select deleted from contacts where id = '{$id}'"); + $row = $this->_db->fetchByAssoc($result); + $this->assertEquals($row['deleted'],'1'); + + $this->_db->query("delete from contacts where id = '{$id}'"); + } + + public function testRetrieve() + { + $bean = new Contact(); + $bean->last_name = 'foobar' . date("YmdHis"); + $bean->id = 'test' . date("YmdHis"); + $this->_db->insert($bean); + $id = $bean->id; + + $bean = new Contact(); + $result = $this->_db->retrieve($bean,array('id'=>$id)); + $row = $this->_db->fetchByAssoc($result); + $this->assertEquals($row['id'],$id); + + $this->_db->query("delete from contacts where id = '{$id}'"); + } + + public function testRetrieveView() + { + // TODO: Write this test + } + + public function testCreateTable() + { + // TODO: Write this test + } + + public function testCreateTableParams() + { + $tablename = 'test' . date("YmdHis"); + $this->_db->createTableParams($tablename, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array( + array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + ) + ) + ); + $this->assertTrue(in_array($tablename,$this->_db->getTablesArray())); + + $this->_db->dropTableName($tablename); + } + + public function testRepairTable() + { + // TODO: Write this test + } + + public function testRepairTableParams() + { + // TODO: Write this test + } + + public function testCompareFieldInTables() + { + $tablename1 = 'test1_' . date("YmdHis"); + $this->_db->createTableParams($tablename1, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array() + ); + $tablename2 = 'test2_' . date("YmdHis"); + $this->_db->createTableParams($tablename2, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array() + ); + + $res = $this->_db->compareFieldInTables( + 'foo', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'match'); + + $this->_db->dropTableName($tablename1); + $this->_db->dropTableName($tablename2); + } + + public function testCompareFieldInTablesNotInTable1() + { + $tablename1 = 'test3_' . date("YmdHis"); + $this->_db->createTableParams($tablename1, + array( + 'foobar' => array ( + 'name' => 'foobar', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array() + ); + $tablename2 = 'test4_' . date("YmdHis"); + $this->_db->createTableParams($tablename2, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array() + ); + + $res = $this->_db->compareFieldInTables( + 'foo', $tablename1, $tablename2); + $this->assertEquals($res['msg'],'not_exists_table1'); + + $this->_db->dropTableName($tablename1); + $this->_db->dropTableName($tablename2); + } + + public function testCompareFieldInTablesNotInTable2() + { + $tablename1 = 'test5_' . date("YmdHis"); + $this->_db->createTableParams($tablename1, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array() + ); + $tablename2 = 'test6_' . date("YmdHis"); + $this->_db->createTableParams($tablename2, + array( + 'foobar' => array ( + 'name' => 'foobar', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array() + ); + + $res = $this->_db->compareFieldInTables( + 'foo', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'not_exists_table2'); + + $this->_db->dropTableName($tablename1); + $this->_db->dropTableName($tablename2); + } + + public function testCompareFieldInTablesFieldsDoNotMatch() + { + $tablename1 = 'test7_' . date("YmdHis"); + $this->_db->createTableParams($tablename1, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array() + ); + $tablename2 = 'test8_' . date("YmdHis"); + $this->_db->createTableParams($tablename2, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'int', + ), + ), + array() + ); + + $res = $this->_db->compareFieldInTables( + 'foo', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'no_match'); + + $this->_db->dropTableName($tablename1); + $this->_db->dropTableName($tablename2); + } + + public function testCompareIndexInTables() + { + $tablename1 = 'test9_' . date("YmdHis"); + $this->_db->createTableParams($tablename1, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array( + array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + ) + ) + ); + $tablename2 = 'test10_' . date("YmdHis"); + $this->_db->createTableParams($tablename2, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array( + array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + ) + ) + ); + + $res = $this->_db->compareIndexInTables( + 'idx_foo', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'match'); + + $this->_db->dropTableName($tablename1); + $this->_db->dropTableName($tablename2); + } + + public function testCompareIndexInTablesNotInTable1() + { + $tablename1 = 'test11_' . date("YmdHis"); + $this->_db->createTableParams($tablename1, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array( + array( + 'name' => 'idx_foobar', + 'type' => 'index', + 'fields' => array('foo'), + ) + ) + ); + $tablename2 = 'test12_' . date("YmdHis"); + $this->_db->createTableParams($tablename2, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array( + array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + ) + ) + ); + + $res = $this->_db->compareIndexInTables( + 'idx_foo', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'not_exists_table1'); + + $this->_db->dropTableName($tablename1); + $this->_db->dropTableName($tablename2); + } + + public function testCompareIndexInTablesNotInTable2() + { + $tablename1 = 'test13_' . date("YmdHis"); + $this->_db->createTableParams($tablename1, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array( + array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + ) + ) + ); + $tablename2 = 'test14_' . date("YmdHis"); + $this->_db->createTableParams($tablename2, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array( + array( + 'name' => 'idx_foobar', + 'type' => 'index', + 'fields' => array('foo'), + ) + ) + ); + + $res = $this->_db->compareIndexInTables( + 'idx_foo', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'not_exists_table2'); + + $this->_db->dropTableName($tablename1); + $this->_db->dropTableName($tablename2); + } + + public function testCompareIndexInTablesIndexesDoNotMatch() + { + $tablename1 = 'test15_' . date("YmdHis"); + $this->_db->createTableParams($tablename1, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array( + array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + ) + ) + ); + $tablename2 = 'test16_' . date("YmdHis"); + $this->_db->createTableParams($tablename2, + array( + 'foo' => array ( + 'name' => 'foobar', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array( + array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foobar'), + ) + ) + ); + + $res = $this->_db->compareIndexInTables( + 'idx_foo', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'no_match'); + + $this->_db->dropTableName($tablename1); + $this->_db->dropTableName($tablename2); + } + + public function testCreateIndex() + { + // TODO: Write this test + } + + public function testAddIndexes() + { + $tablename1 = 'test17_' . date("YmdHis"); + $this->_db->createTableParams($tablename1, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array( + array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + ) + ) + ); + $tablename2 = 'test18_' . date("YmdHis"); + $this->_db->createTableParams($tablename2, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array() + ); + + // first test not executing the statement + $this->_db->addIndexes( + $tablename2, + array(array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + )), + false); + + $res = $this->_db->compareIndexInTables( + 'idx_foo', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'not_exists_table2'); + + // now, execute the statement + $this->_db->addIndexes( + $tablename2, + array(array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + )) + ); + $res = $this->_db->compareIndexInTables( + 'idx_foo', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'match'); + + $this->_db->dropTableName($tablename1); + $this->_db->dropTableName($tablename2); + } + + public function testDropIndexes() + { + $tablename1 = 'test19_' . date("YmdHis"); + $this->_db->createTableParams($tablename1, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array( + array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + ) + ) + ); + $tablename2 = 'test20_' . date("YmdHis"); + $this->_db->createTableParams($tablename2, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array( + array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + ) + ) + ); + + $res = $this->_db->compareIndexInTables( + 'idx_foo', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'match'); + + // first test not executing the statement + $this->_db->dropIndexes( + $tablename2, + array(array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + )), + false); + + $res = $this->_db->compareIndexInTables( + 'idx_foo', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'match'); + + // now, execute the statement + $sql = $this->_db->dropIndexes( + $tablename2, + array(array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + )), + true + ); + + $res = $this->_db->compareIndexInTables( + 'idx_foo', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'not_exists_table2'); + + $this->_db->dropTableName($tablename1); + $this->_db->dropTableName($tablename2); + } + + public function testModifyIndexes() + { + $tablename1 = 'test21_' . date("YmdHis"); + $this->_db->createTableParams($tablename1, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + 'foobar' => array ( + 'name' => 'foobar', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array( + array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + ) + ) + ); + $tablename2 = 'test22_' . date("YmdHis"); + $this->_db->createTableParams($tablename2, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + 'foobar' => array ( + 'name' => 'foobar', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array( + array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foobar'), + ) + ) + ); + + $res = $this->_db->compareIndexInTables( + 'idx_foo', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'no_match'); + + $this->_db->modifyIndexes( + $tablename2, + array(array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + )), + false); + + $res = $this->_db->compareIndexInTables( + 'idx_foo', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'no_match'); + + $this->_db->modifyIndexes( + $tablename2, + array(array( + 'name' => 'idx_foo', + 'type' => 'index', + 'fields' => array('foo'), + )) + ); + + $res = $this->_db->compareIndexInTables( + 'idx_foo', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'match'); + + $this->_db->dropTableName($tablename1); + $this->_db->dropTableName($tablename2); + } + + public function testAddColumn() + { + $tablename1 = 'test23_' . date("YmdHis"); + $this->_db->createTableParams($tablename1, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + 'foobar' => array ( + 'name' => 'foobar', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array() + ); + $tablename2 = 'test24_' . date("YmdHis"); + $this->_db->createTableParams($tablename2, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array() + ); + + $res = $this->_db->compareFieldInTables( + 'foobar', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'not_exists_table2'); + + $this->_db->addColumn( + $tablename2, + array( + 'foobar' => array ( + 'name' => 'foobar', + 'type' => 'varchar', + 'len' => '255', + ) + ) + ); + + $res = $this->_db->compareFieldInTables( + 'foobar', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'match'); + + $this->_db->dropTableName($tablename1); + $this->_db->dropTableName($tablename2); + } + + public function testAlterColumn() + { + $tablename1 = 'test25_' . date("YmdHis"); + $this->_db->createTableParams($tablename1, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + 'foobar' => array ( + 'name' => 'foobar', + 'type' => 'varchar', + 'len' => '255', + 'required' => true, + ), + ), + array() + ); + $tablename2 = 'test26_' . date("YmdHis"); + $this->_db->createTableParams($tablename2, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + 'foobar' => array ( + 'name' => 'foobar', + 'type' => 'int', + ), + ), + array() + ); + + $res = $this->_db->compareFieldInTables( + 'foobar', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'no_match'); + + $this->_db->alterColumn( + $tablename2, + array( + 'foobar' => array ( + 'name' => 'foobar', + 'type' => 'varchar', + 'len' => '255', + 'required' => true, + ) + ) + ); + + $res = $this->_db->compareFieldInTables( + 'foobar', $tablename1, $tablename2); + + $this->assertEquals($res['msg'],'match'); + + $this->_db->dropTableName($tablename1); + $this->_db->dropTableName($tablename2); + } + + public function testDropTable() + { + // TODO: Write this test + } + + public function testDropTableName() + { + $tablename = 'test' . date("YmdHis"); + $this->_db->createTableParams($tablename, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array() + ); + $this->assertTrue(in_array($tablename,$this->_db->getTablesArray())); + + $this->_db->dropTableName($tablename); + + $this->assertFalse(in_array($tablename,$this->_db->getTablesArray())); + } + + public function testDeleteColumn() + { + // TODO: Write this test + } + + public function testDisconnectAll() + { + $this->_db->disconnectAll(); + $this->assertTrue($this->_db->checkError()); + $this->_db = &DBManagerFactory::getInstance(); + } + + public function testQuote() + { + $string = "'dog eat "; + + if ( $this->_db->dbType == 'mysql') + $this->assertEquals($this->_db->quoteForEmail($string),"\'dog eat "); + else + $this->assertEquals($this->_db->quoteForEmail($string),"''dog eat "); + } + + public function testQuoteForEmail() + { + $string = "'dog eat "; + + if ( $this->_db->dbType == 'mysql') + $this->assertEquals($this->_db->quoteForEmail($string),"\'dog eat "); + else + $this->assertEquals($this->_db->quoteForEmail($string),"''dog eat "); + } + + public function testArrayQuote() + { + $string = array("'dog eat "); + $this->_db->arrayQuote($string); + if ( $this->_db->dbType == 'mysql') + $this->assertEquals($string,array("\'dog eat ")); + else + $this->assertEquals($string,array("''dog eat ")); + } + + public function testQuery() + { + $beanIds = $this->_createRecords(5); + + $result = $this->_db->query("SELECT id From contacts where last_name = 'foobar'"); + if ( $this->_db instanceOf MysqliManager ) + $this->assertType('Mysqli_result',$result); + else + $this->assertTrue(is_resource($result)); + + while ( $row = $this->_db->fetchByAssoc($result) ) + $this->assertTrue(in_array($row['id'],$beanIds),"Id not found '{$row['id']}'"); + + $this->_removeRecords($beanIds); + } + + public function disabledLimitQuery() + { + $beanIds = $this->_createRecords(5); + $_REQUEST['module'] = 'contacts'; + $result = $this->_db->limitQuery("SELECT id From contacts where last_name = 'foobar'",1,3); + if ( $this->_db instanceOf MysqliManager ) + $this->assertType('Mysqli_result',$result); + else + $this->assertTrue(is_resource($result)); + + while ( $row = $this->_db->fetchByAssoc($result) ) { + if ( $row['id'][0] > 3 || $row['id'][0] < 0 ) + $this->assertFalse(in_array($row['id'],$beanIds),"Found {$row['id']} in error"); + else + $this->assertTrue(in_array($row['id'],$beanIds),"Didn't find {$row['id']}"); + } + unset($_REQUEST['module']); + $this->_removeRecords($beanIds); + } + + public function testGetOne() + { + $beanIds = $this->_createRecords(1); + + $id = $this->_db->getOne("SELECT id From contacts where last_name = 'foobar'"); + $this->assertEquals($id,$beanIds[0]); + + $this->_removeRecords($beanIds); + } + + public function testGetFieldsArray() + { + $beanIds = $this->_createRecords(1); + + $result = $this->_db->query("SELECT id From contacts where id = '{$beanIds[0]}'"); + $fields = $this->_db->getFieldsArray($result,true); + + $this->assertEquals(array("id"),$fields); + + $this->_removeRecords($beanIds); + } + + public function testGetRowCount() + { + $beanIds = $this->_createRecords(1); + + $result = $this->_db->query("SELECT id From contacts where id = '{$beanIds[0]}'"); + + $this->assertEquals($this->_db->getRowCount($result),1); + + $this->_removeRecords($beanIds); + } + + public function testGetAffectedRowCount() + { + if ( ($this->_db instanceOf MysqliManager) ) + $this->markTestSkipped('Skipping on Mysqli; doesn\'t apply to this backend'); + + $beanIds = $this->_createRecords(1); + $result = $this->_db->query("DELETE From contacts where id = '{$beanIds[0]}'"); + $this->assertEquals($this->_db->getAffectedRowCount(),1); + } + + public function testFetchByAssoc() + { + $beanIds = $this->_createRecords(1); + + $result = $this->_db->query("SELECT id From contacts where id = '{$beanIds[0]}'"); + + $row = $this->_db->fetchByAssoc($result); + + $this->assertTrue(is_array($row)); + $this->assertEquals($row['id'],$beanIds[0]); + + $this->_removeRecords($beanIds); + } + + public function testConnect() + { + // TODO: Write this test + } + + public function testDisconnect() + { + $this->_db->disconnect(); + $this->assertTrue($this->_db->checkError()); + $this->_db = &DBManagerFactory::getInstance(); + } + + public function testGetTablesArray() + { + $tablename = 'test' . date("YmdHis"); + $this->_db->createTableParams($tablename, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array() + ); + + $this->assertTrue($this->_db->tableExists($tablename)); + + $this->_db->dropTableName($tablename); + } + + public function testVersion() + { + $ver = $this->_db->version(); + + $this->assertTrue(is_string($ver)); + } + + public function testTableExists() + { + $tablename = 'test' . date("YmdHis"); + $this->_db->createTableParams($tablename, + array( + 'foo' => array ( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array() + ); + + $this->assertTrue(in_array($tablename,$this->_db->getTablesArray())); + + $this->_db->dropTableName($tablename); + } + + public function providerCompareVardefs() + { + $returnArray = array( + array( + array( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + array( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + true), + array( + array( + 'name' => 'foo', + 'type' => 'char', + 'len' => '255', + ), + array( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + false), + array( + array( + 'name' => 'foo', + 'type' => 'char', + 'len' => '255', + ), + array( + 'name' => 'foo', + 'len' => '255', + ), + false), + array( + array( + 'name' => 'foo', + 'len' => '255', + ), + array( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + true), + array( + array( + 'name' => 'foo', + 'type' => 'varchar', + 'len' => '255', + ), + array( + 'name' => 'FOO', + 'type' => 'varchar', + 'len' => '255', + ), + true), + ); + + return $returnArray; + } + + /** + * @dataProvider providerCompareVarDefs + */ + public function testCompareVarDefs($fieldDef1,$fieldDef2,$expectedResult) + { + if ( $expectedResult ) { + $this->assertTrue($this->_db->compareVarDefs($fieldDef1,$fieldDef2)); + } + else { + $this->assertFalse($this->_db->compareVarDefs($fieldDef1,$fieldDef2)); + } + } + + public function providerConvert() + { + $db = DBManagerFactory::getInstance(); + + $returnArray = array( + array( + array('foo','nothing'), + 'foo' + ) + ); + if ( $db instanceOf MysqlManager ) + $returnArray += array( + array( + array('foo','today'), + 'CURDATE()' + ), + array( + array('foo','left'), + 'LEFT(foo)' + ), + array( + array('foo','left',array('1','2','3')), + 'LEFT(foo,1,2,3)' + ), + array( + array('foo','date_format'), + 'DATE_FORMAT(foo)' + ), + array( + array('foo','date_format',array('1','2','3')), + 'DATE_FORMAT(foo,1,2,3)' + ), + array( + array('foo','datetime',array("'%Y-%m'")), + 'DATE_FORMAT(foo, \'%Y-%m-%d %H:%i:%s\')' + ), + array( + array('foo','IFNULL'), + 'IFNULL(foo)' + ), + array( + array('foo','IFNULL',array('1','2','3')), + 'IFNULL(foo,1,2,3)' + ), + array( + array('foo','CONCAT',array('1','2','3')), + 'CONCAT(foo,1,2,3)' + ), + array( + array('foo','text2char'), + 'foo' + ), + ); + if ( $db instanceOf MssqlManager ) + $returnArray += array( + array( + array('foo','today'), + 'GETDATE()' + ), + array( + array('foo','left'), + 'LEFT(foo)' + ), + array( + array('foo','left',array('1','2','3')), + 'LEFT(foo,1,2,3)' + ), + array( + array('foo','date_format'), + 'CONVERT(varchar(10),foo,120)' + ), + array( + array('foo','date_format',array('1','2','3')), + 'CONVERT(varchar(10),foo,120)' + ), + array( + array('foo','date_format',array("'%Y-%m'")), + 'CONVERT(varchar(7),foo,120)' + ), + array( + array('foo','IFNULL'), + 'ISNULL(foo)' + ), + array( + array('foo','IFNULL',array('1','2','3')), + 'ISNULL(foo,1,2,3)' + ), + array( + array('foo','CONCAT',array('1','2','3')), + 'foo+1+2+3' + ), + array( + array('foo','text2char'), + 'CAST(foo AS varchar(8000))' + ), + ); + if ( $db instanceOf SqlsrvManager ) + $returnArray += array( + array( + array('foo','datetime'), + 'CONVERT(varchar(20),foo,120)' + ), + ); + + return $returnArray; + } + + /** + * @group bug33283 + * @dataProvider providerConvert + */ + public function testConvert( + array $parameters, + $result + ) + { + if ( count($parameters) < 3 ) + $this->assertEquals( + $this->_db->convert($parameters[0],$parameters[1]), + $result); + elseif ( count($parameters) < 4 ) + $this->assertEquals( + $this->_db->convert($parameters[0],$parameters[1],$parameters[2]), + $result); + else + $this->assertEquals( + $this->_db->convert($parameters[0],$parameters[1],$parameters[2],$parameters[3]), + $result); + } + + /** + * @group bug33283 + */ + public function testConcat() + { + $ret = $this->_db->concat('foo',array('col1','col2','col3')); + + if ( $this->_db instanceOf MysqlManager ) + $this->assertEquals($ret, + "CONCAT(IFNULL(foo.col1,''),' ',IFNULL(foo.col2,''),' ',IFNULL(foo.col3,''))" + ); + if ( $this->_db instanceOf MssqlManager ) + $this->assertEquals($ret, + "CONCAT(IFNULL(foo.col1,''),' ',IFNULL(foo.col2,''),' ',IFNULL(foo.col3,''))" + ); + if ( $this->_db instanceOf OracleManager ) + $this->assertEquals($ret, + "CONCAT(IFNULL(foo.col1,''),' ',IFNULL(foo.col2,''),' ',IFNULL(foo.col3,''))" + ); + } + + public function providerFromConvert() + { + $returnArray = array( + array( + array('foo','nothing'), + 'foo' + ) + ); + if ( $this->_db instanceOf MssqlManager + || $this->_db instanceOf OracleManager ) + $returnArray += array( + array( + array('2009-01-01 12:00:00','date'), + '2009-01-01' + ), + array( + array('2009-01-01 12:00:00','time'), + '12:00:00' + ) + ); + + return $returnArray; + } + + /** + * @group bug33283 + * @dataProvider providerFromConvert + */ + public function testFromConvert( + array $parameters, + $result + ) + { + $this->assertEquals( + $this->_db->fromConvert($parameters[0],$parameters[1]), + $result); + } + + /** + * @group bug34892 + */ + public function testMssqlNotClearingErrorResults() + { + if ( get_class($this->_db) != 'MssqlManager' ) + $this->markTestSkipped('Skipping; only applies with php_mssql driver'); + + // execute a bad query + $this->_db->query("select dsdsdsdsdsdsdsdsdsd"); + // assert it found an error + $this->assertTrue($this->_db->checkError()); + // now, execute a good query + $this->_db->query("select * from config"); + // and make no error messages are asserted + $this->assertFalse($this->_db->checkError()); + } +} diff --git a/tests/include/database/FreeTDSManagerTest.php b/tests/include/database/FreeTDSManagerTest.php new file mode 100755 index 00000000..c3676bb7 --- /dev/null +++ b/tests/include/database/FreeTDSManagerTest.php @@ -0,0 +1,28 @@ +_db = DBManagerFactory::getInstance(); + if(get_class($this->_db) != 'FreeTDSManager') { + $this->markTestSkipped("Skipping test if not mssql configuration"); + } + } + + public function testAppendnAddsNCorrectly() + { + $sql = $this->_db->appendN('SELECT name FROM accounts where name = \'Test\''); + $this->assertEquals($sql, 'SELECT name FROM accounts where name = N\'Test\'', 'Assert N was added.'); + + $sql = $this->_db->appendN('SELECT name FROM accounts where name = \'O\\\'Rielly\''); + $this->assertEquals($sql, 'SELECT name FROM accounts where name = N\'O\\\'Rielly\'', 'Assert N was added.'); + } + +} diff --git a/tests/include/javascript/JSAlertsTest.php b/tests/include/javascript/JSAlertsTest.php new file mode 100755 index 00000000..5502a934 --- /dev/null +++ b/tests/include/javascript/JSAlertsTest.php @@ -0,0 +1,70 @@ +beans = array(); + $this->old_user = $current_user; + $current_user = $this->_user = SugarTestUserUtilities::createAnonymousUser(); + $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']); + $GLOBALS['app_strings'] = return_application_language($GLOBALS['current_language']); + } + + public function tearDown() + { + foreach($this->beans as $bean) { + $bean->mark_deleted($bean->id); + } + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['app_list_strings']); + unset($GLOBALS['current_user']); + unset($GLOBALS['app_strings']); + } + + protected function createNewMeeting() + { + $m = new Meeting(); + $m->name = "40541TestMeeting"; + $m->date_start = gmdate($GLOBALS['timedate']->get_db_date_time_format(), time() + 3000); + $m->duration_hours = 0; + $m->duration_minutes = 15; + $m->reminder_time = 60; + $m->reminder_checked = true; + $m->save(); + $m->load_relationship("users"); + $m->users->add($this->_user->id); + $this->beans[] = $m; + return $m; + } + + public function testGetAlertsForUser() + { + + global $app_list_strings; + $app_list_strings['reminder_max_time'] = 5000; + $m = $this->createNewMeeting(); + $alerts = new jsAlerts(); + $script = $alerts->getScript(); + $this->assertRegExp("/addAlert.*\"{$m->name}\"/", $script); + } + + public function testGetDeclinedAlertsForUser() + { + + global $app_list_strings; + $app_list_strings['reminder_max_time'] = 5000; + $m = $this->createNewMeeting(); + //Decline the meeting + $query = "UPDATE meetings_users SET deleted = 0, accept_status = 'decline' " . + "WHERE meeting_id = '$m->id' AND user_id = '{$this->_user->id}'"; + $m->db->query($query); + $alerts = new jsAlerts(); + $script = $alerts->getScript(); + $this->assertNotRegExp("/addAlert.*\"{$m->name}\"/", $script); + } +} diff --git a/tests/include/javascript/JavascriptTest.php b/tests/include/javascript/JavascriptTest.php new file mode 100755 index 00000000..fd8209c5 --- /dev/null +++ b/tests/include/javascript/JavascriptTest.php @@ -0,0 +1,36 @@ +_javascript = new javascript(); + } + + public function providerBuildStringToTranslateInSmarty() + { + return array( + array( + "LBL_TEST", + "{/literal}{sugar_translate label='LBL_TEST' module='' for_js=true}{literal}", + ), + array( + array("LBL_TEST","LBL_TEST_2"), + "{/literal}{sugar_translate label='LBL_TEST' module='' for_js=true}{literal}{/literal}{sugar_translate label='LBL_TEST_2' module='' for_js=true}{literal}", + ), + ); + } + + /** + * @dataProvider providerBuildStringToTranslateInSmarty + * @ticket 41983 + */ + public function testBuildStringToTranslateInSmarty($string, $returnedString) + { + $this->assertEquals($returnedString, $this->_javascript->buildStringToTranslateInSmarty($string)); + } +} diff --git a/tests/include/utils/Bug22882Test.php b/tests/include/utils/Bug22882Test.php new file mode 100755 index 00000000..da6c3bfc --- /dev/null +++ b/tests/include/utils/Bug22882Test.php @@ -0,0 +1,303 @@ +loadFilesDeletedValue(); + $resultfr = return_app_list_strings_language('fr_test'); + $resulten = return_app_list_strings_language('en_us'); + $resultfr = array_keys($resultfr['account_type_dom']); + $resulten = array_keys($resulten['account_type_dom']); + if($this->isSameSize($resultfr, $resulten)){ + $this->isEqual($resultfr, $resulten); + } + $this->cleanupFiles(); + } + + public function testMultiLanguagesDeletedValueFrOnly() + { + $this->loadFilesDeletedValueFrOnly(); + $resultfr = return_app_list_strings_language('fr_test'); + $resulten = return_app_list_strings_language('en_us'); + $resultfr = array_keys($resultfr['account_type_dom']); + $resulten = array_keys($resulten['account_type_dom']); + $this->assertNotEquals(count($resultfr), count($resulten), 'The 2 drop down list have the same size.'); + $this->cleanupFiles(); + } + + public function testMultiLanguagesDeletedValueEnOnly() + { + $this->loadFilesDeletedValueEnOnly(); + $resultfr = return_app_list_strings_language('fr_test'); + $resulten = return_app_list_strings_language('en_us'); + $resultfr = array_keys($resultfr['account_type_dom']); + $resulten = array_keys($resulten['account_type_dom']); + $this->assertNotEquals(count($resultfr),count($resulten)); + $this->assertFalse(in_array('Customer',$resulten)); + $this->assertTrue(in_array('Customer',$resultfr)); + $this->cleanupFiles(); + } + + public function testMultiLanguagesAddedValue() + { + $this->loadFilesAddedValueEn(); + $resultfr = return_app_list_strings_language('fr_test'); + $resulten = return_app_list_strings_language('en_us'); + $resultfr = array_keys($resultfr['account_type_dom']); + $resulten = array_keys($resulten['account_type_dom']); + $this->assertNotEquals(count($resultfr), count($resulten), 'The 2 drop down list have the same size.'); + $this->cleanupFiles(); + } + + public function loadFilesDeletedValue(){ + $file_fr = << 'Analyste', Line deleted + 'Competitor' => 'Concurrent', + 'Customer' => 'Client', + 'Integrator' => 'Intégrateur', + 'Investor' => 'Investisseur', + 'Partner' => 'Partenaire', + 'Press' => 'Presse', + 'Prospect' => 'Prospect', + 'Other' => 'Autre', + '' => '', +); +FRFR; + $file_en = << 'Analyst', Line deleted + 'Competitor' => 'Competitor', + 'Customer' => 'Customer', + 'Integrator' => 'Integrator', + 'Investor' => 'Investor', + 'Partner' => 'Partner', + 'Press' => 'Press', + 'Prospect' => 'Prospect', + 'Other' => 'Other', + '' => '', +); +ENEN; + if(!file_exists('include/language/fr_test.lang.php')){ + $this->file = file_get_contents('include/language/en_us.lang.php'); + file_put_contents('include/language/fr_test.lang.php', $this->file); + } + if(!file_exists('custom/include/language/fr_test.lang.php')){ + file_put_contents('custom/include/language/fr_test.lang.php', $file_fr); + }else{ + $this->file_fr_tmp = file_get_contents('custom/include/language/fr_test.lang.php'); + file_put_contents('custom/include/language/fr_test.lang.php', $file_fr); + } + if(!file_exists('custom/include/language/en_us.lang.php')){ + file_put_contents('custom/include/language/en_us.lang.php', $file_en); + }else{ + $this->file_en_tmp = file_get_contents('custom/include/language/en_us.lang.php'); + file_put_contents('custom/include/language/en_us.lang.php', $file_en); + } + } + + public function loadFilesDeletedValueFrOnly(){ + $file_fr = << 'Analyste', Line deleted + 'Competitor' => 'Concurrent', + 'Customer' => 'Client', + 'Integrator' => 'Intégrateur', + 'Investor' => 'Investisseur', + 'Partner' => 'Partenaire', + 'Press' => 'Presse', + 'Prospect' => 'Prospect', + 'Other' => 'Autre', + '' => '', +); +FRFR; + $file_en = << 'Analyst', + 'Competitor' => 'Competitor', + 'Customer' => 'Customer', + 'Integrator' => 'Integrator', + 'Investor' => 'Investor', + 'Partner' => 'Partner', + 'Press' => 'Press', + 'Prospect' => 'Prospect', + 'Other' => 'Other', + '' => '', +); +ENEN; + if(!file_exists('include/language/fr_test.lang.php')){ + $this->file = file_get_contents('include/language/en_us.lang.php'); + file_put_contents('include/language/fr_test.lang.php', $this->file); + } + if(!file_exists('custom/include/language/fr_test.lang.php')){ + file_put_contents('custom/include/language/fr_test.lang.php', $file_fr); + }else{ + $this->file_fr_tmp = file_get_contents('custom/include/language/fr_test.lang.php'); + file_put_contents('custom/include/language/fr_test.lang.php', $file_fr); + } + if(!file_exists('custom/include/language/en_us.lang.php')){ + file_put_contents('custom/include/language/en_us.lang.php', $file_en); + }else{ + $this->file_en_tmp = file_get_contents('custom/include/language/en_us.lang.php'); + file_put_contents('custom/include/language/en_us.lang.php', $file_en); + } + } + + public function loadFilesDeletedValueEnOnly(){ + $file_fr = << 'Analyste', + 'Competitor' => 'Concurrent', + 'Customer' => 'Client', + 'Integrator' => 'Intégrateur', + 'Investor' => 'Investisseur', + 'Partner' => 'Partenaire', + 'Press' => 'Presse', + 'Prospect' => 'Prospect', + 'Other' => 'Autre', + '' => '', +); +FRFR; + $file_en = << 'Analyst', + 'Competitor' => 'Competitor', + //'Customer' => 'Customer', + 'Integrator' => 'Integrator', + 'Investor' => 'Investor', + 'Partner' => 'Partner', + 'Press' => 'Press', + 'Prospect' => 'Prospect', + 'Other' => 'Other', + '' => '', +); +ENEN; + if(!file_exists('include/language/fr_test.lang.php')){ + $this->file = file_get_contents('include/language/en_us.lang.php'); + file_put_contents('include/language/fr_test.lang.php', $this->file); + } + if(!file_exists('custom/include/language/fr_test.lang.php')){ + file_put_contents('custom/include/language/fr_test.lang.php', $file_fr); + }else{ + $this->file_fr_tmp = file_get_contents('custom/include/language/fr_test.lang.php'); + file_put_contents('custom/include/language/fr_test.lang.php', $file_fr); + } + if(!file_exists('custom/include/language/en_us.lang.php')){ + file_put_contents('custom/include/language/en_us.lang.php', $file_en); + }else{ + $this->file_en_tmp = file_get_contents('custom/include/language/en_us.lang.php'); + file_put_contents('custom/include/language/en_us.lang.php', $file_en); + } + } + + public function loadFilesAddedValueEn(){ + $file_fr = << 'Analyste', + 'Competitor' => 'Concurrent', + 'Customer' => 'Client', + 'Integrator' => 'Intégrateur', + 'Investor' => 'Investisseur', + 'Partner' => 'Partenaire', + 'Press' => 'Presse', + 'Prospect' => 'Prospect', + 'Other' => 'Autre', + '' => '', +); +FRFR; + $file_en = << 'Extra', + 'Analyst' => 'Analyst', + 'Competitor' => 'Competitor', + 'Customer' => 'Customer', + 'Integrator' => 'Integrator', + 'Investor' => 'Investor', + 'Partner' => 'Partner', + 'Press' => 'Press', + 'Prospect' => 'Prospect', + 'Other' => 'Other', + '' => '', +); +ENEN; + if(!file_exists('include/language/fr_test.lang.php')){ + $this->file = file_get_contents('include/language/en_us.lang.php'); + file_put_contents('include/language/fr_test.lang.php', $this->file); + } + if(!file_exists('custom/include/language/fr_test.lang.php')){ + file_put_contents('custom/include/language/fr_test.lang.php', $file_fr); + }else{ + $this->file_fr_tmp = file_get_contents('custom/include/language/fr_test.lang.php'); + file_put_contents('custom/include/language/fr_test.lang.php', $file_fr); + } + if(!file_exists('custom/include/language/en_us.lang.php')){ + file_put_contents('custom/include/language/en_us.lang.php', $file_en); + }else{ + $this->file_en_tmp = file_get_contents('custom/include/language/en_us.lang.php'); + file_put_contents('custom/include/language/en_us.lang.php', $file_en); + } + } + + public function cleanupFiles(){ + if(!empty($this->file)){ + $this->file = ''; + unlink('include/language/fr_test.lang.php'); + } + if(!empty($this->file_fr_tmp)){ + file_put_contents('custom/include/language/fr_test.lang.php', $this->file_fr_tmp); + $this->file_fr_tmp = ''; + }else{ + unlink('custom/include/language/fr_test.lang.php'); + } + if(!empty($this->file_en_tmp)){ + file_put_contents('custom/include/language/en_us.lang.php', $this->file_en_tmp); + $this->file_en_tmp = ''; + }else{ + unlink('custom/include/language/en_us.lang.php'); + } + } + + public function isSameSize($result1, $result2) + { + if(count($result1) != count($result2)){ + $this->assertTrue(false, 'The 2 drop down list didn\'t have the same size.'); + return false; + } + return true; + } + + public function isEqual($result1, $result2) + { + foreach($result1 as $k=>$v){ + $this->assertTrue(in_array($v,$result2)); + } + foreach($result2 as $k=>$v){ + $this->assertTrue(in_array($v,$result1)); + } + } +} diff --git a/tests/include/utils/Bug33284_Test.php b/tests/include/utils/Bug33284_Test.php new file mode 100755 index 00000000..49d38dd4 --- /dev/null +++ b/tests/include/utils/Bug33284_Test.php @@ -0,0 +1,52 @@ +max_display_set = true; + $this->max_display_length = $sugar_config['tracker_max_display_length']; + } + } + + public function tearDown() { + if($this->max_display_set) { + global $sugar_config; + $sugar_config['tracker_max_display_length'] = $this->max_display_length; + } + } + + public function test_get_tracker_substring1() + { + global $sugar_config; + $sugar_config['tracker_max_display_length'] = 20; + $test_string = ' Hello There How Are You? '; + $display_string = getTrackerSubstring($test_string); + $this->assertEquals(strlen($display_string), 20, 'Assert that the string length is equal to 20 characters'); + } + + /* + public function test_get_tracker_substring2() + { + global $sugar_config; + unset($sugar_config['tracker_max_display_length']); + $test_string = ' Hello There How Are You? '; + + $default_length = 15; + + + $display_string = getTrackerSubstring($test_string); + $this->assertEquals(strlen($display_string), $default_length, 'Assert that the string length is equal to 15 characters (default)'); + + $test_string = '科學家發現史上最大恐龍腳印科學家發現史上最大恐龍腳印'; + $display_string = getTrackerSubstring($test_string); + $this->assertEquals(mb_strlen($display_string), $default_length, 'Assert that the string length is equal to 15 characters (default)'); + } + */ +} + +?> \ No newline at end of file diff --git a/tests/include/utils/Bug42427Test.php b/tests/include/utils/Bug42427Test.php new file mode 100755 index 00000000..c3e3c82c --- /dev/null +++ b/tests/include/utils/Bug42427Test.php @@ -0,0 +1,44 @@ +_backup_default_language = $sugar_config['default_language']; + } + } + + public function tearDown() + { + unlink('include/language/fr_test.lang.php'); + unlink('include/language/de_test.lang.php'); + + sugar_cache_clear('app_list_strings.en_us'); + sugar_cache_clear('app_list_strings.fr_test'); + sugar_cache_clear('app_list_strings.de_test'); + + if ( isset($this->_backup_default_language) ) { + $sugar_config['default_language'] = $this->_backup_default_language; + } + } + + public function testWillLoadEnUsStringIfDefaultLanguageIsNotEnUs() + { + file_put_contents('include/language/fr_test.lang.php', ''); + file_put_contents('include/language/de_test.lang.php', ''); + + $sugar_config['default_language'] = 'fr_test'; + + $strings = return_app_list_strings_language('de_test'); + + $this->assertArrayHasKey('lead_source_default_key',$strings); + } +} diff --git a/tests/include/utils/CheckPhpVersionTest.php b/tests/include/utils/CheckPhpVersionTest.php new file mode 100755 index 00000000..9924d7e6 --- /dev/null +++ b/tests/include/utils/CheckPhpVersionTest.php @@ -0,0 +1,32 @@ +assertEquals($expected_retval, check_php_version($ver), $message); + } +} diff --git a/tests/include/utils/CheckPlatformTest.php b/tests/include/utils/CheckPlatformTest.php new file mode 100755 index 00000000..9b9628ae --- /dev/null +++ b/tests/include/utils/CheckPlatformTest.php @@ -0,0 +1,16 @@ +_isOnWindows = (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'); + } + + public function testVerifyIfWeAreOnWindows() + { + $this->assertEquals(is_windows(), $this->_isOnWindows); + } +} + diff --git a/tests/include/utils/CreateCacheDirectoryTest.php b/tests/include/utils/CreateCacheDirectoryTest.php new file mode 100755 index 00000000..92eaca79 --- /dev/null +++ b/tests/include/utils/CreateCacheDirectoryTest.php @@ -0,0 +1,64 @@ +_original_cwd = getcwd(); + chdir(dirname(__FILE__)); + $this->_removeCacheDirectory('./cache'); + } + + public function tearDown() + { + $this->_removeCacheDirectory('./cache'); + chdir($this->_original_cwd); + } + + private function _removeCacheDirectory($dir) + { + $dir_handle = @opendir($dir); + if ($dir_handle === false) { + return; + } + while (($filename = readdir($dir_handle)) !== false) { + if ($filename == '.' || $filename == '..') { + continue; + } + if (is_dir("{$dir}/{$filename}")) { + $this->_removecacheDirectory("{$dir}/{$filename}"); + } else { + unlink("{$dir}/{$filename}"); + } + } + closedir($dir_handle); + rmdir("{$dir}"); + } + + public function testCreatesCacheDirectoryIfDoesnotExist() + { + $this->assertFalse(file_exists('./cache'), 'check that the cache directory does not exist'); + create_cache_directory('foobar'); + $this->assertTrue(file_exists('./cache'), 'creates a cache directory'); + } + + public function testCreatesDirectoryInCacheDirectoryProvidedItIsGivenAFile() + { + $this->assertFalse(file_exists('./cache/foobar-test')); + create_cache_directory('foobar-test/cache-file.php'); + $this->assertTrue(file_exists('./cache/foobar-test')); + } + + public function testReturnsDirectoryCreated() + { + $created = create_cache_directory('foobar/cache-file.php'); + $this->assertEquals( + 'cache/foobar/cache-file.php', + $created + ); + } +} + diff --git a/tests/include/utils/DbUtilsTest.php b/tests/include/utils/DbUtilsTest.php new file mode 100755 index 00000000..260eb46e --- /dev/null +++ b/tests/include/utils/DbUtilsTest.php @@ -0,0 +1,61 @@ +_random = rand(100, 200); + $GLOBALS['from_html_cache_clear'] = true; + $this->_old_toHTML = $GLOBALS['toHTML']; + $GLOBALS['toHTML'] = array( + 'foobar' => 'barfoo', + $this->_random => 'random', + ); + } + + public function tearDown() + { + $GLOBALS['toHTML'] = $this->_old_toHTML; + } + + public function testReturnsSameValueOnNoneStrings() + { + $random = rand(100, 200); + $this->assertEquals(from_html($random), $random); + } + + public function testSwapsValuesForKeysFromToHTMLGlobal() + { + $GLOBALS['toHTML']['foobar'] = 'barfoo'; + $this->assertEquals(from_html('barfoo'), 'foobar'); + } + + public function testSwapsValuesForKeysFromToHTMLGlobalWithRandomData() + { + $this->assertEquals(from_html('random'), $this->_random); + } + + public function testWillReturnTheSameValueTwiceInARow() + { + unset($GLOBALS['from_html_clear_cache']); + $GLOBALS['toHTML']['foobar'] = 'barfoo'; + $this->assertEquals(from_html('barfoo'), 'foobar'); + $this->assertEquals(from_html('barfoo'), 'foobar'); + } + + public function testWillReturnRawValueIfEncodeParameterIsFalse() + { + $GLOBALS['toHTML']['foobar'] = 'barfoo'; + $this->assertEquals(from_html('barfoo', false), 'barfoo'); + } +} + diff --git a/tests/include/utils/DeepArrayDiffTest.php b/tests/include/utils/DeepArrayDiffTest.php new file mode 100755 index 00000000..77e6bb05 --- /dev/null +++ b/tests/include/utils/DeepArrayDiffTest.php @@ -0,0 +1,36 @@ + true, + 'value2' => false, + 'value3' => 'yummy' + ); + + $array2 = array( + 'value1' => true, + 'value2' => true, + 'value3' => 'yummy' + ); + + $diffs = deepArrayDiff($array1,$array2); + + $this->assertEquals($diffs['value2'], false); + $this->assertFalse(isset($diffs['value1'])); + $this->assertFalse(isset($diffs['value3'])); + + + $diffs = deepArrayDiff($array2,$array1); + + $this->assertEquals($diffs['value2'], true); + $this->assertFalse(isset($diffs['value1'])); + $this->assertFalse(isset($diffs['value3'])); + } +} diff --git a/tests/include/utils/ExternalCacheAPITest.php b/tests/include/utils/ExternalCacheAPITest.php new file mode 100755 index 00000000..396df287 --- /dev/null +++ b/tests/include/utils/ExternalCacheAPITest.php @@ -0,0 +1,69 @@ +_cacheKey1 = 'test cache key 1 '.date("YmdHis"); + $this->_cacheValue1 = 'test cache value 1'.date("YmdHis"); + $this->_cacheKey2 = 'test cache key 2 '.date("YmdHis"); + $this->_cacheValue2 = 'test cache value 2 '.date("YmdHis"); + } + + public function tearDown() + { + // clear out the test cache if we haven't already + if ( sugar_cache_retrieve($this->_cacheKey1) ) + sugar_cache_clear($this->_cacheKey1); + if ( sugar_cache_retrieve($this->_cacheKey2) ) + sugar_cache_clear($this->_cacheKey2); + } + + public function testSugarCacheValidate() + { + $this->assertTrue(sugar_cache_validate()); + $this->assertTrue($GLOBALS['external_cache_checked']); + } + + public function testStoreAndRetrieve() + { + sugar_cache_put($this->_cacheKey1,$this->_cacheValue1); + sugar_cache_put($this->_cacheKey2,$this->_cacheValue2); + $this->assertEquals( + sugar_cache_retrieve($this->_cacheKey1), + $this->_cacheValue1); + $this->assertEquals( + sugar_cache_retrieve($this->_cacheKey2), + $this->_cacheValue2); + } + + public function testStoreClearCacheKeyAndRetrieve() + { + sugar_cache_put($this->_cacheKey1,$this->_cacheValue1); + sugar_cache_put($this->_cacheKey2,$this->_cacheValue2); + sugar_cache_clear($this->_cacheKey1); + $this->assertNotEquals( + sugar_cache_retrieve($this->_cacheKey1), + $this->_cacheValue1); + $this->assertEquals( + sugar_cache_retrieve($this->_cacheKey2), + $this->_cacheValue2); + } + + public function testStoreResetCacheAndRetrieve() + { + $this->markTestSkipped('Not working as expected'); + + sugar_cache_put($this->_cacheKey1,$this->_cacheValue1); + sugar_cache_put($this->_cacheKey2,$this->_cacheValue2); + sugar_cache_reset(); + $this->assertNotEquals( + sugar_cache_retrieve($this->_cacheKey1), + $this->_cacheValue1); + $this->assertNotEquals( + sugar_cache_retrieve($this->_cacheKey2), + $this->_cacheValue2); + } +} + diff --git a/tests/include/utils/SugarArrayMergeRecursiveTest.php b/tests/include/utils/SugarArrayMergeRecursiveTest.php new file mode 100755 index 00000000..5870a8b8 --- /dev/null +++ b/tests/include/utils/SugarArrayMergeRecursiveTest.php @@ -0,0 +1,82 @@ + array("two" => array("three" => array("some" => "stuff")))); + $array2 = array("one" => array("two" => array("three" => array("more" => "stuff")))); + $expected = array("one" => array("two" => array("three" => array("more" => "stuff", "some" => "stuff")))); + $results = sugarArrayMergeRecursive($array1,$array2); + $this->assertEquals($results, $expected); + } + + /** + * this one won't preserve order + */ + public function testSubArrayKeysArePreserved() + { + $array1 = array( + 'dog' => array( + 'dog1' => 'dog1', + 'dog2' => 'dog2', + 'dog3' => 'dog3', + 'dog4' => 'dog4', + ) + ); + + $array2 = array( + 'dog' => array( + 'dog2' => 'dog2', + 'dog1' => 'dog1', + 'dog3' => 'dog3', + 'dog4' => 'dog4', + ) + ); + + $results = sugarArrayMergeRecursive($array1,$array2); + + $keys1 = sort(array_keys($results['dog'])); + $keys2 = sort(array_keys($array2['dog'])); + + $this->assertEquals($keys1,$keys2); + } + + public function testSugarArrayMergeMergesTwoArraysWithLikeKeysOverwritingExistingKeys() + { + $foo = array( + 'one' => 123, + 'two' => 123, + 'foo' => array( + 'int' => 123, + 'foo' => 'bar', + ), + ); + $bar = array( + 'one' => 123, + 'two' => 321, + 'foo' => array( + 'int' => 123, + 'bar' => 'foo', + ), + ); + + $expected = array( + 'one' => 123, + 'two' => 321, + 'foo' => array( + 'int' => 123, + 'foo' => 'bar', + 'bar' => 'foo', + ), + ); + $this->assertEquals(sugarArrayMergeRecursive($foo, $bar), $expected); + // insure that internal functions can't duplicate behavior + $this->assertNotEquals(array_merge($foo, $bar), $expected); + $this->assertNotEquals(array_merge_recursive($foo, $bar), $expected); + } +} diff --git a/tests/include/utils/SugarArrayMergeTest.php b/tests/include/utils/SugarArrayMergeTest.php new file mode 100755 index 00000000..c694d724 --- /dev/null +++ b/tests/include/utils/SugarArrayMergeTest.php @@ -0,0 +1,72 @@ + array( + 'dog1' => 'dog1', + 'dog2' => 'dog2', + 'dog3' => 'dog3', + 'dog4' => 'dog4', + ) + ); + + $array2 = array( + 'dog' => array( + 'dog2' => 'dog2', + 'dog1' => 'dog1', + 'dog3' => 'dog3', + 'dog4' => 'dog4', + ) + ); + + $results = sugarArrayMerge($array1,$array2); + + $keys1 = array_keys($results['dog']); + $keys2 = array_keys($array2['dog']); + + for ( $i = 0; $i < 4; $i++ ) { + $this->assertEquals($keys1[$i],$keys2[$i]); + } + } + + public function testSugarArrayMergeMergesTwoArraysWithLikeKeysOverwritingExistingKeys() + { + $foo = array( + 'one' => 123, + 'two' => 123, + 'foo' => array( + 'int' => 123, + 'foo' => 'bar', + ), + ); + $bar = array( + 'one' => 123, + 'two' => 321, + 'foo' => array( + 'int' => 123, + 'bar' => 'foo', + ), + ); + + $expected = array( + 'one' => 123, + 'two' => 321, + 'foo' => array( + 'int' => 123, + 'foo' => 'bar', + 'bar' => 'foo', + ), + ); + $this->assertEquals(sugarArrayMerge($foo, $bar), $expected); + // insure that internal functions can't duplicate behavior + $this->assertNotEquals(array_merge($foo, $bar), $expected); + $this->assertNotEquals(array_merge_recursive($foo, $bar), $expected); + } +} diff --git a/tests/include/utils/SugarArrayTest.php b/tests/include/utils/SugarArrayTest.php new file mode 100755 index 00000000..e7c9eab1 --- /dev/null +++ b/tests/include/utils/SugarArrayTest.php @@ -0,0 +1,72 @@ + array( + $random => array( + 'bar' => $random, + ), + ), + ); + + $array = new SugarArray($array); + $this->assertEquals($array->get("foo.{$random}.bar"), $random); + } + + public function testReturnsDefaultValueWhenDoesNotContainRequestedValue() + { + $random = rand(100, 200); + $array = new SugarArray(array()); + $this->assertEquals($array->get('unknown', $random), $random); + } + + public function testImplementsArrayAccess() + { + $reflection = new ReflectionClass('SugarArray'); + $this->assertTrue($reflection->implementsInterface('ArrayAccess')); + } + + public function testImplementsCountable() + { + $reflection = new ReflectionClass('SugarArray'); + $this->assertTrue($reflection->implementsInterface('Countable')); + } + + public function testStaticMethodCanTraverseProvidedArray() + { + $random = rand(100, 200); + $array = array( + 'foo' => array( + $random => array( + 'bar' => $random, + ), + ), + ); + + $this->assertEquals(SugarArray::staticGet($array, "foo.{$random}.bar"), $random); + } + + public function testStaticMethodCanReturnDefaultOnUnknownValue() + { + $random = rand(100, 200); + $this->assertEquals(SugarArray::staticGet(array(123, 321), 'unknown', $random), $random); + } + + public function testAdd_blank_option() + { + $options = 'noneArray'; + $expectedArray = array(''=>''); + $result = add_blank_option($options); + $this->assertEquals($result[''], $expectedArray['']); + $options2 = array('mason'=>'unittest'); + $expectedArray2 = array(''=>'','mason'=>'unittest'); + $result2 = add_blank_option($options2); + $this->assertEquals($result2, $expectedArray2); + } +} + diff --git a/tests/include/utils/SugarFileUtilsTest.php b/tests/include/utils/SugarFileUtilsTest.php new file mode 100755 index 00000000..710e1965 --- /dev/null +++ b/tests/include/utils/SugarFileUtilsTest.php @@ -0,0 +1,160 @@ +markTestSkipped('Skipping on Windows'); + + $this->_filename = realpath(dirname(__FILE__).'/../../../cache/').'file_utils_override'.mt_rand().'.txt'; + touch($this->_filename); + $this->_old_default_permissions = $GLOBALS['sugar_config']['default_permissions']; + $GLOBALS['sugar_config']['default_permissions'] = + array ( + 'dir_mode' => 0777, + 'file_mode' => 0660, + 'user' => $this->_getCurrentUser(), + 'group' => $this->_getCurrentGroup(), + ); + } + + public function tearDown() + { + if(file_exists($this->_filename)) { + unlink($this->_filename); + } + $GLOBALS['sugar_config']['default_permissions'] = $this->_old_default_permissions; + SugarConfig::getInstance()->clearCache(); + } + + private function _getCurrentUser() + { + if ( function_exists('posix_getuid') ) { + return posix_getuid(); + } + return ''; + } + + private function _getCurrentGroup() + { + if ( function_exists('posix_getgid') ) { + return posix_getgid(); + } + return ''; + } + + private function _getTestFilePermissions() + { + return substr(sprintf('%o', fileperms($this->_filename)), -4); + } + + public function testSugarTouch() + { + $this->assertTrue(sugar_touch($this->_filename)); + } + + public function testSugarTouchWithTime() + { + $time = filemtime($this->_filename); + + $this->assertTrue(sugar_touch($this->_filename, $time)); + + $this->assertEquals($time,filemtime($this->_filename)); + } + + public function testSugarTouchWithAccessTime() + { + $time = filemtime($this->_filename); + $atime = gmmktime(); + + $this->assertTrue(sugar_touch($this->_filename, $time, $atime)); + + $this->assertEquals($time,filemtime($this->_filename)); + $this->assertEquals($atime,fileatime($this->_filename)); + } + + public function testSugarChmod() + { + return true; + $this->assertTrue(sugar_chmod($this->_filename)); + $this->assertEquals($this->_getTestFilePermissions(),decoct(get_mode())); + } + + public function testSugarChmodWithMode() + { + $mode = 0411; + $this->assertTrue(sugar_chmod($this->_filename, $mode)); + + $this->assertEquals($this->_getTestFilePermissions(),decoct($mode)); + } + + public function testSugarChmodNoDefaultMode() + { + $GLOBALS['sugar_config']['default_permissions']['file_mode'] = null; + $this->assertFalse(sugar_chmod($this->_filename)); + } + + public function testSugarChmodDefaultModeNotAnInteger() + { + $GLOBALS['sugar_config']['default_permissions']['file_mode'] = ''; + $this->assertFalse(sugar_chmod($this->_filename)); + } + + public function testSugarChmodDefaultModeIsZero() + { + $GLOBALS['sugar_config']['default_permissions']['file_mode'] = 0; + $this->assertFalse(sugar_chmod($this->_filename)); + } + + public function testSugarChmodWithModeNoDefaultMode() + { + $GLOBALS['sugar_config']['default_permissions']['file_mode'] = null; + $mode = 0411; + $this->assertTrue(sugar_chmod($this->_filename, $mode)); + + $this->assertEquals($this->_getTestFilePermissions(),decoct($mode)); + } + + public function testSugarChmodWithModeDefaultModeNotAnInteger() + { + $GLOBALS['sugar_config']['default_permissions']['file_mode'] = ''; + $mode = 0411; + $this->assertTrue(sugar_chmod($this->_filename, $mode)); + + $this->assertEquals($this->_getTestFilePermissions(),decoct($mode)); + } + + public function testSugarChown() + { + $this->assertTrue(sugar_chown($this->_filename)); + $this->assertEquals(fileowner($this->_filename),$this->_getCurrentUser()); + } + + public function testSugarChownWithUser() + { + $this->assertTrue(sugar_chown($this->_filename,$this->_getCurrentUser())); + $this->assertEquals(fileowner($this->_filename),$this->_getCurrentUser()); + } + + public function testSugarChownNoDefaultUser() + { + $GLOBALS['sugar_config']['default_permissions']['user'] = ''; + + $this->assertFalse(sugar_chown($this->_filename)); + } + + public function testSugarChownWithUserNoDefaultUser() + { + $GLOBALS['sugar_config']['default_permissions']['user'] = ''; + + $this->assertTrue(sugar_chown($this->_filename,$this->_getCurrentUser())); + + $this->assertEquals(fileowner($this->_filename),$this->_getCurrentUser()); + } +} +?> diff --git a/tests/include/utils/SugarVersionTest.php b/tests/include/utils/SugarVersionTest.php new file mode 100755 index 00000000..01e02256 --- /dev/null +++ b/tests/include/utils/SugarVersionTest.php @@ -0,0 +1,55 @@ +assertEquals($returnedStatus,$expectedResult, + "{$returnedStatus} status did not match expected status of {$expectedResult}"); + } + + public function providerVersionStatus() + { + return array( + array('5.5.0RC1','RC'), + array('5.5.0RC','RC'), + array('5.5.0','GA'), + array('5.5.0Beta','BETA'), + array('5.5.0BEta1','BETA'), + array('5.2','GA'), + array('5.2RC2','RC'), + ); + } + + /** + * @dataProvider providerVersionMajorMinor + */ + public function testVersionMajorMinor( + $version, + $expectedResult + ) + { + $returnedVersion = getMajorMinorVersion($version); + $this->assertEquals($returnedVersion,$expectedResult, + "{$returnedVersion} MajorMinor version did not match expected version of {$expectedResult}"); + } + + public function providerVersionMajorMinor() + { + return array( + array('5.5.0RC1','5.5'), + array('5.5.1RC','5.5.1'), + array('5.0','5.0'), + array('5.0Beta','5.0'), + array('5.5.1RC','5.5.1'), + ); + } +} diff --git a/tests/include/utils/XssTest.php b/tests/include/utils/XssTest.php new file mode 100755 index 00000000..b427bba0 --- /dev/null +++ b/tests/include/utils/XssTest.php @@ -0,0 +1,45 @@ +link", "test link"), + array("some data", "some data<>alert('xss!')"), + array("some data", "some data< src=\" http://localhost/xss.js\">"), + array("some data", "some data<>< src=\" http://localhost/xss.js\">"), + ); + } + + protected function clean($str) { + $potentials = clean_xss($str, false); + if(is_array($potentials) && !empty($potentials)) { + foreach($potentials as $bad) { + $str = str_replace($bad, "", $str); + } + } + return $str; + } + + /** + * @dataProvider xssData + */ + public function testXssFilter($before, $after) + { + $this->assertEquals($after, $this->clean($before)); + } + + /** + * @dataProvider xssData + */ + public function testXssFilterBean($before, $after) + { + $bean = new EmailTemplate(); + $bean->body_html = to_html($before); + $bean->cleanBean(); + $this->assertEquals(to_html($after), $bean->body_html); + } +} diff --git a/tests/include/vCard/ISO88591SampleFile.vcf b/tests/include/vCard/ISO88591SampleFile.vcf new file mode 100755 index 00000000..3d1e337d --- /dev/null +++ b/tests/include/vCard/ISO88591SampleFile.vcf @@ -0,0 +1,15 @@ +BEGIN:VCARD +VERSION:2.1 +N:Müster;Hans;;Herr +FN:Hans Müster +ORG:Muster GmbH;Testkontakt +TITLE:Geschäftsführer +TEL;WORK;VOICE:+41 61 127 50 50 +TEL;HOME;VOICE:+41 61 127 50 51 +TEL;CELL;VOICE:+41 61 127 50 53 +TEL;WORK;FAX:+41 61 127 50 52 +ADR;WORK:;;Ringstrasse 39;Therwil;;4106;Schweiz +LABEL;WORK;ENCODING=QUOTED-PRINTABLE:Ringstrasse 39=0D=0ATherwil 4106=0D=0ASchweiz +EMAIL;PREF;INTERNET:hans.muster@muster.com +REV:20070222T164709Z +END:VCARD diff --git a/tests/include/vCard/SimpleVCard.vcf b/tests/include/vCard/SimpleVCard.vcf new file mode 100755 index 00000000..096440f6 --- /dev/null +++ b/tests/include/vCard/SimpleVCard.vcf @@ -0,0 +1,13 @@ +BEGIN:VCARD +N:person;test; +FN: person lead +BDAY: +TEL;FAX: +TEL;HOME: +TEL;CELL: +TEL;WORK: +EMAIL;INTERNET: +ADR;WORK:;;;;;; +ORG:SDizzle Inc; +TITLE: +END:VCARD \ No newline at end of file diff --git a/tests/include/vCard/UTF8SampleFile.vcf b/tests/include/vCard/UTF8SampleFile.vcf new file mode 100755 index 00000000..9344f168 --- /dev/null +++ b/tests/include/vCard/UTF8SampleFile.vcf @@ -0,0 +1,15 @@ +BEGIN:VCARD +VERSION:2.1 +N:Müster;Hans;;Herr +FN:Hans Müster +ORG:Muster GmbH;Testkontakt +TITLE:Geschäftsführer +TEL;WORK;VOICE:+41 61 127 50 50 +TEL;HOME;VOICE:+41 61 127 50 51 +TEL;CELL;VOICE:+41 61 127 50 53 +TEL;WORK;FAX:+41 61 127 50 52 +ADR;WORK:;;Ringstrasse 39;Therwil;;4106;Schweiz +LABEL;WORK;ENCODING=QUOTED-PRINTABLE:Ringstrasse 39=0D=0ATherwil 4106=0D=0ASchweiz +EMAIL;PREF;INTERNET:hans.muster@muster.com +REV:20070222T164709Z +END:VCARD diff --git a/tests/include/vCard/vCardBug40629Test.php b/tests/include/vCard/vCardBug40629Test.php new file mode 100755 index 00000000..4e45338a --- /dev/null +++ b/tests/include/vCard/vCardBug40629Test.php @@ -0,0 +1,45 @@ +account = SugarTestAccountUtilities::createAccount(); + $this->account->name = "SDizzle Inc"; + $this->account->save(); + } + + public function tearDown() + { + unset($GLOBALS['current_user']); + SugarTestAccountUtilities::removeAllCreatedAccounts(); + } + + /** + * @group bug40629 + */ + public function testImportedVcardAccountLink() + { + $filename = dirname(__FILE__)."/SimpleVCard.vcf"; + + $vcard = new vCard(); + $contact_id = $vcard->importVCard($filename,'Contacts'); + $contact_record = new Contact(); + $contact_record->retrieve($contact_id); + + $this->assertFalse(empty($contact_record->account_id), "Contact should have an account record associated"); + $GLOBALS['db']->query("delete from contacts where id = '{$contact_id}'"); + + $vcard = new vCard(); + $lead_id = $vcard->importVCard($filename,'Leads'); + $lead_record = new Lead(); + $lead_record->retrieve($lead_id); + + $this->assertTrue(empty($lead_record->account_id), "Lead should not have an account record associated"); + $GLOBALS['db']->query("delete from leads where id = '{$lead_id}'"); + } +} \ No newline at end of file diff --git a/tests/include/vCard/vCardTest.php b/tests/include/vCard/vCardTest.php new file mode 100755 index 00000000..c9968055 --- /dev/null +++ b/tests/include/vCard/vCardTest.php @@ -0,0 +1,77 @@ +importVCard($filename,$module); + + $bean = new vCardMockModule; + $bean = $bean->retrieve($record); + + $this->assertEquals('Hans Müster',$bean->first_name.' '.$bean->last_name); + } + + public function testImportedVcardWithSameCharsetIsNotTranslated() + { + $filename = dirname(__FILE__)."/UTF8SampleFile.vcf"; + $module = "vCardMockModule"; + + $vcard = new vCard(); + $record = $vcard->importVCard($filename,$module); + + $bean = new vCardMockModule; + $bean = $bean->retrieve($record); + + $this->assertEquals('Hans Müster',$bean->first_name.' '.$bean->last_name); + } +} + +class vCardMockModule extends Person +{ + private static $_savedObjects = array(); + + public function save() + { + $this->id = create_guid(); + + self::$_savedObjects[$this->id] = $this; + + return $this->id; + } + + public function retrieve($id = -1, $encode=true,$deleted=true) + { + if ( isset(self::$_savedObjects[$id]) ) + return self::$_savedObjects[$id]; + + return null; + } +} \ No newline at end of file diff --git a/tests/include/workflow/testfiles/logic_hooks.php b/tests/include/workflow/testfiles/logic_hooks.php new file mode 100755 index 00000000..eb540431 --- /dev/null +++ b/tests/include/workflow/testfiles/logic_hooks.php @@ -0,0 +1,12 @@ + \ No newline at end of file diff --git a/tests/include/workflow/testfiles/workflow/actions_array.php b/tests/include/workflow/testfiles/workflow/actions_array.php new file mode 100755 index 00000000..48f85d5f --- /dev/null +++ b/tests/include/workflow/testfiles/workflow/actions_array.php @@ -0,0 +1,55 @@ + + +array ( + + 'action_type' => 'update', + 'action_module' => '', + 'rel_module' => '', + 'rel_module_type' => 'all', + 'basic' => array ( + + 'description' => 'Hey Man!', + ), + + 'basic_ext' => array ( + + ), + + 'advanced' => array ( + + ), + +), + +'Accounts1_action0' => + +array ( + + 'action_type' => 'update', + 'action_module' => '', + 'rel_module' => '', + 'rel_module_type' => 'all', + 'basic' => array ( + + 'team_id' => '1', + ), + + 'basic_ext' => array ( + + ), + + 'advanced' => array ( + + ), + +), + +); + + + +?> \ No newline at end of file diff --git a/tests/include/workflow/testfiles/workflow/alerts_array.php b/tests/include/workflow/testfiles/workflow/alerts_array.php new file mode 100755 index 00000000..9778b98a --- /dev/null +++ b/tests/include/workflow/testfiles/workflow/alerts_array.php @@ -0,0 +1,9 @@ + \ No newline at end of file diff --git a/tests/include/workflow/testfiles/workflow/plugins_array.php b/tests/include/workflow/testfiles/workflow/plugins_array.php new file mode 100755 index 00000000..a8dcff39 --- /dev/null +++ b/tests/include/workflow/testfiles/workflow/plugins_array.php @@ -0,0 +1,9 @@ + \ No newline at end of file diff --git a/tests/include/workflow/testfiles/workflow/triggers_array.php b/tests/include/workflow/testfiles/workflow/triggers_array.php new file mode 100755 index 00000000..dba01b72 --- /dev/null +++ b/tests/include/workflow/testfiles/workflow/triggers_array.php @@ -0,0 +1,9 @@ + \ No newline at end of file diff --git a/tests/include/workflow/testfiles/workflow/workflow.php b/tests/include/workflow/testfiles/workflow/workflow.php new file mode 100755 index 00000000..0b1391c1 --- /dev/null +++ b/tests/include/workflow/testfiles/workflow/workflow.php @@ -0,0 +1,74 @@ +fetched_row['name'] == 'Sugar' )) && + (isset($focus->name) && $focus->name == 'Sugar')){ + + + //Frame Secondary + + $secondary_array = array(); + //Secondary Triggers + + global $triggeredWorkflows; + if (!isset($triggeredWorkflows['eaa0bd50_7aff_3ed6_f43c_4c7354ab1221'])){ + $triggeredWorkflows['eaa0bd50_7aff_3ed6_f43c_4c7354ab1221'] = true; + unset($alertshell_array); + process_workflow_actions($focus, $action_meta_array['Accounts1_action0']); + } + + + //End Frame Secondary + + unset($secondary_array); + + + //End if trigger is true + } + + + //end function process_wflow_triggers + } + + //end class + } + +?> \ No newline at end of file diff --git a/tests/install/QuotesSeedDataTest.php b/tests/install/QuotesSeedDataTest.php new file mode 100755 index 00000000..ae491d94 --- /dev/null +++ b/tests/install/QuotesSeedDataTest.php @@ -0,0 +1,97 @@ +limitQuery($query,0,10,true,"Error retrieving Accounts"); + while($row = $GLOBALS['db']->fetchByAssoc($results)) { + $sugar_demodata['company_name_array'][] = $row['name']; + } + + $this->quote_name = 'Test Quote ' . mktime(); + + $sugar_demodata['quotes_seed_data']['quotes'][0] = array( + 'name' => $this->quote_name, + 'quote_stage' => 'Draft', + 'date_quote_expected_closed' => '04/30/2012', + 'description' => 'This is a test that should contain one product group with two products and a total of three items', + + + 'bundle_data' => array( + 0 => array ( + 'bundle_name' => 'Group 1', + 'bundle_stage' => 'Draft', + 'comment' => 'Three Computers', + 'products' => array ( + 1 => array('name'=>'TK 1000 Desktop', 'quantity'=>'1'), + 2 => array('name'=>'TK m30 Desktop', 'quantity'=>'2'), + ), + ), + ), + ); + } + + public function tearDown() { + $sql = "SELECT * FROM quotes WHERE name = '{$this->quote_name}'"; + $results = $GLOBALS['db']->query($sql); + $quote_id = ''; + + while($row = $GLOBALS['db']->fetchByAssoc($results)) { + $quote_id = $row['id']; + } + + $sql = "DELETE FROM quotes WHERE id = '{$quote_id}'"; + $GLOBALS['db']->query($sql); + + $sql = "DELETE FROM products WHERE quote_id = '{$quote_id}'"; + $GLOBALS['db']->query($sql); + + $bundle_id = ''; + $sql = "SELECT bundle_id FROM product_bundle_quote WHERE quote_id = '{$quote_id}"; + + $results = $GLOBALS['db']->query($sql); + while($row = $GLOBALS['db']->fetchByAssoc($results)) { + $bundle_id = $row['bundle_id']; + + $sql = "DELETE FROM product_bundle_product WHERE bundle_id = '{$bundle_id}'"; + $GLOBALS['db']->query($sql); + + $sql = "DELETE FROM product_bundle_quote WHERE bundle_id = '{$bundle_id}'"; + $GLOBALS['db']->query($sql); + } + + if(!empty($bundle_id)) { + $sql = "SELECT note_id FROM product_bundle_note WHERE bundle_id = '{$bundle_id}"; + $results = $GLOBALS['db']->query($sql); + while($row = $GLOBALS['db']->fetchByAssoc($results)) { + $note_id = $row['note_id']; + + $sql = "DELETE FROM product_bundle_notes WHERE id = '{$note_id}'"; + $GLOBALS['db']->query($sql); + } + + $sql = "DELETE FROM product_bundle_note WHERE bundle_id = '{$bundle_id}'"; + $GLOBALS['db']->query($sql); + } + + } + + public function test_create_seed_quotes() { + require_once('install/seed_data/quotes_SeedData.php'); + $sql = "SELECT * FROM quotes WHERE name = '{$this->quote_name}'"; + $results = $GLOBALS['db']->query($sql); + $quote_created = false; + while($row = $GLOBALS['db']->fetchByAssoc($results)) { + $quote_created = true; + } + + $this->assertTrue($quote_created); + } +} +?> \ No newline at end of file diff --git a/tests/modules/Administration/Bug36978Test.php b/tests/modules/Administration/Bug36978Test.php new file mode 100755 index 00000000..7b45ef9e --- /dev/null +++ b/tests/modules/Administration/Bug36978Test.php @@ -0,0 +1,264 @@ +markTestSkipped("Skipping unless otherwise specified"); + return; + } + + $admin = new User(); + $GLOBALS['current_user'] = $admin->retrieve('1'); + + $GLOBALS['app_list_strings'] = return_app_list_strings_language('en_us'); + + //Create the custom relationships + if(!file_exists('custom/Extension/modules/abc_Test/Ext/Vardefs')) { + mkdir_recursive('custom/Extension/modules/abc_Test/Ext/Vardefs'); + } + + if(!file_exists('custom/Extension/modules/abc_Test/Ext/Layoutdefs')) { + mkdir_recursive('custom/Extension/modules/abc_Test/Ext/Layoutdefs'); + } + + if(!file_exists('modules/abc_Test/metadata')) { + mkdir_recursive('modules/abc_Test/metadata'); + } + + if( $fh = @fopen('modules/abc_Test/metadata/studio.php', 'w+') ) + { +$string = << 'abc_test_abc_test', + 'type' => 'link', + 'relationship' => 'abc_test_abc_test', + 'source' => 'non-db', + 'side' => 'right', + 'vname' => 'LBL_ABC_TEST_ABC_TEST_FROM_ABC_TEST_L_TITLE', +); +?> + 'abc_test_abc_test_name', + 'type' => 'relate', + 'source' => 'non-db', + 'vname' => 'LBL_ABC_TEST_ABC_TEST_FROM_ABC_TEST_L_TITLE', + 'save' => true, + 'id_name' => 'abc_test_ab6dabc_test_ida', + 'link' => 'abc_test_abc_test', + 'table' => 'abc_test', + 'module' => 'abc_Test', + 'rname' => 'name', +); +?> + 'abc_test_ab6dabc_test_ida', + 'type' => 'link', + 'relationship' => 'abc_test_abc_test', + 'source' => 'non-db', + 'reportable' => false, + 'side' => 'right', + 'vname' => 'LBL_ABC_TEST_ABC_TEST_FROM_ABC_TEST_R_TITLE', +); +?> + +EOQ; + fputs( $fh, $string); + fclose( $fh ); + } + + //Create the custom relationships + if(!file_exists('custom/metadata')) { + mkdir_recursive('custom/metadata'); + } + + if( $fh = @fopen('custom/metadata/abc_test_abc_testMetaData.php', 'w+') ) + { +$string = << 'one-to-many', + 'relationships' => + array ( + 'abc_test_abc_test' => + array ( + 'lhs_module' => 'abc_Test', + 'lhs_table' => 'abc_test', + 'lhs_key' => 'id', + 'rhs_module' => 'abc_Test', + 'rhs_table' => 'abc_test', + 'rhs_key' => 'id', + 'relationship_type' => 'one-to-many', + 'join_table' => 'abc_test_abc_test_c', + 'join_key_lhs' => 'abc_test_ab6dabc_test_ida', + 'join_key_rhs' => 'abc_test_aed49bc_test_idb', + ), + ), + 'table' => 'abc_test_abc_test_c', + 'fields' => + array ( + 0 => + array ( + 'name' => 'id', + 'type' => 'varchar', + 'len' => 36, + ), + 1 => + array ( + 'name' => 'date_modified', + 'type' => 'datetime', + ), + 2 => + array ( + 'name' => 'deleted', + 'type' => 'bool', + 'len' => '1', + 'default' => '0', + 'required' => true, + ), + 3 => + array ( + 'name' => 'abc_test_ab6dabc_test_ida', + 'type' => 'varchar', + 'len' => 36, + ), + 4 => + array ( + 'name' => 'abc_test_aed49bc_test_idb', + 'type' => 'varchar', + 'len' => 36, + ), + ), + 'indices' => + array ( + 0 => + array ( + 'name' => 'abc_test_abc_testspk', + 'type' => 'primary', + 'fields' => + array ( + 0 => 'id', + ), + ), + 1 => + array ( + 'name' => 'abc_test_abc_test_ida1', + 'type' => 'index', + 'fields' => + array ( + 0 => 'abc_test_ab6dabc_test_ida', + ), + ), + 2 => + array ( + 'name' => 'abc_test_abc_test_alt', + 'type' => 'alternate_key', + 'fields' => + array ( + 0 => 'abc_test_aed49bc_test_idb', + ), + ), + ), +); +?> + + +EOQ; + fputs( $fh, $string); + fclose( $fh ); + } + + +if(!file_exists('custom/Extension/application/Ext/TableDictionary')) { + mkdir_recursive('custom/Extension/application/Ext/TableDictionary'); +} + + +if( $fh = @fopen('custom/Extension/application/Ext/TableDictionary/abc_test_abc_test.php', 'w+') ) +{ +$string = << +EOQ; + fputs( $fh, $string); + fclose( $fh ); +} + + $this->rel_guid = create_guid(); + $sql = "INSERT INTO relationships (id, relationship_name, lhs_module, lhs_table, lhs_key, rhs_module, rhs_table, rhs_key, join_table, join_key_lhs, join_key_rhs, relationship_type, reverse, deleted) VALUES ('{$this->rel_guid}', 'abc_test_abc_test', 'abc_Test', 'abc_test', 'id', 'abc_Test', 'abc_test', 'id', 'abc_test_abc_test_c', 'abc_test_ab6abc_test_id', 'abc_test_aed49bc_test_id', 'one-to-many', 0, 0)"; + $GLOBALS['db']->query($sql); + + $rel = new Relationship(); + $rel->delete_cache(); + $rel->build_relationship_cache(); + + $this->moduleList = $GLOBALS['moduleList']; +} + +function tearDown() { + if(file_exists('custom/Extension/modules/abc_Test/Ext/Vardefs/test.php')) { + unlink('custom/Extension/modules/abc_Test/Ext/Vardefs/test.php'); + } + + if(file_exists('custom/metadata/abc_test_abc_testMetaData.php')) { + unlink('custom/metadata/abc_test_abc_testMetaData.php'); + } + + if(file_exists('custom/Extension/application/Ext/TableDictionary/abc_test_abc_test.php')) { + unlink('custom/Extension/application/Ext/TableDictionary/abc_test_abc_test.php'); + } + + if(file_exists('modules/abc_Test/metadata/studio.php')) { + unlink('modules/abc_Test/metadata/studio.php'); + } + + rmdir_recursive('custom/Extension/modules/abc_Test/Ext/Vardefs'); + rmdir_recursive('custom/Extension/modules/abc_Test/Ext/Layoutdefs'); + rmdir_recursive('custom/Extension/modules/abc_Test/Ext'); + rmdir_recursive('custom/Extension/modules/abc_Test'); + rmdir_recursive('modules/abc_Test/metadata'); + rmdir_recursive('modules/abc_Test'); + + $sql = "DELETE FROM relationships WHERE id = '{$this->rel_guid}'"; + $GLOBALS['db']->query($sql); + + $GLOBALS['moduleList'] = $this->moduleList; +} + + +function test_upgrade_custom_relationships() { + $GLOBALS['moduleList'] = array(); + $GLOBALS['moduleList'][] = 'abc_Test'; + $GLOBALS['beanList']['abc_Test'] = 'abc_Test'; + /* + include('modules/Administration/upgrade_custom_relationships.php'); + upgrade_custom_relationships(); + include('custom/Extension/modules/abc_Test/Ext/Vardefs/test.php'); + */ +} + + +} +?> \ No newline at end of file diff --git a/tests/modules/Administration/UpgradeHistoryTest.php b/tests/modules/Administration/UpgradeHistoryTest.php new file mode 100755 index 00000000..8d3378b2 --- /dev/null +++ b/tests/modules/Administration/UpgradeHistoryTest.php @@ -0,0 +1,26 @@ +name = 'abc'; + $patchToCheck->id = ''; + $GLOBALS['db']->query("INSERT INTO upgrade_history (id, name, date_entered) VALUES +('444', 'abc','2008-12-20 08:08:20') "); + $GLOBALS['db']->query("INSERT INTO upgrade_history (id, name , date_entered) VALUES +('555','abc', '2008-12-20 08:08:20')"); + $uh = new UpgradeHistory(); + $return = $uh->checkForExisting($patchToCheck); + $this->assertContains($return->id, array('444','555')); + + $patchToCheck->id = '555'; + $return = $uh->checkForExisting($patchToCheck); + $this->assertEquals($return->id, '444'); + + $GLOBALS['db']->query("delete from upgrade_history where id='444'"); + $GLOBALS['db']->query("delete from upgrade_history where id='555'"); + } +} \ No newline at end of file diff --git a/tests/modules/Calendar/Bug20626Test.php b/tests/modules/Calendar/Bug20626Test.php new file mode 100755 index 00000000..90b21c60 --- /dev/null +++ b/tests/modules/Calendar/Bug20626Test.php @@ -0,0 +1,42 @@ +getUserDateTimePreferences(); + $meeting->date_start = $timedate->swap_formats("2006-12-23 11:00pm" , 'Y-m-d h:ia', $format['date'].' '.$format['time']); + $meeting->time_start = ""; + $meeting->object_name = "Meeting"; + $meeting->duration_hours = 2; + $ca = new CalendarActivity($meeting); + $this->assertEquals($meeting->date_start , $ca->sugar_bean->date_start); + } +} \ No newline at end of file diff --git a/tests/modules/Calls/Bug39161Test.php b/tests/modules/Calls/Bug39161Test.php new file mode 100755 index 00000000..5623f0d5 --- /dev/null +++ b/tests/modules/Calls/Bug39161Test.php @@ -0,0 +1,17 @@ +field_defs['contact_name']; + $this->assertTrue(ListLayoutMetaDataParser::isValidField($def['name'], $def)); + $this->assertFalse(GridLayoutMetaDataParser::validField($def, 'editview')); + $this->assertFalse(GridLayoutMetaDataParser::validField($def, 'detailview')); + $this->assertFalse(GridLayoutMetaDataParser::validField($def, 'quickcreate')); + } + +} \ No newline at end of file diff --git a/tests/modules/Calls/CallHelperTest.php b/tests/modules/Calls/CallHelperTest.php new file mode 100755 index 00000000..c70e77ab --- /dev/null +++ b/tests/modules/Calls/CallHelperTest.php @@ -0,0 +1,236 @@ + + + + + +EOHTML + ), + array('MassUpdate',<< + + + + +EOHTML + ), + array('QuickCreate',<< + + + + +EOHTML + ), + array('DetailView','15'), + ); + } + + /** + * @dataProvider providerGetDurationMinutesOptions + */ + public function testGetDurationMinutesOptions( + $view, + $returnValue + ) + { + $focus = new Call(); + + $this->assertEquals( + getDurationMinutesOptions($focus,'','',$view), + $returnValue + ); + } + + public function testGetDurationMinutesOptionsNonDefaultValue() + { + $focus = new Call(); + $focus->duration_minutes = '30'; + + $this->assertEquals( + getDurationMinutesOptions($focus,'','','DetailView'), + $focus->duration_minutes + ); + } + + public function testGetDurationMinutesOptionsFromRequest() + { + $focus = new Call(); + $_REQUEST['duration_minutes'] = '45'; + + $this->assertEquals( + getDurationMinutesOptions($focus,'','','DetailView'), + $_REQUEST['duration_minutes'] + ); + + unset($_REQUEST['duration_minutes']); + } + + public function testGetDurationMinutesOptionsOtherValues() + { + $focus = new Call(); + $focus->date_start = null; + $focus->duration_hours = null; + $focus->minutes_value_default = null; + + getDurationMinutesOptions($focus,'','','DetailView'); + + $this->assertEquals($focus->date_start,$GLOBALS['timedate']->to_display_date(gmdate($GLOBALS['timedate']->get_date_time_format()))); + $this->assertEquals($focus->duration_hours,'0'); + $this->assertEquals($focus->duration_minutes,'1'); + } + + public function providerGetReminderTime() + { + return array( + array('EditView',<< + + + + + + +EOHTML + ), + array('MassUpdate',<< + + + + + + +EOHTML + ), + array('SubpanelCreates',<< + + + + + + +EOHTML + ), + array('QuickCreate',<< + + + + + + +EOHTML + ), + array('DetailView',''), + ); + } + + /** + * @dataProvider providerGetReminderTime + */ + public function testGetReminderTime( + $view, + $returnValue + ) + { + $focus = new Call(); + + $this->assertEquals( + getReminderTime($focus,'','',$view), + $returnValue + ); + } + + public function testGetReminderTimeNonDefaultValue() + { + $focus = new Call(); + $focus->reminder_time = '600'; + + $this->assertEquals( + getReminderTime($focus,'','','EditView'), + << + + + + + + +EOHTML + ); + } + + public function testGetReminderTimeNonDefaultValueDetailView() + { + $focus = new Call(); + $focus->reminder_time = '300'; + + $this->assertEquals( + getReminderTime($focus,'','','DetailView'), + '5 minutes prior' + ); + } + + public function testGetReminderTimeFromRequest() + { + $focus = new Call(); + $_REQUEST['reminder_time'] = '900'; + $_REQUEST['full_form'] = true; + + $this->assertEquals( + getReminderTime($focus,'','','EditView'), + << + + + + + + +EOHTML + ); + + unset($_REQUEST['reminder_time']); + unset($_REQUEST['full_form']); + } + + public function testGetReminderTimeFromValue() + { + $focus = new Call(); + unset($focus->reminder_time); + + $this->assertEquals( + getReminderTime($focus,'','1800','EditView'), + << + + + + + + +EOHTML + ); + } +} diff --git a/tests/modules/CampaignLog/CampaignLogTest.php b/tests/modules/CampaignLog/CampaignLogTest.php new file mode 100755 index 00000000..de1fbcb7 --- /dev/null +++ b/tests/modules/CampaignLog/CampaignLogTest.php @@ -0,0 +1,194 @@ +tracker_name ='Campaign Log Unit Test Tracker'; + $ct->tracker_url = 'sugarcrm.com'; + $ct->campaign_id = $this->campaign_id; + $ct->save(); + $this->campaign_tracker = $ct; + + + //for each type, create an object and populate the campaignLog list + foreach($this->targetObjectArray as $type){ + //skip campaign tracker + if($type == 'CampaignTracker'){ + continue; + } + + //create the new bean + $bean = new $type(); + if ($type == 'Account'){ + $bean->name = 'CampLog Unit Test Account'; + }else{ + $bean->first_name = 'CampaignLog'; + $bean->last_name = 'Test '.$type; + } + $type_obj = 'target_'.$type; + $bean->save(); + $this->$type_obj = $bean; + + //save email + $sea = new SugarEmailAddress(); + $id = $this->$type_obj->id; + $module = $this->$type_obj->module_dir; + $new_addrs=array();$primary='';$replyTo='';$invalid='';$optOut='';$in_workflow=false; + $_REQUEST[$module.'_email_widget_id'] = 0; + $_REQUEST[$module.'0emailAddress0'] = $type.'UnitTest@example.com'; + $_REQUEST[$module.'emailAddressPrimaryFlag'] = '0emailAddress0'; + $_REQUEST[$module.'emailAddressVerifiedFlag0'] = 'true'; + $_REQUEST[$module.'emailAddressVerifiedValue0'] = 'unitTest@sugarcrm.com'; + $requestVariablesSet = array('0emailAddress0','emailAddressPrimaryFlag','emailAddressVerifiedFlag0','emailAddressVerifiedValue0'); + $sea->save($id, $module, $new_addrs, $primary, $replyTo, $invalid, $optOut, $in_workflow); + //unset email request values for next run + foreach ($requestVariablesSet as $k) + unset($_REQUEST[$k]); + + + //now create the campaign log + $cl = new CampaignLog(); + $cl->campaign_id = $this->campaign_id; + $cl->tracker_key = $ct->tracker_key; + $cl->target_id = $bean->id; + $cl->target_type = $bean->module_dir; + $cl->activity_type = 'targeted';//options are targeted (user was sent an email), link (user clicked on link), removed (user opted out) and viewed (viewed) + $cl->activity_date = date('Y-m-d H:i:s'); + $cl->related_id = 'somebogusemailid'.date('His'); // this means link will not really work, but we are not testing email + $cl->related_type = 'Emails'; + $cl->list_id = $this->prospect_list_id; + $cl->marketing_id = $this->email_marketing_id; + $cl->save(); + } + //keep last created campaign log bean to be used to call functions + $this->campaign_log = $cl; + + + } + + public function tearDown() + { + global $current_user; + //for each type, delete the object and it's email + foreach($this->targetObjectArray as $type){ + //skip campaign tracker + if($type == 'CampaignTracker'){ + continue; + } + //create string to reference bean by + $type_obj = 'target_'.$type; + + //remove the email address and relationship + $query = 'delete from email_addresses where email_address = \''.$type.'UnitTest@example.com\';'; + $GLOBALS['db']->query($query); + $query = 'delete from email_addr_bean_rel where bean_id = \''.$this->$type_obj->id.'\';'; + $GLOBALS['db']->query($query); + + //remove the bean and delete record + $this->$type_obj->deleted = 1; + $this->$type_obj->save(); + $GLOBALS['db']->query('DELETE FROM '.$this->$type_obj->table_name.' WHERE id = \''.$this->$type_obj->id.'\' '); + unset($this->$type_obj); + + } + + //delete the campaign logs and campaign tracker + $GLOBALS['db']->query('DELETE FROM campaign_log WHERE campaign_id = \''.$this->campaign_id.'\' '); + $GLOBALS['db']->query('DELETE FROM campaign_tracker WHERE id = \''.$this->campaign_tracker->id.'\' '); + unset($this->campaign_tracker); + unset($this->campaign_log );SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + } + + + + public function testGetListViewData(){ + global $current_user; + $lvd = $this->campaign_log->get_list_view_data(); + + //make sure the returned value is an array + $this->assertTrue(is_array($lvd), 'CampaignLog->get_list_view_data should return an object of array type'); + + //make sure some of the expected values exist + $this->assertFalse(empty($lvd['CAMPAIGN_ID']), 'array element CAMPAIGN_ID is expected to exist when calling CampaignLog->get_list_view_data '); + $this->assertFalse(empty($lvd['TARGET_ID']), 'array element TARGET_ID is expected to exist when calling CampaignLog->get_list_view_data '); + } + + public function testGetRelatedName(){ + global $current_user,$locale; + + foreach($this->targetObjectArray as $type){ + //skip campaign tracker + if($type == 'CampaignTracker'){ + continue; + } + //create string to reference bean by + $type_obj = 'target_'.$type; + + //make sure the related name is coming in from the correct related type + $related_name = $this->campaign_log->get_related_name($this->$type_obj->id,$this->$type_obj->module_dir); + + //make sure the returned name is formatted as expected + if ($type == 'Account'){ + $this->assertSame($related_name, $this->$type_obj->name, 'name retrieved from campaign log does not match the expected name of '.$formatted_name.' for the related '.$type.' object'); + }elseif ($type == 'User'){ + $formatted_name = $this->$type_obj->id.$this->$type_obj->module_dir; + $this->assertSame($related_name, $formatted_name, 'name retrieved from campaign log does not match the expected formatted name of '.$formatted_name.' for the related '.$type.' object'); + }else{ + $bean->first_name = 'CampaignLog'; + $bean->last_name = 'Test '.$type; + $formatted_name = $locale->getLocaleFormattedName($this->$type_obj->first_name, $this->$type_obj->last_name); + $this->assertSame($related_name, $formatted_name, 'name retrieved from campaign log does not match the expected formatted name of '.$formatted_name.' for the related '.$type.' object'); + } + + } + + } + + public function testRetrieveEmailAddress(){ + global $current_user; + foreach($this->targetObjectArray as $type){ + //skip campaign tracker + if($type == 'CampaignTracker'){ + continue; + } + //create string to reference bean by + $type_obj = 'target_'.$type; + + $eastring = $this->campaign_log->retrieve_email_address($this->$type_obj->id); + $this->assertSame($eastring, $type.'UnitTest@example.com', 'email retrieved from campaign log object type '.$type.'does not match the expected email of '.$type.'UnitTest@example.com'); + } + + } + + +} \ No newline at end of file diff --git a/tests/modules/CampaignTrackers/CampaignTrackersTest.php b/tests/modules/CampaignTrackers/CampaignTrackersTest.php new file mode 100755 index 00000000..1e7234d9 --- /dev/null +++ b/tests/modules/CampaignTrackers/CampaignTrackersTest.php @@ -0,0 +1,83 @@ +name = 'CT test ' . time(); + $c->campaign_type = 'Email'; + $c->status = 'Active'; + $timeDate = new TimeDate(); + $c->end_date = $timeDate->to_display_date(date('Y')+1 .'-01-01'); + $c->assigned_id = $current_user->id; + $c->team_id = '1'; + $c->team_set_id = '1'; + $c->save(); + $this->campaign = $c; + + //create campaign tracker + $ct = new CampaignTracker(); + $ct->tracker_name ='Campaign Tracker Test ' . time(); + $ct->tracker_url = 'sugarcrm.com'; + $ct->campaign_id = $this->campaign->id; + $ct->save(); + $this->campaign_tracker = $ct; + + + + + } + + public function tearDown() + { + //delete the campaign and campaign tracker + $GLOBALS['db']->query('DELETE FROM campaign_log WHERE campaign_id = \''.$this->campaign->id.'\' '); + $GLOBALS['db']->query('DELETE FROM campaign_tracker WHERE id = \''.$this->campaign_tracker->id.'\' '); + unset($this->campaign_tracker); + unset($this->campaign_log ); + unset($GLOBALS['current_user']); + } + + + public function testSave(){ + //save was already performed, so just confirm that the http protocol got added on save + $this->assertSame('http://sugarcrm.com', $this->campaign_tracker->tracker_url, 'http protocol was not added to campaign_tracker->tracker_url on save'); + + } + + + + public function testFillInAdditionalDetailFields(){ + global $current_user; + + $this->campaign_tracker->fill_in_additional_detail_fields(); + + //test that campaign name gets filled in + $this->assertSame($this->campaign->name, $this->campaign_tracker->campaign_name, 'campaign name was not set properly during function call'); + + //test that message url gets filed out + $this->assertFalse(empty($this->campaign_tracker->message_url), 'message url was not populated correctly during function call'); + } + + public function testGetSummaryText(){ + //test that tracker name is returned + $this->assertSame($this->campaign_tracker->tracker_name, $this->campaign_tracker->get_summary_text(), 'campaign tracker name is not set properly in summary text'); + + } + + + + +} \ No newline at end of file diff --git a/tests/modules/Campaigns/Bug35014Test.php b/tests/modules/Campaigns/Bug35014Test.php new file mode 100755 index 00000000..725f4739 --- /dev/null +++ b/tests/modules/Campaigns/Bug35014Test.php @@ -0,0 +1,162 @@ +markTestSkipped('SugarTestCampaignUtilities does not exist'); + $GLOBALS['current_user'] = SugarTestUserUtilities::createAnonymousUser(); + $campaign = SugarTestCampaignUtilities::createCampaign(); + $this->campaign_id = $campaign->id; + } + + public function tearDown() + { + SugarTestCampaignUtilities::removeAllCreatedCampaigns(); + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + } + + public function testLeadCaptureResponse() + { + // SET GLOBAL PHP VARIABLES + $_POST = array + ( + 'first_name' => 'Sadek', + 'last_name' => 'Baroudi', + 'campaign_id' => $this->campaign_id, + 'redirect_url' => 'http://www.sugarcrm.com/index.php', + 'assigned_user_id' => 1, + 'team_id' => '1', + 'team_set_id' => 'Global', + 'req_id' => 'last_name;', + ); + + // RUN TEST 1 + $postString = ''; + foreach($_POST as $k => $v) + { + $postString .= "{$k}=".urlencode($v)."&"; + } + $postString = rtrim($postString, "&"); + + $ch = curl_init("{$GLOBALS['sugar_config']['site_url']}/index.php?entryPoint=WebToLeadCapture"); + curl_setopt($ch, CURLOPT_POST, count($_POST) + 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, $postString); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0); + curl_setopt($ch, CURLOPT_HEADER, 1); + ob_start(); + $return = curl_exec($ch); + $output = ob_get_clean(); + + $matches = array(); + preg_match("/Location: .*/", $output, $matches); + $this->assertTrue(count($matches) > 0, "Could not get the header information for the response"); + + $location = ''; + if(count($matches) > 0){ + $location = str_replace("Location :", "", $matches[0]); + } + + $query_string = substr($location, strpos($location, "?") + 1); + $query_string_array = explode("&", $query_string); + + $post_compare_array = array(); + $skipKeys = array('module', 'action', 'entryPoint', 'client_id_address'); + foreach($query_string_array as $key_val) + { + $key_val_array = explode("=", $key_val); + if(in_array($key_val_array[0], $skipKeys)) + continue; + $post_compare_array[$key_val_array[0]] = $key_val_array[1]; + } + + // the redirect_url doesn't get returned, so we unset it + unset($_POST['redirect_url']); + + $this->assertEquals($_POST, $post_compare_array, "The returned get location doesn't match that of the post passed in"); + + + // SET GLOBAL PHP VARIABLES + $_POST = array + ( + 'first_name' => 'Sadek', + 'last_name' => 'Baroudi', + 'campaign_id' => $this->campaign_id, + 'redirect_url' => 'http://www.sugarcrm.com/index.php', + 'assigned_user_id' => 1, + 'team_id' => '1', + 'team_set_id' => 'Global', + 'req_id' => 'last_name;', + 'SuperLongGetVar' => + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis'. + 'PneumonoultramicroscopicsilicovolcanoconiosisPneumonoultramicroscopicsilicovolcanoconiosis', + ); + + + // RUN TEST 1 + $postString = ''; + foreach($_POST as $k => $v) + { + $postString .= "{$k}=".urlencode($v)."&"; + } + $postString = rtrim($postString, "&"); + + $ch = curl_init("{$GLOBALS['sugar_config']['site_url']}/index.php?entryPoint=WebToLeadCapture"); + curl_setopt($ch, CURLOPT_POST, count($_POST) + 1); + curl_setopt($ch, CURLOPT_POSTFIELDS, $postString); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0); + curl_setopt($ch, CURLOPT_HEADER, 1); + ob_start(); + $return = curl_exec($ch); + $output = ob_get_clean(); + + $matches = array(); + preg_match('/form name="redirect"/', $output, $matches); + $this->assertTrue(count($matches) > 0, "Should have output a form since we have a long get string"); + } +} +?> \ No newline at end of file diff --git a/tests/modules/Campaigns/Bug40233Test.php b/tests/modules/Campaigns/Bug40233Test.php new file mode 100755 index 00000000..7ef60dd2 --- /dev/null +++ b/tests/modules/Campaigns/Bug40233Test.php @@ -0,0 +1,269 @@ +markTestSkipped('Marking this skipped until we figure out why it is causing the SQL server connection to go away.'); + $this->clear_database = true; + $this->remove_beans = true; + $this->saved_current_user = $GLOBALS['current_user']; + $user = new User(); + $user->retrieve('1'); + $GLOBALS['current_user'] = $user; + + $this->campaign = new Campaign(); + $this->campaign->name = 'Bug39665Test ' . time(); + $this->campaign->campaign_type = 'Email'; + $this->campaign->status = 'Active'; + $timeDate = new TimeDate(); + $this->campaign->end_date = $timeDate->to_display_date(date('Y')+1 .'-01-01'); + $this->campaign->assigned_id = $user->id; + $this->campaign->team_id = '1'; + $this->campaign->team_set_id = '1'; + $this->campaign->save(); + + $this->emailmarketing = new EmailMarketing(); + $this->emailmarketing->name = $this->campaign->name . ' Email1'; + $this->emailmarketing->campaign_id = $this->campaign->id; + $this->emailmarketing->from_name = 'SugarCRM'; + $this->emailmarketing->from_addr = 'from@exmaple.com'; + $this->emailmarketing->reply_to_name = 'SugarCRM'; + $this->emailmarketing->reply_to_addr = 'reply@exmaple.com'; + $this->emailmarketing->status = 'active'; + $this->emailmarketing->all_prospect_lists = 1; + $this->emailmarketing->date_start = $timeDate->to_display_date(date('Y')+1 .'-01-01') . ' 00:00:00'; + + $this->emailmarketing2 = new EmailMarketing(); + $this->emailmarketing2->name = $this->campaign->name . ' Email2'; + $this->emailmarketing2->campaign_id = $this->campaign->id; + $this->emailmarketing2->from_name = 'SugarCRM'; + $this->emailmarketing2->from_addr = 'do_not_reply@exmaple.com'; + $this->emailmarketing2->reply_to_name = 'SugarCRM'; + $this->emailmarketing2->reply_to_addr = 'reply@exmaple.com'; + $this->emailmarketing2->status = 'active'; + $this->emailmarketing2->all_prospect_lists = 1; + $this->emailmarketing2->date_start = $timeDate->to_display_date(date('Y')+1 .'-01-01') . ' 00:00:00'; + + $query = 'SELECT id FROM inbound_email WHERE deleted=0'; + $result = $GLOBALS['db']->query($query); + while($row = $GLOBALS['db']->fetchByAssoc($result)) + { + $this->emailmarketing->inbound_email_id = $row['id']; + $this->emailmarketing2->inbound_email_id = $row['id']; + break; + } + + $query = 'SELECT id FROM email_templates WHERE deleted=0'; + while($row = $GLOBALS['db']->fetchByAssoc($result)) + { + $this->emailmarketing->template_id = $row['id']; + $this->emailmarketing2->template_id = $row['id']; + break; + } + + $this->emailmarketing->save(); + $this->emailmarketing2->save(); + + $this->campaign->load_relationship('prospectlists'); + $this->prospectlist = new ProspectList(); + $this->prospectlist->name = $this->campaign->name.' Prospect List1'; + $this->prospectlist->assigned_user_id= $GLOBALS['current_user']->id; + $this->prospectlist->list_type = "default"; + $this->prospectlist->save(); + $this->campaign->prospectlists->add($this->prospectlist->id); + + $this->campaign->load_relationship('prospectlists'); + $this->prospectlist2 = new ProspectList(); + $this->prospectlist2->name = $this->campaign->name.' Prospect List2'; + $this->prospectlist2->assigned_user_id= $GLOBALS['current_user']->id; + $this->prospectlist2->list_type = "default"; + $this->prospectlist2->save(); + $this->campaign->prospectlists->add($this->prospectlist2->id); + + $campaign_log_states = array(0=>'viewed', 1=>'link', 2=>'invalid email', 3=>'send error', 4=>'removed', 5=>'blocked', 6=>'lead', 7=>'contact'); + + for($i=0; $i < 10; $i++) + { + $contact = SugarTestContactUtilities::createContact(); + $contact->campaign_id = $this->campaign->id; + $contact->email2 = 'contact'. mt_rand() . '@sugar.com'; //Simulate a secondary email + $contact->save(); + $contact->load_relationship('prospect_lists'); + $contact->prospect_lists->add($this->prospectlist->id); + $contact->prospect_lists->add($this->prospectlist2->id); + + $this->create_campaign_log($this->campaign, $contact, $this->emailmarketing, $this->prospectlist, 'targeted'); + $this->create_campaign_log($this->campaign, $contact, $this->emailmarketing, $this->prospectlist, $campaign_log_states[mt_rand(0, 7)]); + + $this->create_campaign_log($this->campaign, $contact, $this->emailmarketing2, $this->prospectlist, 'targeted'); + $this->create_campaign_log($this->campaign, $contact, $this->emailmarketing2, $this->prospectlist, $campaign_log_states[mt_rand(0, 7)]); + } + + for($i=0; $i < 10; $i++) + { + $lead = SugarTestLeadUtilities::createLead(); + $lead->campaign_id = $this->campaign->id; + $lead->email2 = 'lead2' . mt_rand() . '@sugar.com'; //Simulate a secondary email + $lead->save(); + $lead->load_relationship('prospect_lists'); + $lead->prospect_lists->add($this->prospectlist->id); + $lead->prospect_lists->add($this->prospectlist2->id); + + $this->create_campaign_log($this->campaign, $lead, $this->emailmarketing, $this->prospectlist, 'targeted'); + $this->create_campaign_log($this->campaign, $lead, $this->emailmarketing, $this->prospectlist, $campaign_log_states[mt_rand(0, 7)]); + + $this->create_campaign_log($this->campaign, $lead, $this->emailmarketing2, $this->prospectlist, 'targeted'); + $this->create_campaign_log($this->campaign, $lead, $this->emailmarketing2, $this->prospectlist, $campaign_log_states[mt_rand(0, 7)]); + } + + + //But wait, there's more... now we email the friggin thing to place it in the queue + + + if ($this->campaign->db->dbType=='oci8') { + } else { + $current_date= "'".gmdate($GLOBALS['timedate']->get_db_date_time_format())."'"; + } + + //start scheduling now..... + $emailmarketing_beans = array($this->emailmarketing, $this->emailmarketing2); + foreach ($emailmarketing_beans as $marketing) { + + $mergedvalue=$GLOBALS['timedate']->merge_date_time($marketing->date_start,$marketing->time_start); + + if ($this->campaign->db->dbType=='oci8') { + } else { + $send_date_time= "'".$GLOBALS['timedate']->to_db_date($mergedvalue) . ' ' .$GLOBALS['timedate']->to_db_time($mergedvalue)."'"; + } + + //find all prospect lists associated with this email marketing message. + if ($marketing->all_prospect_lists == 1) { + $query="SELECT prospect_lists.id prospect_list_id from prospect_lists "; + $query.=" INNER JOIN prospect_list_campaigns plc ON plc.prospect_list_id = prospect_lists.id"; + $query.=" WHERE plc.campaign_id='{$this->campaign->id}'"; + $query.=" AND prospect_lists.deleted=0"; + $query.=" AND plc.deleted=0"; + $query.=" AND prospect_lists.list_type!='test' AND prospect_lists.list_type not like 'exempt%'"; + } else { + $query="select email_marketing_prospect_lists.* FROM email_marketing_prospect_lists "; + $query.=" inner join prospect_lists on prospect_lists.id = email_marketing_prospect_lists.prospect_list_id"; + $query.=" WHERE prospect_lists.deleted=0 and email_marketing_id = '{$marketing->id}' and email_marketing_prospect_lists.deleted=0"; + $query.=" AND prospect_lists.list_type!='test' AND prospect_lists.list_type not like 'exempt%'"; + } + $result=$this->campaign->db->query($query); + while (($row=$this->campaign->db->fetchByAssoc($result))!=null ) { + $prospect_list_id=$row['prospect_list_id']; + //delete all messages for the current campaign and current email marketing message. + $delete_emailman_query="delete from emailman where campaign_id='{$this->campaign->id}' and marketing_id='{$marketing->id}' and list_id='{$prospect_list_id}'"; + $this->campaign->db->query($delete_emailman_query); + + $insert_query= "INSERT INTO emailman (date_entered, user_id, campaign_id, marketing_id,list_id, related_id, related_type, send_date_time"; + if ($this->campaign->db->dbType=='oci8') { + } + $insert_query.=')'; + $insert_query.= " SELECT $current_date,'{$GLOBALS['current_user']->id}',plc.campaign_id,'{$marketing->id}',plp.prospect_list_id, plp.related_id, plp.related_type,{$send_date_time} "; + if ($this->campaign->db->dbType=='oci8') { + } + $insert_query.= "FROM prospect_lists_prospects plp "; + $insert_query.= "INNER JOIN prospect_list_campaigns plc ON plc.prospect_list_id = plp.prospect_list_id "; + $insert_query.= "WHERE plp.prospect_list_id = '{$prospect_list_id}' "; + $insert_query.= "AND plp.deleted=0 "; + $insert_query.= "AND plc.deleted=0 "; + $insert_query.= "AND plc.campaign_id='{$this->campaign->id}'"; + + if ($this->campaign->db->dbType=='oci8') { + } + $this->campaign->db->query($insert_query); + } + } + } + + public function tearDown() + { + $GLOBALS['current_user'] = $this->saved_current_user; + + if($this->remove_beans) + { + $this->campaign->mark_deleted($this->campaign->id); + $this->prospectlist->mark_deleted($this->prospectlist->id); + + SugarTestContactUtilities::removeAllCreatedContacts(); + SugarTestLeadUtilities::removeAllCreatedLeads(); + } + + if($this->clear_database) + { + $sql = 'DELETE FROM email_marketing WHERE campaign_id = \'' . $this->campaign->id . '\''; + $GLOBALS['db']->query($sql); + + $sql = 'DELETE FROM emailman WHERE campaign_id = \'' . $this->campaign->id . '\''; + $GLOBALS['db']->query($sql); + + $sql = 'DELETE FROM campaign_log WHERE campaign_id = \'' . $this->campaign->id . '\''; + $GLOBALS['db']->query($sql); + + $sql = 'DELETE FROM prospect_lists_prospects WHERE prospect_list_id=\'' . $this->prospectlist->id . '\''; + $GLOBALS['db']->query($sql); + + $sql = 'DELETE FROM prospect_lists_prospects WHERE prospect_list_id=\'' . $this->prospectlist2->id . '\''; + $GLOBALS['db']->query($sql); + + $sql = 'DELETE FROM prospect_lists WHERE id = \'' . $this->prospectlist->id . '\''; + $GLOBALS['db']->query($sql); + + $sql = 'DELETE FROM prospect_lists WHERE id = \'' . $this->prospectlist2->id . '\''; + $GLOBALS['db']->query($sql); + + $sql = 'DELETE FROM prospect_list_campaigns WHERE campaign_id = \'' . $this->campaign->id . '\''; + $GLOBALS['db']->query($sql); + + $sql = 'DELETE FROM campaigns WHERE id = \'' . $this->campaign->id . '\''; + $GLOBALS['db']->query($sql); + } + + } + + function test_viewed_message() + { + $this->markTestSkipped('Skip for now'); + $this->assertTrue(true); + } + + protected function create_campaign_log($campaign, $target, $marketing, $prospectlist, $activity_type, $target_tracker_key='') + { + $campaign_log = new CampaignLog(); + $campaign_log->campaign_id=$campaign->id; + $campaign_log->target_tracker_key=$target_tracker_key; + $campaign_log->target_id= $target->id; + $campaign_log->target_type=$target->module_dir; + $campaign_log->marketing_id=$marketing->id; + $campaign_log->more_information=$target->email1; + $campaign_log->activity_type=$activity_type; + $campaign_log->activity_date=$GLOBALS['timedate']->to_display_date_time(gmdate($GLOBALS['timedate']->get_db_date_time_format())); + $campaign_log->list_id=$prospectlist->id; + $campaign_log->related_type='Emails'; + $campaign_log->save(); + } + +} +?> \ No newline at end of file diff --git a/tests/modules/Configurator/ConfiguratorTest.php b/tests/modules/Configurator/ConfiguratorTest.php new file mode 100755 index 00000000..3fc4839c --- /dev/null +++ b/tests/modules/Configurator/ConfiguratorTest.php @@ -0,0 +1,24 @@ + 'true', + 'admin_export_only' => 'false', + 'upload_dir' => 'yummy' + ); + + $cfg = new Configurator(); + + $cfg->populateFromPost(); + + $this->assertEquals($cfg->config['disable_export'], true); + $this->assertEquals($cfg->config['admin_export_only'], false); + $this->assertEquals($cfg->config['upload_dir'], 'yummy'); + + unset($_POST); + } +} diff --git a/tests/modules/Contacts/Bug15255Test.php b/tests/modules/Contacts/Bug15255Test.php new file mode 100755 index 00000000..681f6c48 --- /dev/null +++ b/tests/modules/Contacts/Bug15255Test.php @@ -0,0 +1,65 @@ +id = 'c_'.$unid; + $contact->first_name = 'testfirst'; + $contact->last_name = 'testlast'; + $contact->new_with_id = true; + $contact->disable_custom_fields = true; + $contact->save(); + $this->c = $contact; + + $account = new Account(); + $account->id = 'a_'.$unid; + $account->first_name = 'testfirst'; + $account->last_name = 'testlast'; + $account->assigned_user_id = 'SugarUser'; + $account->new_with_id = true; + $account->disable_custom_fields = true; + $account->save(); + $this->a = $account; + + $ac_id = 'ac_'.$unid; + $this->ac_id = $ac_id; + $GLOBALS['db']->query("insert into accounts_contacts (id , contact_id, account_id, date_modified, deleted) values ('{$ac_id}', '{$contact->id}', '{$account->id}', '$time', 0)"); + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + + $GLOBALS['db']->query("DELETE FROM contacts WHERE id= '{$this->c->id}'"); + $GLOBALS['db']->query("DELETE FROM accounts WHERE id = '{$this->a->id}'"); + $GLOBALS['db']->query("DELETE FROM accounts_contacts WHERE id = '{$this->ac_id}'"); + + unset($this->a); + unset($this->c); + unset($this->ac_id); + } + + function testFill_in_additional_detail_fields(){ + $locale = new Localization(); + $this->c->fill_in_additional_detail_fields(); + $localName = $locale->getLocaleFormattedName('testfirst', 'testlast'); + $this->assertEquals($this->c->name, $localName); + //$this->assertEquals($this->c->name, 'testfirst testlast'); + } +} +?> \ No newline at end of file diff --git a/tests/modules/Contacts/Bug7825Test.php b/tests/modules/Contacts/Bug7825Test.php new file mode 100755 index 00000000..0c64fc51 --- /dev/null +++ b/tests/modules/Contacts/Bug7825Test.php @@ -0,0 +1,24 @@ +retrieve('1'); + + $current_user->setPreference('default_locale_name_format', 'l f s'); + $sugar_field_relate = new SugarFieldRelate('Relate'); + $new_field = $sugar_field_relate->formatField('Max Liang', array('name' => 'contact_name')); + + $this->assertEquals(trim($new_field), trim('Liang Max'), "Assert that name format is correct"); + + $current_user->setPreference('default_locale_name_format', 'f l s'); + $sugar_field_relate = new SugarFieldRelate('Relate'); + $new_field = $sugar_field_relate->formatField('Max Liang', array('name' => 'contact_name')); + + $this->assertEquals(trim($new_field), trim('Max Liang'), "Assert that name format is correct"); + } +} \ No newline at end of file diff --git a/tests/modules/DynamicFields/Bug24095Test.php b/tests/modules/DynamicFields/Bug24095Test.php new file mode 100755 index 00000000..b2f0aac7 --- /dev/null +++ b/tests/modules/DynamicFields/Bug24095Test.php @@ -0,0 +1,61 @@ +accountMockBean = PHPUnit_Framework_MockObject_Mock::generate('Account' , array('hasCustomFields')); + $this->_tablename = 'test' . date("YmdHis"); + if ( isset($GLOBALS['installing']) ) + $this->_old_installing = $GLOBALS['installing']; + $GLOBALS['installing'] = true; + + $GLOBALS['db']->createTableParams($this->_tablename . '_cstm', + array( + 'id_c' => array ( + 'name' => 'id_c', + 'type' => 'id', + ), + 'foo_c' => array ( + 'name' => 'foo_c', + 'type' => 'varchar', + 'len' => '255', + ), + ), + array() + ); + $GLOBALS['db']->query("INSERT INTO {$this->_tablename}_cstm (id_c,foo_c) VALUES ('12345','67890')"); + } + + public function tearDown() + { + $GLOBALS['db']->dropTableName($this->_tablename . '_cstm'); + if ( isset($this->_old_installing) ) + $GLOBALS['installing'] = $this->_old_installing; + } + + public function testDynamicFieldsRetrieveWorks() + { + $bean =new $this->accountMockBean->mockClassName(); + $bean->custom_fields = new DynamicField($bean->module_dir); + $bean->custom_fields->setup($bean); + $bean->expects($this->any()) + ->method('hasCustomFields') + ->will($this->returnValue(true)); + $bean->table_name = $this->_tablename; + $bean->id = '12345'; + $bean->custom_fields->retrieve(); + $this->assertEquals($bean->id_c, '12345'); + $this->assertEquals($bean->foo_c, '67890'); + } +} + + diff --git a/tests/modules/DynamicFields/Bug39766Test.php b/tests/modules/DynamicFields/Bug39766Test.php new file mode 100755 index 00000000..77057dc8 --- /dev/null +++ b/tests/modules/DynamicFields/Bug39766Test.php @@ -0,0 +1,20 @@ + 2, 'type' => 'float'); + require_once ('modules/DynamicFields/FieldCases.php') ; + $field = get_widget ( $_REQUEST [ 'type' ] ) ; + $field->populateFromPost () ; + + $this->assertEquals($field->ext1, 2, 'Asserting that the ext1 value was set to the proper precision'); + $this->assertEquals($field->precision, 2, 'Asserting that the precision value was set to the proper precision'); + } +} diff --git a/tests/modules/DynamicFields/RepairCustomFieldsTest.php b/tests/modules/DynamicFields/RepairCustomFieldsTest.php new file mode 100755 index 00000000..32f92d40 --- /dev/null +++ b/tests/modules/DynamicFields/RepairCustomFieldsTest.php @@ -0,0 +1,122 @@ +df->buildCache($this->modulename); + VardefManager::clearVardef(); + VardefManager::refreshVardefs($this->modulename, $this->objectname); + $this->seed->field_defs = $GLOBALS['dictionary'][$this->objectname]['fields']; + + } + + public function setUp() + { + $this->markTestSkipped("Skipping for now..."); + $this->field = get_widget('varchar'); + $this->field->id = $this->modulename.'foo_c'; + $this->field->name = 'foo_c'; + $this->field->vanme = 'LBL_Foo'; + $this->field->comments = NULL; + $this->field->help = NULL; + $this->field->custom_module = $this->modulename; + $this->field->type = 'varchar'; + $this->field->label = 'LBL_FOO'; + $this->field->len = 255; + $this->field->required = 0; + $this->field->default_value = NULL; + $this->field->date_modified = '2009-09-14 02:23:23'; + $this->field->deleted = 0; + $this->field->audited = 0; + $this->field->massupdate = 0; + $this->field->duplicate_merge = 0; + $this->field->reportable = 1; + $this->field->importable = 'true'; + $this->field->ext1 = NULL; + $this->field->ext2 = NULL; + $this->field->ext3 = NULL; + $this->field->ext4 = NULL; + $this->seed = new Account(); + $this->df = new DynamicField($this->modulename); + $this->df->setup ( $this->seed ) ; + + $this->field->save ( $this->df ) ; + $this->db = $GLOBALS['db']; + + $this->repairDictionary(); + + } + + public function tearDown() + { + $this->field->delete ( $this->df ) ; + if ($this->db->tableExists($this->table_name)) + { + $this->db->dropTableName($this->table_name); + } + } + + public function testRepairRemovedFieldNoExecute() + { + //Remove the custom column + $this->db->query("ALTER TABLE {$this->table_name} DROP COLUMN {$this->field->name}"); + //Run repair + $ret = $this->df->repairCustomFields(false); + $this->assertRegExp("/MISSING IN DATABASE - {$this->field->name} - ROW/", $ret); + $compareFieldDefs = $this->db->getHelper()->get_columns($this->table_name); + $this->assertArrayNotHasKey($this->field->name, $compareFieldDefs); + } + + public function testRepairRemovedFieldExecute() + { + //Remove the custom column + $this->db->query("ALTER TABLE {$this->table_name} DROP COLUMN {$this->field->name}"); + //Run repair + $ret = $this->df->repairCustomFields(true); + $this->assertRegExp("/MISSING IN DATABASE - {$this->field->name} - ROW/", $ret); + $compareFieldDefs = $this->db->getHelper()->get_columns($this->table_name); + $this->assertArrayHasKey($this->field->name, $compareFieldDefs); + } + + public function testCreateTableNoExecute() + { + //Remove the custom table + $this->db->dropTableName($this->table_name); + //Run repair + $ret = $this->df->repairCustomFields(false); + //Test that the table is going to be created. + $this->assertRegExp("/Missing Table: {$this->table_name}/", $ret); + //Test that the custom field is going to be added. + $this->assertRegExp("/MISSING IN DATABASE - {$this->field->name} - ROW/", $ret); + //Assert that the table was NOT created + $this->assertFalse($this->db->tableExists($this->table_name), + "Asserting that the custom table is not created when repair is run with execute set false"); + } + + public function testCreateTableExecute() + { + //Remove the custom table + $this->db->dropTableName($this->table_name); + //Run repair + $ret = $this->df->repairCustomFields(); + $this->assertRegExp("/MISSING IN DATABASE - {$this->field->name} - ROW/", $ret); + //Test that the table is going to be created. + $this->assertRegExp("/Missing Table: {$this->table_name}/", $ret); + //Test that the custom field is going to be added. + $this->assertRegExp("/MISSING IN DATABASE - {$this->field->name} - ROW/", $ret); + //Assert that the table was created + $this->assertTrue($this->db->tableExists($this->table_name), + "Asserting that the custom table is created when repair is run with execute not set"); + } +} diff --git a/tests/modules/DynamicFields/URLFieldTest.php b/tests/modules/DynamicFields/URLFieldTest.php new file mode 100755 index 00000000..6c780079 --- /dev/null +++ b/tests/modules/DynamicFields/URLFieldTest.php @@ -0,0 +1,47 @@ +field = get_widget('url'); + $this->field->id = $this->_modulename.'foo_c'; + $this->field->name = 'foo_c'; + $this->field->vanme = 'LBL_Foo'; + $this->field->comments = NULL; + $this->field->help = NULL; + $this->field->custom_module = $this->_modulename; + $this->field->type = 'url'; + $this->field->len = 255; + $this->field->required = 0; + $this->field->default_value = NULL; + $this->field->date_modified = '2009-09-14 02:23:23'; + $this->field->deleted = 0; + $this->field->audited = 0; + $this->field->massupdate = 0; + $this->field->duplicate_merge = 0; + $this->field->reportable = 1; + $this->field->importable = 'true'; + $this->field->ext1 = NULL; + $this->field->ext2 = NULL; + $this->field->ext3 = NULL; + $this->field->ext4 = NULL; + } + + public function tearDown() + { + } + + public function testURLFieldsInVardef() + { + $this->field->ext4 = '_self'; + $vardef = $this->field->get_field_def(); + $this->assertEquals($vardef['link_target'], '_self'); + } +} diff --git a/tests/modules/EmailAddresses/EmailAddressTest.php b/tests/modules/EmailAddresses/EmailAddressTest.php new file mode 100755 index 00000000..1c959feb --- /dev/null +++ b/tests/modules/EmailAddresses/EmailAddressTest.php @@ -0,0 +1,61 @@ +emailaddress = new EmailAddress(); + } + + public function tearDown() + { + unset($this->emailaddress); + $query = "delete from email_addresses where email_address = '".$this->testEmailAddressString."';"; + $GLOBALS['db']->query($query); + } + + public function testEmailAddress() + { + $id = ''; + $module = ''; + $new_addrs=array(); + $primary=''; + $replyTo=''; + $invalid=''; + $optOut=''; + $in_workflow=false; + $_REQUEST['_email_widget_id'] = 0; + $_REQUEST['0emailAddress0'] = $this->testEmailAddressString; + $_REQUEST['emailAddressPrimaryFlag'] = '0emailAddress0'; + $_REQUEST['emailAddressVerifiedFlag0'] = 'true'; + $_REQUEST['emailAddressVerifiedValue0'] = 'unitTest@sugarcrm.com'; + $requestVariablesSet = array('0emailAddress0','emailAddressPrimaryFlag','emailAddressVerifiedFlag0','emailAddressVerifiedValue0'); + $this->emailaddress->save($id, $module, $new_addrs, $primary, $replyTo, $invalid, $optOut, $in_workflow); + foreach ($requestVariablesSet as $k) + unset($_REQUEST[$k]); + + $this->assertEquals($this->emailaddress->addresses[0]['email_address'], $this->testEmailAddressString); + $this->assertEquals($this->emailaddress->addresses[0]['primary_address'], 1); + } + + public function testSaveEmailAddressUsingSugarbeanSave() + { + $this->emailaddress->email_address = $this->testEmailAddressString; + $this->emailaddress->opt_out = '1'; + $this->emailaddress->save(); + + $this->assertTrue(!empty($this->emailaddress->id)); + $this->assertEquals( + $this->emailaddress->id, + $GLOBALS['db']->getOne("SELECT id FROM email_addresses WHERE id = '{$this->emailaddress->id}' AND email_address = '{$this->testEmailAddressString}' and opt_out = '1'"), + 'Email Address record not added' + ); + } +} \ No newline at end of file diff --git a/tests/modules/Emails/Bug32489Test.php b/tests/modules/Emails/Bug32489Test.php new file mode 100755 index 00000000..e47dbce8 --- /dev/null +++ b/tests/modules/Emails/Bug32489Test.php @@ -0,0 +1,107 @@ +outbound_id = uniqid(); + $time = date('Y-m-d H:i:s'); + + $em = new Email(); + $em->name = 'tst_' . uniqid(); + $em->type = 'inbound'; + $em->intent = 'pick'; + $em->date_sent = $timedate->to_display_date_time(gmdate("Y-m-d H:i:s", (gmmktime() + (3600 * 24 * 2) ))) ; //Two days from today + $em->save(); + $this->em1 = $em; + + $n = new Note(); + $n->name = 'tst_' . uniqid(); + $n->filename = 'file_' . uniqid(); + $n->parent_type = 'Emails'; + $n->parent_id = $this->em1->id; + $n->save(); + $this->note1 = $n; + + + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + + $GLOBALS['db']->query("DELETE FROM emails WHERE id= '{$this->em1->id}'"); + $GLOBALS['db']->query("DELETE FROM notes WHERE id= '{$this->note1->id}'"); + if($this->note2 != null) + $GLOBALS['db']->query("DELETE FROM notes WHERE id= '{$this->note2->id}'"); + + unset($this->em1); + unset($this->note1); + unset($this->note2); + } + + function testSimpleImportEmailSearch(){ + global $current_user,$timedate; + + //Simple search by name + $_REQUEST['name'] = $this->em1->name; + $results = $this->em1->searchImportedEmails(); + $this->assertEquals(1, count($results['out']), "Could not perform a simple search for imported emails" ); + $this->assertEquals(count($results['out']), $results['totalCount'], "Imported emails search, total count of result set and count query not equal."); + + //Search should return nothing + $_REQUEST['name'] = uniqid() . uniqid(); //Should be enough entropy. + $results = $this->em1->searchImportedEmails(); + $this->assertEquals(0, count($results['out']), "Could not perform a simple search for imported emails, expected no results" ); + + //Search by date filters. + $tomm = gmdate('Y-m-d H:i:s',(gmmktime() + 3600 * 24)); + $tommDisplay = $timedate->to_display_date_time($tomm); + $_REQUEST['dateFrom'] = $tommDisplay; + unset($_REQUEST['name']); + $results = $this->em1->searchImportedEmails(); + $this->assertTrue(count($results['out']) >= 1, "Could not perform a simple search for imported emails with a single date filter" ); + + $weekFromNow = gmdate('Y-m-d H:i:s',(gmmktime() + (3600 * 24 * 7))); + $weekFromNowDisplay = $timedate->to_display_date_time($weekFromNow); + $_REQUEST['dateTo'] = $weekFromNowDisplay; + $results = $this->em1->searchImportedEmails(); + $this->assertTrue(count($results['out']) >= 1, "Could not perform a simple search for imported emails with a two date filter" ); + } + + function testSimpleImportEmailSearchWithAttachments() + { + unset($_REQUEST); + $_REQUEST['name'] = $this->em1->name; + $_REQUEST['attachmentsSearch'] = 1; + $results = $this->em1->searchImportedEmails(); + $this->assertEquals(1, count($results['out']), "Could not perform a simple search for imported emails with single attachment" ); + + //Add a second note related to same parent, same results should be obtained. + $n = new Note(); + $n->name = 'tst2_' . uniqid(); + $n->filename = 'file2_' . uniqid(); + $n->parent_type = 'Emails'; + $n->parent_id = $this->em1->id; + $n->save(); + $this->note2 = $n; + $results = $this->em1->searchImportedEmails(); + $this->assertEquals(1, count($results['out']), "Could not perform a simple search for imported emails with multiple attachment" ); + } +} +?> \ No newline at end of file diff --git a/tests/modules/Emails/Bug40527Test.php b/tests/modules/Emails/Bug40527Test.php new file mode 100755 index 00000000..be164b79 --- /dev/null +++ b/tests/modules/Emails/Bug40527Test.php @@ -0,0 +1,40 @@ +contact = SugarTestContactUtilities::createContact(); + $this->account = SugarTestAccountUtilities::createAccount(); + + $override_data = array( + 'parent_type' => 'Accounts', + 'parent_id' => $this->account->id, + ); + $this->email = SugarTestEmailUtilities::createEmail('', $override_data); + } + + public function tearDown() + { + SugarTestContactUtilities::removeAllCreatedContacts(); + SugarTestAccountUtilities::removeAllCreatedAccounts(); + SugarTestEmailUtilities::removeAllCreatedEmails(); + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + } + + public function testContactRelationship() + { + $this->assertTrue($this->email->parent_type == 'Accounts', "The email parent_type should be Accounts"); + $this->assertTrue($this->email->parent_id == $this->account->id, "The email parent_id should be SDizzle"); + + $this->email->fill_in_additional_detail_fields(); + $this->assertTrue(empty($this->email->contact_id), "There should be no contact associated with the Email"); + } +} diff --git a/tests/modules/Emails/ComposePackageTest.php b/tests/modules/Emails/ComposePackageTest.php new file mode 100755 index 00000000..72b33145 --- /dev/null +++ b/tests/modules/Emails/ComposePackageTest.php @@ -0,0 +1,73 @@ +id = 'c_'.$unid; + $contact->first_name = 'testfirst'; + $contact->last_name = 'testlast'; + $contact->new_with_id = true; + $contact->disable_custom_fields = true; + $contact->save(); + $this->c = $contact; + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + unset($GLOBALS['beanFiles']); + unset($GLOBALS['beanList']); + + $GLOBALS['db']->query("DELETE FROM contacts WHERE id= '{$this->c->id}'"); + + unset($this->c); + } + + public function testComposeFromMethodCallNoData() + { + $_REQUEST['forQuickCreate'] = true; + require_once('modules/Emails/Compose.php'); + $data = array(); + $compose_data = generateComposeDataPackage($data,FALSE); + + $this->assertEquals('', $compose_data['to_email_addrs']); + } + + public function testComposeFromMethodCallForContact() + { + $_REQUEST['forQuickCreate'] = true; + require_once('modules/Emails/Compose.php'); + $data = array(); + $data['parent_type'] = 'Contacts'; + $data['parent_id'] = $this->c->id; + + $compose_data = generateComposeDataPackage($data,FALSE); + + $this->assertEquals('Contacts', $compose_data['parent_type']); + $this->assertEquals($this->c->id, $compose_data['parent_id']); + $this->assertEquals($this->c->name, $compose_data['parent_name']); + } +} \ No newline at end of file diff --git a/tests/modules/Emails/EmailTest.php b/tests/modules/Emails/EmailTest.php new file mode 100755 index 00000000..ab161e78 --- /dev/null +++ b/tests/modules/Emails/EmailTest.php @@ -0,0 +1,88 @@ +email = new Email(); + $this->email->email2init(); + } + + public function tearDown() + { + unset($this->email); + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + } + + public function testSafeAttachmentName () + { + $extArray[] = '0.py'; + $extArray[] = '1.php'; + $extArray[] = '2.php3'; + $extArray[] = '3.php4'; + $extArray[] = '4.php5'; + $extArray[] = '5.js'; + $extArray[] = '6.htm'; + $extArray[] = '7.html'; + $extArray[] = '8.txt'; + $extArray[] = '9.doc'; + $extArray[] = '10.xls'; + $extArray[] = '11.pdf'; + $extArray[] = '12'; + + for ($i = 0; $i < count($extArray); $i++) { + $result = $this->email->safeAttachmentName($extArray[$i]); + if ($i < 8) { + $this->assertEquals($result, true); + } else { + $this->assertEquals($result, false); + } + } + } + + public function testEmail2ParseAddresses() + { + $emailDisplayName[] = ''; + $emailDisplayName[] = 'Shine Ye'; + $emailDisplayName[] = 'Roger,Smith'; + $emailAddress[] = 'masonhu@sugarcrm.com'; + $emailAddress[] = 'xye@sugarcrm.com'; + $emailAddress[] = 'roger@sugarcrm.com'; + for ($j = 0; $j < count($emailDisplayName); $j++) + { + if ($j < 1) + $emailString[] = $emailDisplayName[$j].$emailAddress[$j]; + else + $emailString[] = $emailDisplayName[$j].'<'.$emailAddress[$j].'>'; + + } + $emailAddressString = implode(', ', $emailString); + $result = $this->email->email2ParseAddresses($emailAddressString); + $onlyEmailResult = $this->email->email2ParseAddressesForAddressesOnly($emailAddressString); + for ($v = 0; $v < count($result); $v++) + { + $this->assertEquals($result[$v]['display'], $emailDisplayName[$v]); + $this->assertEquals($result[$v]['email'], $emailAddress[$v]); + $this->asserteQuals($onlyEmailResult[$v], $emailAddress[$v]); + } + } + + public function testDecodeDuringSend() + { + $testString = 'Replace sugarLessThan and sugarGreaterThan with < and >'; + $expectedResult = 'Replace < and > with < and >'; + $resultString = $this->email->decodeDuringSend($testString); + $this->asserteQuals($resultString, $expectedResult); + } +} +?> \ No newline at end of file diff --git a/tests/modules/Emails/EmailUITest.php b/tests/modules/Emails/EmailUITest.php new file mode 100755 index 00000000..20bc8db2 --- /dev/null +++ b/tests/modules/Emails/EmailUITest.php @@ -0,0 +1,108 @@ +eui = new EmailUI(); + $this->_folders = array(); + } + + public function tearDown() + { + $GLOBALS['db']->query("DELETE FROM folders_subscriptions WHERE assigned_user_id='{$GLOBALS['current_user']->id}'"); + foreach ($this->_folders as $f) { + $GLOBALS['db']->query("DELETE FROM folders_subscriptions WHERE folder_id='{$f}'"); + $GLOBALS['db']->query("DELETE FROM folders WHERE id='{$f}'"); + } + + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + unset($GLOBALS['beanFiles']); + unset($GLOBALS['beanList']); + } + + /** + * Save a SugarFolder + */ + public function testSaveNewFolder() + { + $newFolderName = "UNIT_TEST"; + $rs = $this->eui->saveNewFolder($newFolderName,'Home',0); + $newFolderID = $rs['id']; + $this->_folders[] = $newFolderID; + + $sf = new SugarFolder(); + $sf->retrieve($newFolderID); + $this->assertEquals($newFolderName, $sf->name); + + } + + /** + * Save the user preference for list view order per IE account. + * + */ + public function testSaveListViewSortOrder() + { + $tmpId = create_guid(); + $folderName = "UNIT_TEST"; + $sortBy = 'last_name'; + $dir = "DESC"; + $rs = $this->eui->saveListViewSortOrder($tmpId,$folderName,$sortBy,$dir); + + //Check against the saved preferences. + $prefs = unserialize($GLOBALS['current_user']->getPreference('folderSortOrder', 'Emails')); + $this->assertEquals($sortBy, $prefs[$tmpId][$folderName]['current']['sort']); + $this->assertEquals($dir, $prefs[$tmpId][$folderName]['current']['direction']); + + + } + public function testGetRelatedEmail() + { + + $account = new Account(); + $account->name = "emailTestAccount"; + $account->save(false); + + $relatedBeanInfo = array('related_bean_id' => $account->id, "related_bean_type" => "Accounts"); + + //First pass should return a blank query as are no related items + $qArray = $this->eui->getRelatedEmail("LBL_DROPDOWN_LIST_ALL", array(), $relatedBeanInfo); + $this->assertEquals("", $qArray['query']); + + //Now create a related Contact + $contact = new Contact(); + $contact->name = "emailTestContact"; + $contact->account_id = $account->id; + $contact->account_name = $account->name; + $contact->email1 = "test@test.com"; + $contact->save(false); + + //Now we should get a result + $qArray = $this->eui->getRelatedEmail("LBL_DROPDOWN_LIST_ALL", array(), $relatedBeanInfo); + $r = $account->db->limitQuery($qArray['query'], 0, 25, true); + $person = array(); + $a = $account->db->fetchByAssoc($r); + $person['bean_id'] = $a['id']; + $person['bean_module'] = $a['module']; + $person['email'] = $a['email_address']; + + $this->assertEquals("test@test.com", $person['email']); + + //Cleanup + $contact->deleted = true; + $contact->save(false); + $account->deleted = true; + $account->save(false); + + } +} \ No newline at end of file diff --git a/tests/modules/Emails/FindEmailFromBeanIdsTest.php b/tests/modules/Emails/FindEmailFromBeanIdsTest.php new file mode 100755 index 00000000..2b0bfa67 --- /dev/null +++ b/tests/modules/Emails/FindEmailFromBeanIdsTest.php @@ -0,0 +1,45 @@ +emailUI = new EmailUI(); + $this->beanIds[] = '8744c7d9-9e4b-2338-cb76-4ab0a3d0a651'; + $this->beanIds[] = '8749a110-1d85-4562-fa23-4ab0a3c65e12'; + $this->beanIds[] = '874c1242-4645-898d-238a-4ab0a3f7e7c3'; + $this->beanType = 'users'; + $this->whereArr['first_name'] = 'testfn'; + $this->whereArr['last_name'] = 'testln'; + $this->whereArr['email_address'] = 'test@example.com'; + $this->expectedQuery = <<emailUI); + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + } + + function testFindEmailFromBeanIdTest() + { + //$this->resultQuery = $this->emailUI->findEmailFromBeanIds('', $this->beanType, $this->whereArr); + $this->resultQuery = $this->emailUI->findEmailFromBeanIds($this->beanIds, $this->beanType, $this->whereArr); + $this->assertEquals($this->expectedQuery, $this->resultQuery); + } +} + +?> \ No newline at end of file diff --git a/tests/modules/Emails/HandleBodyInHTMLformatTest.php b/tests/modules/Emails/HandleBodyInHTMLformatTest.php new file mode 100755 index 00000000..4897103a --- /dev/null +++ b/tests/modules/Emails/HandleBodyInHTMLformatTest.php @@ -0,0 +1,45 @@ +sugarMailer = new SugarPHPMailer(); + $this->email = new Email(); + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + } + + public function testHandleBodyInHtmlformat () + { + $emailBodyInHtml = << ' +EOQ; + + $emailBodyInHtmlResult = << ' was translated +to " < > ' +EOQ; + $this->email->description_html = $emailBodyInHtml; + $this->assertNotEquals($this->sugarMailer->Body, $emailBodyInHtmlResult); + $this->email->handleBodyInHTMLformat($this->sugarMailer); + $this->assertEquals($this->sugarMailer->Body, $emailBodyInHtmlResult); + } +} +?> \ No newline at end of file diff --git a/tests/modules/Home/QuickSearchTests.php b/tests/modules/Home/QuickSearchTests.php new file mode 100755 index 00000000..d8d1cc3c --- /dev/null +++ b/tests/modules/Home/QuickSearchTests.php @@ -0,0 +1,48 @@ +query($q); + } + + public function testFormatResults() + { + $tempPT = new ProductTemplate(); + $tempPT->name = 'MasonUnitTest'; + $tempPT->description = "Unit'test"; + $tempPT->cost_price = 1000; + $tempPT->discount_price = 800; + $tempPT->list_price = 1100; + $tempPT->save(); + + $_REQUEST['data'] = '{"conditions":[{"end":"%","name":"name","op":"like_custom","value":""}],"field_list":["name","id","type_id","mft_part_num","cost_price","list_price","discount_price","pricing_factor","description","cost_usdollar","list_usdollar","discount_usdollar","tax_class_name"],"form":"EditView","group":"or","id":"EditView_product_name[1]","limit":"30","method":"query","modules":["ProductTemplates"],"no_match_text":"No Match","order":"name","populate_list":["name_1","product_template_id_1"],"post_onblur_function":"set_after_sqs"}'; + $_REQUEST['query'] = 'MasonUnitTest'; + require_once 'modules/home/quicksearchQuery.php'; + + $json = getJSONobj(); + $data = $json->decode(html_entity_decode($_REQUEST['data'])); + if(isset($_REQUEST['query']) && !empty($_REQUEST['query'])){ + foreach($data['conditions'] as $k=>$v){ + if(empty($data['conditions'][$k]['value'])){ + $data['conditions'][$k]['value']=$_REQUEST['query']; + } + } + } + $this->quickSearch = new quicksearchQuery(); + $result = $this->quickSearch->query($data); + $resultBean = $json->decodeReal($result); + $this->assertEquals($resultBean['fields'][0]['description'], $tempPT->description); + } +} +?> \ No newline at end of file diff --git a/tests/modules/Home/UnifiedSearchAdvancedTest.php b/tests/modules/Home/UnifiedSearchAdvancedTest.php new file mode 100755 index 00000000..4093c461 --- /dev/null +++ b/tests/modules/Home/UnifiedSearchAdvancedTest.php @@ -0,0 +1,66 @@ +id = 'l_'.$unid; + $contact->first_name = 'Greg'; + $contact->last_name = 'Brady'; + $contact->new_with_id = true; + $contact->save(); + $this->_contact = $contact; + } + + public function tearDown() + { + $GLOBALS['db']->query("DELETE FROM contacts WHERE id= '{$this->_contact->id}'"); + unset($this->_contact); + } + + public function testSearchByFirstName() + { + global $mod_strings, $modListHeader, $app_strings, $beanList, $beanFiles; + require('config.php'); + require('include/modules.php'); + $modListHeader = $moduleList; + $_REQUEST['query_string'] = $this->_contact->first_name; + $_REQUEST['module'] = 'Home'; + $usa = new UnifiedSearchAdvanced(); + ob_start(); + $usa->search(); + $html = ob_get_contents(); + ob_clean(); + $pos = strpos($html, $this->_contact->first_name); + $this->assertTrue(!empty($pos), "Could not find the contact: ".$this->_contact->first_name." in the search results."); + } + + public function testSearchByFirstAndLastName() + { + global $mod_strings, $modListHeader, $app_strings, $beanList, $beanFiles; + require('config.php'); + require('include/modules.php'); + $_REQUEST['query_string'] = $this->_contact->first_name.' '.$this->_contact->last_name; + $_REQUEST['module'] = 'Home'; + $usa = new UnifiedSearchAdvanced(); + ob_start(); + $usa->search(); + $html = ob_get_contents(); + ob_clean(); + $pos = strpos($html, $this->_contact->first_name); + $this->assertTrue(!empty($pos), "Could not find the lead: ".$this->_contact->first_name." in the search results."); + } +} + diff --git a/tests/modules/Import/Bug39494ImportFile.txt b/tests/modules/Import/Bug39494ImportFile.txt new file mode 100755 index 00000000..1bf8b971 --- /dev/null +++ b/tests/modules/Import/Bug39494ImportFile.txt @@ -0,0 +1,2 @@ +name city +tester1 wuhan \ No newline at end of file diff --git a/tests/modules/Import/ImportCacheFilesTest.php b/tests/modules/Import/ImportCacheFilesTest.php new file mode 100755 index 00000000..5a5058e4 --- /dev/null +++ b/tests/modules/Import/ImportCacheFilesTest.php @@ -0,0 +1,50 @@ +assertEquals( + "{$GLOBALS['sugar_config']['import_dir']}dupes_{$GLOBALS['current_user']->id}.csv", $filename); + } + + public function testgetErrorFileName() + { + $filename = ImportCacheFiles::getErrorFileName(); + + $this->assertEquals( + "{$GLOBALS['sugar_config']['import_dir']}error_{$GLOBALS['current_user']->id}.csv", $filename); + } + + public function testgetStatusFileName() + { + $filename = ImportCacheFiles::getStatusFileName(); + + $this->assertEquals( + "{$GLOBALS['sugar_config']['import_dir']}status_{$GLOBALS['current_user']->id}.csv", $filename); + } + + public function testclearCacheFiles() + { + // make sure there is a file in there + file_put_contents(ImportCacheFiles::getStatusFileName(),'foo'); + + ImportCacheFiles::clearCacheFiles(); + + $this->assertFalse(is_file(ImportCacheFiles::getStatusFileName())); + } +} diff --git a/tests/modules/Import/ImportDuplicateCheckTest.php b/tests/modules/Import/ImportDuplicateCheckTest.php new file mode 100755 index 00000000..6c2ea7ec --- /dev/null +++ b/tests/modules/Import/ImportDuplicateCheckTest.php @@ -0,0 +1,117 @@ +getDuplicateCheckIndexes(); + + foreach ( $focus->getIndices() as $key => $index ) { + if ($key != 'id') $this->assertTrue(isset($indexes[$index['name']]),"{$index['name']} should be in the list"); + } + + $this->assertTrue(isset($indexes['special_idx_email1'])); + $this->assertTrue(isset($indexes['special_idx_email2'])); + } + + public function testGetDuplicateCheckIndexesNoEmail() + { + $focus = loadBean('Calls'); + + $idc = new ImportDuplicateCheck($focus); + $indexes = $idc->getDuplicateCheckIndexes(); + + foreach ( $focus->getIndices() as $key => $index ) { + if ($key != 'id') $this->assertTrue(isset($indexes[$index['name']])); + } + + $this->assertFalse(isset($indexes['special_idx_email1'])); + $this->assertFalse(isset($indexes['special_idx_email2'])); + } + + public function testIsADuplicateRecord() + { + $last_name = 'FooBar'.date("YmdHis"); + + $focus = loadBean('Contacts'); + $focus->last_name = $last_name; + $id = $focus->save(false); + + $focus = loadBean('Contacts'); + $focus->last_name = $last_name; + + $idc = new ImportDuplicateCheck($focus); + + $this->assertTrue($idc->isADuplicateRecord(array('idx_contacts_del_last'))); + + $focus->mark_deleted($id); + } + + public function testIsADuplicateRecordEmail() + { + $email = date("YmdHis").'@foobar.com'; + + $focus = loadBean('Contacts'); + $focus->email1 = $email; + $id = $focus->save(false); + + $focus = loadBean('Contacts'); + $focus->email1 = $email; + + $idc = new ImportDuplicateCheck($focus); + + $this->assertTrue($idc->isADuplicateRecord(array('special_idx_email1'))); + + $focus->mark_deleted($id); + } + + public function testIsADuplicateRecordNotFound() + { + $last_name = 'BadFooBar'.date("YmdHis"); + + $focus = loadBean('Contacts'); + $focus->last_name = $last_name; + + $idc = new ImportDuplicateCheck($focus); + + $this->assertFalse($idc->isADuplicateRecord(array('idx_contacts_del_last'))); + } + + public function testIsADuplicateRecordEmailNotFound() + { + $email = date("YmdHis").'@badfoobar.com'; + + $focus = loadBean('Contacts'); + $focus->email1 = $email; + + $idc = new ImportDuplicateCheck($focus); + + $this->assertFalse($idc->isADuplicateRecord(array('special_idx_email1'))); + } +} diff --git a/tests/modules/Import/ImportFieldSanitizeTest.php b/tests/modules/Import/ImportFieldSanitizeTest.php new file mode 100755 index 00000000..03de979b --- /dev/null +++ b/tests/modules/Import/ImportFieldSanitizeTest.php @@ -0,0 +1,1183 @@ +_ifs = new ImportFieldSanitize(); + $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']); + $GLOBALS['current_user'] = SugarTestUserUtilities::createAnonymousUser(); + $GLOBALS['timedate'] = new TimeDate(); + $beanList = array(); + require('include/modules.php'); + $GLOBALS['beanList'] = $beanList; + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + unset($GLOBALS['app_list_strings']); + unset($GLOBALS['beanList']); + $GLOBALS['timedate'] = new TimeDate(); + } + + public function testValidBool() + { + $this->assertEquals($this->_ifs->bool(0,array()),0); + $this->assertEquals($this->_ifs->bool('no',array()),0); + $this->assertEquals($this->_ifs->bool('off',array()),0); + $this->assertEquals($this->_ifs->bool('n',array()),0); + $this->assertEquals($this->_ifs->bool('yes',array()),1); + $this->assertEquals($this->_ifs->bool('y',array()),1); + $this->assertEquals($this->_ifs->bool('on',array()),1); + $this->assertEquals($this->_ifs->bool(1,array()),1); + } + + public function testValidBoolVarchar() + { + $vardefs = array('dbType' => 'varchar'); + + $this->assertEquals($this->_ifs->bool(0,$vardefs),'off'); + $this->assertEquals($this->_ifs->bool('no',$vardefs),'off'); + $this->assertEquals($this->_ifs->bool('off',$vardefs),'off'); + $this->assertEquals($this->_ifs->bool('n',$vardefs),'off'); + $this->assertEquals($this->_ifs->bool('yes',$vardefs),'on'); + $this->assertEquals($this->_ifs->bool('y',$vardefs),'on'); + $this->assertEquals($this->_ifs->bool('on',$vardefs),'on'); + $this->assertEquals($this->_ifs->bool(1,$vardefs),'on'); + } + + public function testInvalidBool() + { + $this->assertFalse($this->_ifs->bool('OK',array())); + $this->assertFalse($this->_ifs->bool('yep',array())); + } + + public function testValidCurrency() + { + $this->_ifs->dec_sep = '.'; + $this->_ifs->currency_symbol = '$'; + + $this->assertEquals($this->_ifs->currency('$100',array()),100); + } + + public function testInvalidCurrency() + { + $this->_ifs->dec_sep = '.'; + $this->_ifs->currency_symbol = '�'; + + $this->assertNotEquals($this->_ifs->currency('$123.23',array()),123.23); + } + + public function testValidDatetimeSameFormat() + { + $_SESSION[$GLOBALS['current_user']->user_name.'_PREFERENCES']['global']['timezone'] = 'America/New_York'; + + $this->_ifs->dateformat = $GLOBALS['timedate']->get_date_format(); + $this->_ifs->timeformat = $GLOBALS['timedate']->get_time_format(); + $this->_ifs->timezone = 'America/New_York'; + $vardef = array('name' => 'some_date'); + $date = date($this->_ifs->dateformat . ' ' .$this->_ifs->timeformat); + + $comparedate = date( + $GLOBALS['timedate']->get_db_date_time_format(), + strtotime( + $GLOBALS['timedate']->handle_offset( + $date, $GLOBALS['timedate']->get_date_time_format(), false, + $GLOBALS['current_user'], 'America/New_York') + ) + ); + + $this->assertEquals( + $this->_ifs->datetime( + $date, + $vardef), + $comparedate); + + unset($_SESSION[$GLOBALS['current_user']->user_name.'_PREFERENCES']['global']['timezone']); + } + + public function testValidDatetimeDifferentFormat() + { + $_SESSION[$GLOBALS['current_user']->user_name.'_PREFERENCES']['global']['timezone'] = 'America/New_York'; + + $this->_ifs->dateformat = 'm/d/Y'; + if ( $this->_ifs->dateformat == $GLOBALS['timedate']->get_date_format() ) + $this->_ifs->dateformat = 'Y/m/d'; + $this->_ifs->timeformat = 'h:ia'; + if ( $this->_ifs->timeformat == $GLOBALS['timedate']->get_time_format() ) + $this->_ifs->timeformat = 'h.ia'; + $this->_ifs->timezone = 'America/New_York'; + $vardef = array('name' => 'some_date'); + $date = date($this->_ifs->dateformat . ' ' . $this->_ifs->timeformat); + + $comparedate = date( + $GLOBALS['timedate']->get_db_date_time_format(), + strtotime( + $GLOBALS['timedate']->handle_offset( + $date, $GLOBALS['timedate']->get_date_time_format(), false, + $GLOBALS['current_user'], 'America/New_York') + )); + + $this->assertEquals( + $this->_ifs->datetime( + $date, + $vardef), + $comparedate); + + unset($_SESSION[$GLOBALS['current_user']->user_name.'_PREFERENCES']['global']['timezone']); + } + + public function testValidDatetimeDifferentTimezones() + { + $_SESSION[$GLOBALS['current_user']->user_name.'_PREFERENCES']['global']['timezone'] = 'America/New_York'; + + $this->_ifs->dateformat = $GLOBALS['timedate']->get_date_format(); + $this->_ifs->timeformat = $GLOBALS['timedate']->get_time_format(); + $format = $GLOBALS['timedate']->get_date_time_format(); + $this->_ifs->timezone = 'America/Denver'; + $vardef = array('name' => 'some_date'); + $date = date($format); + $comparedate = date( + $GLOBALS['timedate']->get_db_date_time_format(), + strtotime('+2 hours',strtotime( + $GLOBALS['timedate']->handle_offset( + $date, $GLOBALS['timedate']->get_date_time_format(), false, + $GLOBALS['current_user'], 'America/New_York') + ))); + + $this->assertEquals( + $this->_ifs->datetime( + $date, + $vardef), + $comparedate); + + unset($_SESSION[$GLOBALS['current_user']->user_name.'_PREFERENCES']['global']['timezone']); + } + + public function testValidDatetimeDateEntered() + { + $_SESSION[$GLOBALS['current_user']->id.'_PREFERENCES']['global']['timezone'] = 'Atlantic/Cape_Verde'; + + $this->_ifs->dateformat = $GLOBALS['timedate']->get_date_format(); + $this->_ifs->timeformat = $GLOBALS['timedate']->get_time_format(); + $format = $GLOBALS['timedate']->get_date_time_format(); + $this->_ifs->timezone = 'Atlantic/Cape_Verde'; + $vardef = array('name' => 'date_entered'); + $date = date($format); + $comparedate = date( + $GLOBALS['timedate']->get_db_date_time_format(), + strtotime('+1 hours',strtotime($date))); + + $this->assertEquals( + $this->_ifs->datetime( + $date, + $vardef), + $comparedate); + + unset($_SESSION[$GLOBALS['current_user']->user_name.'_PREFERENCES']['global']['timezone']); + } + + public function testValidDatetimeDateOnly() + { + $_SESSION[$GLOBALS['current_user']->user_name.'_PREFERENCES']['global']['timezone'] = 'America/New_York'; + + $this->_ifs->dateformat = $GLOBALS['timedate']->get_date_format(); + $this->_ifs->timeformat = $GLOBALS['timedate']->get_time_format(); + $format = $GLOBALS['timedate']->get_date_format(); + $this->_ifs->timezone = 'America/New_York'; + $vardef = array('name' => 'date_entered'); + $date = date($format); + $comparedate = date( + $GLOBALS['timedate']->get_db_date_time_format(), + strtotime($date)); + + $this->assertTrue( + (bool) $this->_ifs->datetime( + $date, + $vardef)); + + unset($_SESSION[$GLOBALS['current_user']->user_name.'_PREFERENCES']['global']['timezone']); + } + + public function testInvalidDatetime() + { + $this->_ifs->dateformat = 'm.d.Y'; + $this->_ifs->timeformat = 'h:ia'; + $this->_ifs->timezone = 'America/New_York'; + + $this->assertFalse( + $this->_ifs->datetime( + '11/22/2008 11:21', + array('name' => 'some_date'))); + } + + public function testInvalidDatetimeBadDayBadHour() + { + $this->_ifs->dateformat = 'm.d.Y'; + $this->_ifs->timeformat = 'h:ia'; + $this->_ifs->timezone = 'America/New_York'; + + $this->assertFalse( + $this->_ifs->datetime( + '11/40/2008 18:21', + array('name' => 'some_date'))); + } + + public function testValidDateSameFormat() + { + $this->_ifs->dateformat = $GLOBALS['timedate']->get_date_format(); + $date = date($this->_ifs->dateformat); + + $this->assertEquals( + $this->_ifs->date( + $date, + array()), + $date); + } + + public function testValidDateDifferentFormat() + { + $this->_ifs->dateformat = 'm/d/Y'; + if ( $this->_ifs->dateformat == $GLOBALS['timedate']->get_date_format() ) + $this->_ifs->dateformat = 'Y/m/d'; + $date = date($this->_ifs->dateformat ); + $comparedate = date( + $GLOBALS['timedate']->get_date_format(), + strtotime($date)); + + $this->assertEquals( + $this->_ifs->date( + $date, + array()), + $comparedate); + } + + public function testInvalidDate() + { + $this->_ifs->dateformat = 'm/d/Y'; + + $this->assertFalse( + $this->_ifs->date( + '11/22/08', + array())); + } + + public function testInvalidDateBadMonth() + { + $this->_ifs->dateformat = 'm/d/Y'; + + $this->assertFalse( + $this->_ifs->date( + '22/11/08', + array())); + } + + public function testValidEmail() + { + $this->assertEquals( + $this->_ifs->email( + 'sugas@sugarcrm.com',array()), + 'sugas@sugarcrm.com'); + } + + public function testInvalidEmail() + { + $this->assertFalse( + $this->_ifs->email( + 'sug$%$@as@sugarcrm.com',array())); + } + + public function testValidEnum() + { + $vardefs = array('options' => 'salutation_dom'); + + $this->assertEquals( + $this->_ifs->enum( + 'Mr.',$vardefs), + 'Mr.'); + } + + public function testInvalidEnum() + { + $vardefs = array('options' => 'salutation_dom'); + + $this->assertFalse( + $this->_ifs->enum( + 'Foo.',$vardefs)); + } + + /** + * @group bug23485 + */ + public function testEnumWithDisplayValue() + { + $langpack = new SugarTestLangPackCreator(); + $langpack->setAppListString('checkbox_dom',array(''=>'','1'=>'Yep','2'=>'Nada')); + $langpack->save(); + + $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']); + + $vardefs = array('options' => 'checkbox_dom'); + + $this->assertEquals( + $this->_ifs->enum( + 'Yep',$vardefs), + '1'); + } + + /** + * @group bug27467 + */ + public function testEnumWithExtraSpacesAtTheEnd() + { + $langpack = new SugarTestLangPackCreator(); + $langpack->setAppListString('checkbox_dom',array(''=>'','1'=>'Yep','2'=>'Nada')); + $langpack->save(); + + $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']); + + $vardefs = array('options' => 'checkbox_dom'); + + $this->assertEquals( + $this->_ifs->enum( + ' 1 ',$vardefs), + '1'); + } + + /** + * @group bug33328 + */ + public function testEnumWithKeyInDifferentCase() + { + $langpack = new SugarTestLangPackCreator(); + $langpack->setAppListString('gender_list',array('male' => 'Male','female' => 'Female',)); + $langpack->save(); + + $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']); + + $vardefs = array('options' => 'gender_list'); + + $this->assertEquals( + $this->_ifs->enum( + 'MALE',$vardefs), + 'male'); + } + + /** + * @group bug33328 + */ + public function testEnumWithValueInDifferentCase() + { + $langpack = new SugarTestLangPackCreator(); + $langpack->setAppListString('checkbox_dom',array(''=>'','1'=>'Yep','2'=>'Nada')); + $langpack->save(); + + $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']); + + $vardefs = array('options' => 'checkbox_dom'); + + $this->assertEquals( + $this->_ifs->enum( + 'YEP',$vardefs), + '1'); + } + + public function testValidId() + { + $this->assertEquals( + $this->_ifs->id( + '1234567890',array()), + '1234567890'); + } + + public function testInvalidId() + { + $this->assertFalse( + $this->_ifs->id( + '1234567890123456789012345678901234567890',array())); + } + + public function testValidInt() + { + $this->assertEquals($this->_ifs->int('100',array()),100); + + $this->_ifs->num_grp_sep = ','; + + $this->assertEquals($this->_ifs->int('1,123',array()),1123); + } + + public function testInvalidInt() + { + $this->_ifs->num_grp_sep = '.'; + $this->assertFalse($this->_ifs->int('123,23',array())); + $this->_ifs->num_grp_sep = ','; + $this->assertFalse($this->_ifs->int('123.23',array())); + } + + public function testValidFloat() + { + $this->_ifs->dec_sep = '.'; + + $this->assertEquals($this->_ifs->currency('100',array()),100); + $this->assertEquals($this->_ifs->currency('123.23',array()),123.23); + + $this->_ifs->dec_sep = ','; + + $this->assertEquals($this->_ifs->currency('123,23',array()),123.23); + + $this->_ifs->num_grp_sep = ','; + + $this->assertEquals($this->_ifs->currency('1,123.23',array()),1123.23); + } + + public function testInvalidFloat() + { + $this->_ifs->dec_sep = '.'; + + $this->assertNotEquals($this->_ifs->currency('123,23',array()),123.23); + } + + public function testValidFullname() + { + $this->_ifs->default_locale_name_format = 'l f'; + + $focus = loadBean('Contacts'); + + $this->_ifs->fullname('Bar Foo',array(),$focus); + + $this->assertEquals($focus->first_name,'Foo'); + $this->assertEquals($focus->last_name,'Bar'); + } + + public function testInvalidFullname() + { + $this->_ifs->default_locale_name_format = 'f l'; + + $focus = loadBean('Contacts'); + + $this->_ifs->fullname('Bar Foo',array(),$focus); + + $this->assertNotEquals($focus->first_name,'Foo'); + $this->assertNotEquals($focus->last_name,'Bar'); + } + + public function testValidMultiEnum() + { + $vardefs = array('options' => 'salutation_dom'); + + $this->assertEquals( + $this->_ifs->multienum( + 'Mr.,Mrs.',$vardefs), + encodeMultienumValue(array('Mr.', 'Mrs.'))); + $this->assertEquals( + $this->_ifs->multienum( + '^Mr.^,^Mrs.^',$vardefs), + encodeMultienumValue(array('Mr.', 'Mrs.'))); + } + + /** + * @ticket 37842 + */ + public function testValidMultiEnumWhenSpacesExistInTheValue() + { + $vardefs = array('options' => 'salutation_dom'); + + $this->assertEquals( + $this->_ifs->multienum( + 'Mr., Mrs.',$vardefs), + encodeMultienumValue(array('Mr.', 'Mrs.'))); + } + + public function testInvalidMultiEnum() + { + $vardefs = array('options' => 'salutation_dom'); + + $this->assertFalse( + $this->_ifs->multienum( + 'Mr.,foo.',$vardefs)); + } + + public function testValidName() + { + $this->assertEquals( + $this->_ifs->name( + '1234567890',array('len' => 12)), + '1234567890'); + } + + public function testInvalidName() + { + $this->assertEquals( + $this->_ifs->name( + '1234567890123456789012345678901234567890',array('len' => 12)), + '123456789012'); + } + + public function testParent() + { + $account_name = 'test case account'.date("YmdHis"); + $focus = loadBean('Accounts'); + $focus->name = $account_name; + $focus->save(); + $account_id = $focus->id; + + $focus = loadBean('Contacts'); + $vardef = array( + 'required' => false, + 'source' => 'non-db', + 'name' => 'parent_name', + 'vname' => 'LBL_FLEX_RELATE', + 'type' => 'parent', + 'massupdate' => 0, + 'comments' => '', + 'help' => '', + 'importable' => 'false', + 'duplicate_merge' => 'disabled', + 'duplicate_merge_dom_value' => '0', + 'audited' => 0, + 'reportable' => 0, + 'len' => 25, + 'options' => 'parent_type_display', + 'studio' => 'visible', + 'type_name' => 'parent_type', + 'id_name' => 'parent_id', + 'parent_type' => 'record_type_display', + ); + $focus->parent_name = ''; + $focus->parent_id = ''; + $focus->parent_type = 'Accounts'; + + $this->_ifs->parent( + $account_name, + $vardef, + $focus); + + $this->assertEquals($focus->parent_id,$account_id); + + $GLOBALS['db']->query("DELETE FROM accounts where id = '$account_id'"); + } + + public function testRelate() + { + $account_name = 'test case account'.date("YmdHis"); + $focus = loadBean('Accounts'); + $focus->name = $account_name; + $focus->save(); + $account_id = $focus->id; + + $focus = loadBean('Contacts'); + $vardef = array ( + 'name' => 'account_name', + 'rname' => 'name', + 'id_name' => 'account_id', + 'vname' => 'LBL_ACCOUNT_NAME', + 'join_name'=>'accounts', + 'type' => 'relate', + 'link' => 'accounts', + 'table' => 'accounts', + 'isnull' => 'true', + 'module' => 'Accounts', + 'dbType' => 'varchar', + 'len' => '255', + 'source' => 'non-db', + 'unified_search' => true, + ); + + $this->_ifs->relate( + $account_name, + $vardef, + $focus); + + $this->assertEquals($focus->account_id,$account_id); + + $GLOBALS['db']->query("DELETE FROM accounts where id = '$account_id'"); + } + + public function testRelateCreateRecord() + { + $account_name = 'test case account'.date("YmdHis"); + + $focus = loadBean('Contacts'); + $vardef = array ( + 'name' => 'account_name', + 'rname' => 'name', + 'id_name' => 'account_id', + 'vname' => 'LBL_ACCOUNT_NAME', + 'join_name'=>'accounts', + 'type' => 'relate', + 'link' => 'accounts', + 'table' => 'accounts', + 'isnull' => 'true', + 'module' => 'Accounts', + 'dbType' => 'varchar', + 'len' => '255', + 'source' => 'non-db', + 'unified_search' => true, + ); + + // setup + $beanList = array(); + require('include/modules.php'); + $GLOBALS['beanList'] = $beanList; + + $this->_ifs->relate( + $account_name, + $vardef, + $focus); + + // teardown + unset($GLOBALS['beanList']); + + $result = $GLOBALS['db']->query( + "SELECT id FROM accounts where name = '$account_name'"); + $relaterow = $focus->db->fetchByAssoc($result); + + $this->assertEquals($focus->account_id,$relaterow['id']); + + $GLOBALS['db']->query("DELETE FROM accounts where id = '{$relaterow['id']}'"); + } + + /** + * @group bug38356 + */ + public function testRelateCreateRecordNoTableInVardef() + { + $account_name = 'test case account'.date("YmdHis"); + + $focus = loadBean('Contacts'); + $vardef = array ( + 'name' => 'account_name', + 'rname' => 'name', + 'id_name' => 'account_id', + 'vname' => 'LBL_ACCOUNT_NAME', + 'join_name'=>'accounts', + 'type' => 'relate', + 'link' => 'accounts', + 'isnull' => 'true', + 'module' => 'Accounts', + 'dbType' => 'varchar', + 'len' => '255', + 'source' => 'non-db', + 'unified_search' => true, + ); + + // setup + $beanList = array(); + require('include/modules.php'); + $GLOBALS['beanList'] = $beanList; + + $this->_ifs->relate( + $account_name, + $vardef, + $focus); + + // teardown + unset($GLOBALS['beanList']); + + $result = $GLOBALS['db']->query( + "SELECT id FROM accounts where name = '$account_name'"); + $relaterow = $focus->db->fetchByAssoc($result); + + $this->assertEquals($focus->account_id,$relaterow['id']); + + $GLOBALS['db']->query("DELETE FROM accounts where id = '{$relaterow['id']}'"); + } + + /** + * @group bug32869 + */ + public function testRelateCreateRecordIfNoRnameParameter() + { + $account_name = 'test case account'.date("YmdHis"); + + $focus = loadBean('Contacts'); + $vardef = array ( + 'name' => 'account_name', + 'id_name' => 'account_id', + 'vname' => 'LBL_ACCOUNT_NAME', + 'join_name'=>'accounts', + 'type' => 'relate', + 'link' => 'accounts', + 'table' => 'accounts', + 'isnull' => 'true', + 'module' => 'Accounts', + 'dbType' => 'varchar', + 'len' => '255', + 'source' => 'non-db', + 'unified_search' => true, + ); + + // setup + $beanList = array(); + require('include/modules.php'); + $GLOBALS['beanList'] = $beanList; + + $this->_ifs->relate( + $account_name, + $vardef, + $focus); + + // teardown + unset($GLOBALS['beanList']); + + $result = $GLOBALS['db']->query( + "SELECT id FROM accounts where name = '$account_name'"); + $relaterow = $focus->db->fetchByAssoc($result); + + $this->assertEquals($focus->account_id,$relaterow['id']); + + $GLOBALS['db']->query("DELETE FROM accounts where id = '{$relaterow['id']}'"); + } + + /** + * @group bug26897 + */ + public function testRelateCreateRecordCheckACL() + { + $account_name = 'test case account '.date("YmdHis"); + + $focus = new Import_Bug26897_Mock; + $vardef = array ( + 'name' => 'account_name', + 'rname' => 'name', + 'id_name' => 'account_id', + 'vname' => 'LBL_CATEGORY_NAME', + 'join_name'=>'accounts', + 'type' => 'relate', + 'link' => 'accounts_link', + 'table' => 'accounts', + 'isnull' => 'true', + 'module' => 'Import_Bug26897_Mock', + 'dbType' => 'varchar', + 'len' => '255', + 'source' => 'non-db', + ); + + // setup + $beanList = array(); + require('include/modules.php'); + $beanList['Import_Bug26897_Mock'] = 'Import_Bug26897_Mock'; + $beanFiles['Import_Bug26897_Mock'] = 'modules/Accounts/Account.php'; + $GLOBALS['beanList'] = $beanList; + $GLOBALS['beanFiles'] = $beanFiles; + + $this->_ifs->relate( + $account_name, + $vardef, + $focus); + + // teardown + unset($GLOBALS['beanList']); + unset($GLOBALS['beanFiles']); + + $result = $GLOBALS['db']->query( + "SELECT id FROM accounts where name = '$account_name'"); + $relaterow = $focus->db->fetchByAssoc($result); + + $this->assertTrue(empty($focus->account_id),'Category ID should not be set'); + $this->assertNull($relaterow,'Record should not be added to the related table'); + + $GLOBALS['db']->query("DELETE FROM accounts where id = '{$relaterow['id']}'"); + } + + /** + * @group bug33704 + */ + public function testRelateDoNotCreateRecordIfRelatedModuleIsUsers() + { + $account_name = 'test case account'.date("YmdHis"); + $focus = new User; + $vardef = array ( + 'name' => 'account_name', + 'rname' => 'name', + 'id_name' => 'category_id', + 'vname' => 'LBL_CATEGORY_NAME', + 'join_name'=>'accounts', + 'type' => 'relate', + 'link' => 'account_link', + 'table' => 'users', + 'isnull' => 'true', + 'module' => 'Users', + 'dbType' => 'varchar', + 'len' => '255', + 'source' => 'non-db', + ); + + $this->_ifs->relate( + $account_name, + $vardef, + $focus); + + // teardown + unset($GLOBALS['beanList']); + unset($GLOBALS['beanFiles']); + + $result = $GLOBALS['db']->query( + "SELECT id FROM accounts where name = '$account_name'"); + $relaterow = $focus->db->fetchByAssoc($result); + + $this->assertTrue(empty($focus->account_id),'Category ID should not be set'); + $this->assertNull($relaterow,'Record should not be added to the related table'); + + $GLOBALS['db']->query("DELETE FROM accounts where id = '{$relaterow['id']}'"); + } + + /** + * @group bug38885 + */ + public function testRelateToUserNameWhenFullNameIsGiven() + { + // setup + $beanList = array(); + require('include/modules.php'); + $GLOBALS['beanList'] = $beanList; + $GLOBALS['beanFiles'] = $beanFiles; + + $accountFocus = new Account; + $userFocus = SugarTestUserUtilities::createAnonymousUser(); + $vardef = array( + "name" => "assigned_user_name", + "link" => "assigned_user_link", + "vname" => "LBL_ASSIGNED_TO_NAME", + "rname" => "user_name", + "type" => "relate", + "reportable" => false, + "source" => "non-db", + "table" => "users", + "id_name" => "assigned_user_id", + "module" => "Users", + "duplicate_merge" => "disabled", + ); + + $this->assertEquals( + $userFocus->user_name, + $this->_ifs->relate( + $userFocus->first_name.' '.$userFocus->last_name, + $vardef, + $accountFocus, + false) + ); + + // teardown + unset($GLOBALS['beanList']); + unset($GLOBALS['beanFiles']); + } + + /** + * @group bug27562 + */ + public function testRelateCreateRecordUsingMultipleFieldToLinkRecords() + { + $contact_name = 'testcase contact'.date("YmdHis"); + + $focus = new Import_Bug27562_Mock; + + $vardef = array ( + 'name' => 'contact_name', + 'rname' => 'name', + 'id_name' => 'contact_id', + 'vname' => 'LBL_CATEGORY_NAME', + 'join_name'=>'contacts', + 'type' => 'relate', + 'link' => 'contact_link', + 'table' => 'contacts', + 'isnull' => 'true', + 'module' => 'Import_Bug27562_Mock', + 'dbType' => 'varchar', + 'len' => '255', + 'source' => 'non-db', + ); + + // setup + $beanList = array(); + require('include/modules.php'); + $beanList['Import_Bug27562_Mock'] = 'Import_Bug27562_Mock'; + $beanFiles['Import_Bug27562_Mock'] = 'modules/Contacts/Contact.php'; + $GLOBALS['beanList'] = $beanList; + $GLOBALS['beanFiles'] = $beanFiles; + + $this->_ifs->relate( + $contact_name, + $vardef, + $focus); + + // teardown + unset($GLOBALS['beanList']); + unset($GLOBALS['beanFiles']); + + $nameParts = explode(' ',$contact_name); + $result = $GLOBALS['db']->query( + "SELECT id FROM contacts where first_name = '{$nameParts[0]}' and last_name = '{$nameParts[1]}'"); + $relaterow = $focus->db->fetchByAssoc($result); + + $this->assertEquals($focus->contact_id,$relaterow['id']); + + $GLOBALS['db']->query("DELETE FROM contacts where id = '{$relaterow['id']}'"); + } + + public function testRelateDontCreateRecord() + { + $account_name = 'test case account'.date("YmdHis"); + + $focus = loadBean('Contacts'); + $vardef = array ( + 'name' => 'account_name', + 'rname' => 'name', + 'id_name' => 'account_id', + 'vname' => 'LBL_ACCOUNT_NAME', + 'join_name'=>'accounts', + 'type' => 'relate', + 'link' => 'accounts', + 'table' => 'accounts', + 'isnull' => 'true', + 'module' => 'Accounts', + 'dbType' => 'varchar', + 'len' => '255', + 'source' => 'non-db', + 'unified_search' => true, + ); + + // setup + $beanList = array(); + require('include/modules.php'); + $GLOBALS['beanList'] = $beanList; + + $this->assertFalse( + $this->_ifs->relate( + $account_name, + $vardef, + $focus, + false), + 'Should return false since record could not be found' + ); + + // teardown + unset($GLOBALS['beanList']); + + $result = $GLOBALS['db']->query( + "SELECT id FROM accounts where name = '$account_name'"); + $relaterow = $focus->db->fetchByAssoc($result); + $this->assertNull($relaterow,'Record should not have been created'); + if ( $relaterow ) + $GLOBALS['db']->query("DELETE FROM accounts where id = '{$relaterow['id']}'"); + } + + /** + * @group bug27046 + */ + public function testRelateWithInvalidDataFormatting() + { + $langpack = new SugarTestLangPackCreator(); + $langpack->setAppListString('checkbox_dom',array(''=>'','1'=>'Yep','2'=>'Nada')); + $langpack->save(); + + $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']); + + $account_name = 'test case category'.date("YmdHis"); + + $focus = new Import_Bug27046_Mock; + $vardef = array ( + 'name' => 'account_name', + 'rname' => 'name', + 'id_name' => 'account_id', + 'vname' => 'LBL_ACCOUNT_NAME', + 'join_name'=>'accounts', + 'type' => 'relate', + 'link' => 'accounts_link', + 'table' => 'accounts', + 'isnull' => 'true', + 'module' => 'Import_Bug27046_Mock', + 'dbType' => 'varchar', + 'len' => '255', + 'source' => 'non-db', + 'rtype' => 'int', + ); + + // setup + $beanList = array(); + require('include/modules.php'); + $beanList['Import_Bug27046_Mock'] = 'Import_Bug27046_Mock'; + $beanFiles['Import_Bug27046_Mock'] = 'modules/Accounts/Account.php'; + $GLOBALS['beanList'] = $beanList; + $GLOBALS['beanFiles'] = $beanFiles; + + $this->assertFalse( + $this->_ifs->relate( + $account_name, + $vardef, + $focus), + 'Should return false since field format is invalid' + ); + + // teardown + unset($GLOBALS['beanList']); + + $result = $GLOBALS['db']->query( + "SELECT id FROM accounts where name = '$account_name'"); + $relaterow = $focus->db->fetchByAssoc($result); + $this->assertNull($relaterow,'Record should not have been created'); + if ( $relaterow ) + $GLOBALS['db']->query("DELETE FROM accounts where id = '{$relaterow['id']}'"); + } + + public function testValidSyncToOutlookUser() + { + $value = $GLOBALS['current_user']->id . ',' . $GLOBALS['current_user']->user_name; + $bad_names = array(); + + $this->assertTrue( + (bool) $this->_ifs->synctooutlook( + $value, + array(), + $bad_names + ), + 'Test $this->_ifs->synctooutlook() not returning false'); + + $this->assertEquals($bad_names,array()); + } + public function testInvalidSyncToOutlook() + { + $value = "jghu8h8yhuh8hhi889898898"; + $bad_names = array(); + + $this->assertFalse( + $this->_ifs->synctooutlook( + $value, + array(), + $bad_names + ), + 'Test $this->_ifs->synctooutlook() should return false'); + } + + public function testValidTimeSameFormat() + { + $_SESSION[$GLOBALS['current_user']->user_name.'_PREFERENCES']['global']['timezone'] = 'America/New_York'; + + $this->_ifs->timeformat = $GLOBALS['timedate']->get_time_format(); + $this->_ifs->timezone = 'America/New_York'; + $vardef = array('name' => 'some_date'); + $date = date($this->_ifs->timeformat); + + $this->assertEquals( + $this->_ifs->time( + $date, + $vardef), + $date); + + unset($_SESSION[$GLOBALS['current_user']->user_name.'_PREFERENCES']['global']['timezone']); + } + + public function testValidTimeDifferentFormat() + { + $_SESSION[$GLOBALS['current_user']->user_name.'_PREFERENCES']['global']['timezone'] = 'America/New_York'; + + $this->_ifs->timeformat = 'h:ia'; + if ( $this->_ifs->timeformat == $GLOBALS['timedate']->get_time_format() ) + $this->_ifs->timeformat = 'h.ia'; + $this->_ifs->timezone = 'America/New_York'; + $vardef = array('name' => 'some_date'); + + $date = date($this->_ifs->timeformat); + $comparedate = date( + $GLOBALS['timedate']->get_time_format(), + strtotime($date)); + + $this->assertEquals( + $this->_ifs->time( + $date, + $vardef), + $comparedate); + + unset($_SESSION[$GLOBALS['current_user']->user_name.'_PREFERENCES']['global']['timezone']); + } + + public function testValidTimeDifferentTimezones() + { + $_SESSION[$GLOBALS['current_user']->user_name.'_PREFERENCES']['global']['timezone'] = 'America/New_York'; + + $this->_ifs->timeformat = $GLOBALS['timedate']->get_time_format(); + $this->_ifs->timezone = 'America/Denver'; + $vardef = array('name' => 'some_date'); + $date = date($this->_ifs->timeformat); + $comparedate = date( + $GLOBALS['timedate']->get_time_format(), + strtotime('+2 hours',strtotime($date))); + + $this->assertEquals( + $this->_ifs->time( + $date, + $vardef), + $comparedate); + + unset($_SESSION[$GLOBALS['current_user']->user_name.'_PREFERENCES']['global']['timezone']); + } + + public function testInvalidTime() + { + $this->_ifs->timeformat = 'h:ia'; + $this->_ifs->timezone = 'America/New_York'; + + $this->assertFalse( + $this->_ifs->time( + '11:21', + array('name' => 'some_date'))); + } + + public function testInvalidTimeBadSeconds() + { + $this->_ifs->timeformat = 'h:ia'; + $this->_ifs->timezone = 'America/New_York'; + + $this->assertFalse( + $this->_ifs->time( + '11:60', + array('name' => 'some_date'))); + } +} + +class Import_Bug26897_Mock extends Account +{ + function ACLAccess($view,$is_owner='not_set') + { + return false; + } + + function bean_implements($interface) + { + return true; + } +} + +class Import_Bug27562_Mock extends Contact +{ + function ACLAccess($view,$is_owner='not_set') + { + return true; + } +} + +class Import_Bug27046_Mock extends Account +{ + function ACLAccess($view,$is_owner='not_set') + { + return false; + } + + function bean_implements($interface) + { + return true; + } + + function getFieldDefintion($name) + { + return array( + 'name' => 'name', + 'type' => 'int', + ); + } +} diff --git a/tests/modules/Import/ImportFileSplitterTest.php b/tests/modules/Import/ImportFileSplitterTest.php new file mode 100755 index 00000000..b18d1d42 --- /dev/null +++ b/tests/modules/Import/ImportFileSplitterTest.php @@ -0,0 +1,98 @@ +_goodFile = SugarTestImportUtilities::createFile(); + $this->_badFile = $GLOBALS['sugar_config']['import_dir'].'thisfileisntthere'.date("YmdHis"); + $this->_whiteSpaceFile = SugarTestImportUtilities::createFileWithWhiteSpace(); + } + + public function tearDown() + { + SugarTestImportUtilities::removeAllCreatedFiles(); + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + } + + public function testLoadNonExistantFile() + { + $importFileSplitter = new ImportFileSplitter($this->_badFile); + $this->assertFalse($importFileSplitter->fileExists()); + } + + public function testLoadGoodFile() + { + $importFileSplitter = new ImportFileSplitter($this->_goodFile); + $this->assertTrue($importFileSplitter->fileExists()); + } + + public function testSplitSourceFile() + { + $importFileSplitter = new ImportFileSplitter($this->_goodFile); + $importFileSplitter->splitSourceFile(',','"'); + + $this->assertEquals($importFileSplitter->getRecordCount(),2000); + $this->assertEquals($importFileSplitter->getFileCount(),2); + } + + public function testSplitSourceFileNoEnclosure() + { + $importFileSplitter = new ImportFileSplitter($this->_goodFile); + $importFileSplitter->splitSourceFile(',',''); + + $this->assertEquals($importFileSplitter->getRecordCount(),2000); + $this->assertEquals($importFileSplitter->getFileCount(),2); + } + + public function testSplitSourceFileWithHeader() + { + $importFileSplitter = new ImportFileSplitter($this->_goodFile); + $importFileSplitter->splitSourceFile(',','"',true); + + $this->assertEquals($importFileSplitter->getRecordCount(),1999); + $this->assertEquals($importFileSplitter->getFileCount(),2); + } + + public function testSplitSourceFileWithThreshold() + { + $importFileSplitter = new ImportFileSplitter($this->_goodFile,500); + $importFileSplitter->splitSourceFile(',','"'); + + $this->assertEquals($importFileSplitter->getRecordCount(),2000); + $this->assertEquals($importFileSplitter->getFileCount(),4); + } + + public function testGetSplitFileName() + { + $importFileSplitter = new ImportFileSplitter($this->_goodFile); + $importFileSplitter->splitSourceFile(',','"'); + + $this->assertEquals($importFileSplitter->getSplitFileName(0),"{$this->_goodFile}-0"); + $this->assertEquals($importFileSplitter->getSplitFileName(1),"{$this->_goodFile}-1"); + $this->assertEquals($importFileSplitter->getSplitFileName(2),false); + } + + /** + * @group bug25119 + */ + public function testTrimSpaces() + { + $splitter = new ImportFileSplitter($this->_whiteSpaceFile); + $splitter->splitSourceFile(',',' ',false); + + $csvString = file_get_contents("{$this->_whiteSpaceFile}-0"); + + $this->assertEquals( + trim(file_get_contents("{$this->_whiteSpaceFile}-0")), + trim(file_get_contents("{$this->_whiteSpaceFile}")) + ); + } +} diff --git a/tests/modules/Import/ImportFileTest.php b/tests/modules/Import/ImportFileTest.php new file mode 100755 index 00000000..1b672a12 --- /dev/null +++ b/tests/modules/Import/ImportFileTest.php @@ -0,0 +1,263 @@ +getNextRow(); + $this->assertEquals($row, array('foo00')); + $row = $importFile->getNextRow(); + $this->assertEquals($row,array('foo10')); + } + + public function testLoadNonExistantFile() + { + $importFile = new ImportFile($GLOBALS['sugar_config']['import_dir'].'/thisfileisntthere'.date("YmdHis").'.csv',',','"'); + $this->assertFalse($importFile->fileExists()); + } + + public function testLoadGoodFile() + { + $file = SugarTestImportUtilities::createFile(2,1); + $importFile = new ImportFile($file,',','"'); + $this->assertTrue($importFile->fileExists()); + } + + /** + * @ticket 39494 + */ + public function testLoadFileWithByteOrderMark() + { + $importFile = new ImportFile('tests/modules/Import/Bug39494ImportFile.txt',"\t",'',false); + $this->assertTrue($importFile->fileExists()); + $row = $importFile->getNextRow(); + $this->assertEquals($row,array('name','city')); + $row = $importFile->getNextRow(); + $this->assertEquals($row,array('tester1','wuhan')); + } + + public function testGetNextRow() + { + $file = SugarTestImportUtilities::createFile(3,2); + $importFile = new ImportFile($file,',','"'); + + $row = $importFile->getNextRow(); + $this->assertEquals(array("foo00","foo01"),$row); + $row = $importFile->getNextRow(); + $this->assertEquals(array("foo10","foo11"),$row); + $row = $importFile->getNextRow(); + $this->assertEquals(array("foo20","foo21"),$row); + } + + public function testLoadEmptyFile() + { + $emptyFile = $GLOBALS['sugar_config']['import_dir'].'/empty'.date("YmdHis").'.csv'; + file_put_contents($emptyFile,''); + + $importFile = new ImportFile($emptyFile,',','"',false); + + $this->assertFalse($importFile->getNextRow()); + + $importFile = new ImportFile($emptyFile,',','',false); + + $this->assertFalse($importFile->getNextRow()); + + @unlink($emptyFile); + } + + public function testDeleteFileOnDestroy() + { + $file = SugarTestImportUtilities::createFile(3,2); + $importFile = new ImportFile($file,',','"',true); + + unset($importFile); + + $this->assertFalse(is_file($file)); + } + + public function testNotDeleteFileOnDestroy() + { + $file = SugarTestImportUtilities::createFile(3,2); + $importFile = new ImportFile($file,',','"',false); + + unset($importFile); + + $this->assertTrue(is_file($file)); + } + + public function testGetFieldCount() + { + $file = SugarTestImportUtilities::createFile(3,2); + $importFile = new ImportFile($file,',','"'); + + $importFile->getNextRow(); + $this->assertEquals($importFile->getFieldCount(),2); + } + + public function testMarkRowAsDuplicate() + { + $file = SugarTestImportUtilities::createFile(3,2); + $importFile = new ImportFile($file,',','"'); + + $row = $importFile->getNextRow(); + $importFile->markRowAsDuplicate(); + + $fp = sugar_fopen(ImportCacheFiles::getDuplicateFileName(),'r'); + $duperow = fgetcsv($fp); + fclose($fp); + + $this->assertEquals($row,$duperow); + } + + public function testWriteError() + { + $file = SugarTestImportUtilities::createFile(3,2); + $importFile = new ImportFile($file,',','"'); + + $row = $importFile->getNextRow(); + $importFile->writeError('Some Error','field1','foo'); + + $fp = sugar_fopen(ImportCacheFiles::getErrorFileName(),'r'); + $errorrow = fgetcsv($fp); + fclose($fp); + + $this->assertEquals(array('Some Error','field1','foo',1),$errorrow); + + $fp = sugar_fopen(ImportCacheFiles::getErrorRecordsFileName(),'r'); + $errorrecordrow = fgetcsv($fp); + fclose($fp); + + $this->assertEquals($row,$errorrecordrow); + } + + public function testWriteErrorRecord() + { + $file = SugarTestImportUtilities::createFile(3,2); + $importFile = new ImportFile($file,',','"'); + + $row = $importFile->getNextRow(); + $importFile->writeErrorRecord(); + + $fp = sugar_fopen(ImportCacheFiles::getErrorRecordsFileName(),'r'); + $errorrecordrow = fgetcsv($fp); + fclose($fp); + + $this->assertEquals($row,$errorrecordrow); + } + + public function testWriteStatus() + { + $file = SugarTestImportUtilities::createFile(3,2); + $importFile = new ImportFile($file,',','"'); + + $importFile->getNextRow(); + $importFile->writeError('Some Error','field1','foo'); + $importFile->getNextRow(); + $importFile->markRowAsDuplicate(); + $importFile->getNextRow(); + $importFile->markRowAsImported(); + $importFile->writeStatus(); + + $fp = sugar_fopen(ImportCacheFiles::getStatusFileName(),'r'); + $statusrow = fgetcsv($fp); + fclose($fp); + + $this->assertEquals(array(3,1,1,1,0,$file),$statusrow); + } + + public function testWriteStatusWithTwoErrorsInOneRow() + { + $file = SugarTestImportUtilities::createFile(3,2); + $importFile = new ImportFile($file,',','"'); + + $row = $importFile->getNextRow(); + $importFile->writeError('Some Error','field1','foo'); + $importFile->writeError('Some Error','field1','foo'); + $importFile->getNextRow(); + $importFile->markRowAsImported(); + $importFile->getNextRow(); + $importFile->markRowAsImported(); + $importFile->writeStatus(); + + $fp = sugar_fopen(ImportCacheFiles::getStatusFileName(),'r'); + $statusrow = fgetcsv($fp); + fclose($fp); + + $this->assertEquals(array(3,1,0,2,0,$file),$statusrow); + + $fp = sugar_fopen(ImportCacheFiles::getErrorRecordsFileName(),'r'); + $errorrecordrow = fgetcsv($fp); + + $this->assertEquals($row,$errorrecordrow); + $this->assertFalse(fgetcsv($fp),'Should be only 1 record in the csv file'); + fclose($fp); + + } + + public function testWriteStatusWithTwoUpdatedRecords() + { + $file = SugarTestImportUtilities::createFile(3,2); + $importFile = new ImportFile($file,',','"'); + + $row = $importFile->getNextRow(); + $importFile->markRowAsImported(false); + $importFile->getNextRow(); + $importFile->markRowAsImported(); + $importFile->getNextRow(); + $importFile->markRowAsImported(); + $importFile->writeStatus(); + + $fp = sugar_fopen(ImportCacheFiles::getStatusFileName(),'r'); + $statusrow = fgetcsv($fp); + fclose($fp); + + $this->assertEquals(array(3,0,0,2,1,$file),$statusrow); + } + + public function testWriteRowToLastImport() + { + $file = SugarTestImportUtilities::createFile(3,2); + $importFile = new ImportFile($file,',','"'); + $record = $importFile->writeRowToLastImport("Tests","Test","TestRunner"); + + $query = "SELECT * + FROM users_last_import + WHERE assigned_user_id = '{$GLOBALS['current_user']->id}' + AND import_module = 'Tests' + AND bean_type = 'Test' + AND bean_id = 'TestRunner' + AND id = '$record' + AND deleted=0"; + + $result = $GLOBALS['db']->query($query); + + $this->assertNotNull($GLOBALS['db']->fetchByAssoc($result)); + + $query = "DELETE FROM users_last_import + WHERE assigned_user_id = '{$GLOBALS['current_user']->id}' + AND import_module = 'Tests' + AND bean_type = 'Test' + AND bean_id = 'TestRunner' + AND id = '$record' + AND deleted=0"; + $GLOBALS['db']->query($query); + } +} diff --git a/tests/modules/Import/ImportFormsTest.php b/tests/modules/Import/ImportFormsTest.php new file mode 100755 index 00000000..f05dadc5 --- /dev/null +++ b/tests/modules/Import/ImportFormsTest.php @@ -0,0 +1,177 @@ +is_admin; + $GLOBALS['current_user']->is_admin = '1'; + + $focus = loadImportBean('Accounts'); + + $this->assertEquals($focus->object_name, 'Account'); + + $GLOBALS['current_user']->is_admin = $oldisadmin; + } + + public function testLoadImportBeanNotImportable() + { + $this->assertFalse(loadImportBean('vCals')); + } + + public function testLoadImportBeanUserNotAdmin() + { + $this->assertFalse(loadImportBean('Users')); + } + + public function testShowImportError() + { + ob_start(); + showImportError('Error Message','ErrorModule','ErrorAction'); + $output = ob_get_clean(); + + $this->assertRegExp('/

Error Message<\/p>/',$output); + $this->assertRegExp('//',$output); + $this->assertRegExp('//',$output); + } + + public function testHandleImportErrors() + { + $old_error_reporting = error_reporting(E_ALL); + + $errors = array( + array(E_USER_WARNING,'sample E_USER_WARNING','test12.php',4), + array(E_WARNING,'sample E_WARNING','test4.php',2232), + array(E_USER_NOTICE,'sample E_USER_NOTICE','test8.php',932), + array(E_NOTICE,'sample E_NOTICE','12test.php',39), + array(E_STRICT,'sample E_STRICT','t12est.php',42), + array(12121212121,'sample unknown error','te43st.php',334), + ); + + foreach ( $errors as $error ) { + list($errno, $errstr, $errfile, $errline) = $error; + + ob_start(); + handleImportErrors($errno, $errstr, $errfile, $errline); + $output = ob_get_clean(); + $output = trim($output); + + switch ($errno) { + case E_USER_WARNING: + case E_WARNING: + //$this->assertEquals("WARNING: [$errno] $errstr on line $errline in file $errfile
",$output); + break; + case E_USER_NOTICE: + case E_NOTICE: + //$this->assertEquals("NOTICE: [$errno] $errstr on line $errline in file $errfile
",$output); + break; + case E_STRICT: + //$this->assertEquals('',$output); + break; + default: + $this->assertEquals( + "Unknown error type: [$errno] $errstr on line $errline in file $errfile
",$output); + break; + } + } + + error_reporting($old_error_reporting); + } + + public function testGetControlIdField() + { + $html = getControl('Contacts','assigned_user_id'); + + $this->assertRegExp('/name=\'assigned_user_id\'/',$html); + $this->assertRegExp('/id=\'assigned_user_id\'/',$html); + $this->assertRegExp('/type=\'text\'/',$html); + } + + public function testGetControlEmail() + { + $html = getControl('Contacts','email1'); + + $this->assertRegExp('/name=\'email1\'/',$html); + $this->assertRegExp('/id=\'email1\'/',$html); + $this->assertRegExp('/type=\'text\'/',$html); + } + + public function testGetControlCurrencyList() + { + global $app_strings; + + $html = getControl('Opportunities','currency_id'); + + $focus = loadBean('Opportunities'); + + require_once('modules/Opportunities/Opportunity.php'); + + $string = str_ireplace('','',getCurrencyDropDown($focus, 'currency_id', '', 'EditView')); + $this->assertContains($string,$html,"Failed to find string '$string' in '$html'"); + + $string = ""; + $this->assertContains($string,$html,"Failed to find string '$string' in '$html'"); + } + + public function testGetControlVardef() + { + VardefManager::loadVardef( + 'Contacts', + 'Contact'); + $vardef = $GLOBALS['dictionary']['Contact']['fields']['assigned_user_id']; + + $html = getControl('Contacts','assigned_user_id',$vardef); + + $this->assertRegExp('/name=\'assigned_user_id\'/',$html); + $this->assertRegExp('/id=\'assigned_user_id\'/',$html); + $this->assertRegExp('/type=\'text\'/',$html); + } + + public function testGetControlValue() + { + $html = getControl('Contacts','email1',null,'poo'); + + $this->assertRegExp('/name=\'email1\'/',$html); + $this->assertRegExp('/id=\'email1\'/',$html); + $this->assertRegExp('/type=\'text\'/',$html); + $this->assertRegExp('/value=\'poo\'/',$html); + } + + /** + * @group bug41447 + */ + public function testGetControlDatetimecombo() + { + $html = getControl('Calls','date_start'); + + global $timedate; + $string = '", "' . $timedate->get_user_time_format() . '", "'; + + $this->assertContains($string, $html); + } +} diff --git a/tests/modules/Import/ImportMapTest.php b/tests/modules/Import/ImportMapTest.php new file mode 100755 index 00000000..076a56ae --- /dev/null +++ b/tests/modules/Import/ImportMapTest.php @@ -0,0 +1,281 @@ +is_admin = '1'; + $this->_importMap = new ImportMap(); + } + + public function tearDown() + { + unset($GLOBALS['beanList']); + unset($GLOBALS['beanFiles']); + $GLOBALS['db']->query( + 'DELETE FROM import_maps + WHERE assigned_user_id IN (\'' . + implode("','",SugarTestUserUtilities::getCreatedUserIds()) . '\')'); + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + } + + private function _addMapping( + $name = 'test mapping for importmaptest', + $enclosure = '"' + ) + { + $this->_importMap->save( + $GLOBALS['current_user']->id, + $name, + 'TEST', + 'other', + '1', + ',', + $enclosure); + } + + public function testSave() + { + $this->_addMapping(); + $query = "SELECT * FROM import_maps + WHERE assigned_user_id = '{$GLOBALS['current_user']->id}' + AND name = 'test mapping' + AND module = 'TEST' + AND source = 'other' + AND has_header = '1' + AND delimiter = ',' + AND enclosure = '\"'"; + + $result = $GLOBALS['db']->query($query); + + $this->assertNull($GLOBALS['db']->fetchByAssoc($result),'Row not added'); + } + + public function testSaveEmptyEnclosure() + { + $this->_addMapping('test mapping',''); + $query = "SELECT * FROM import_maps + WHERE assigned_user_id = '{$GLOBALS['current_user']->id}' + AND name = 'test mapping' + AND module = 'TEST' + AND source = 'other' + AND has_header = '1' + AND delimiter = ',' + AND enclosure = ' '"; + + $result = $GLOBALS['db']->query($query); + + $this->assertNotNull($GLOBALS['db']->fetchByAssoc($result),'Row not added'); + } + + public function testSetAndGetMapping() + { + $mapping = array( + 'field1' => 'value1', + 'field2' => 'value2', + ); + + $this->_importMap->setMapping($mapping); + $this->_addMapping(); + $id = $this->_importMap->id; + + $importMapRetrieve = new ImportMap(); + $importMapRetrieve->retrieve($id, false); + + $this->assertEquals($importMapRetrieve->getMapping(),$mapping); + } + + public function testSetAndGetDefaultFields() + { + $mapping = array( + 'field1' => 'value1', + 'field2' => 'value2', + ); + + $this->_importMap->setDefaultValues($mapping); + $this->_addMapping(); + $id = $this->_importMap->id; + + $importMapRetrieve = new ImportMap(); + $importMapRetrieve->retrieve($id, false); + + $this->assertEquals($importMapRetrieve->getDefaultValues(),$mapping); + } + + public function testMarkPublished() + { + $this->_addMapping(); + $this->assertTrue($this->_importMap->mark_published( + $GLOBALS['current_user']->id,true)); + $id = $this->_importMap->id; + + $query = "SELECT * FROM import_maps + WHERE id = '$id'"; + + $result = $GLOBALS['db']->query($query); + + $row = $GLOBALS['db']->fetchByAssoc($result); + + $this->assertEquals($row['is_published'],'yes'); + } + + public function testMarkPublishedNameConflict() + { + $this->_addMapping(); + $this->_importMap->mark_published( + $GLOBALS['current_user']->id,true); + + $GLOBALS['current_user'] = SugarTestUserUtilities::createAnonymousUser(); + $this->_importMap = new ImportMap(); + $this->_addMapping(); + $this->assertFalse($this->_importMap->mark_published( + $GLOBALS['current_user']->id,true)); + + $query = "SELECT * FROM import_maps + WHERE id = '{$this->_importMap->id}'"; + + $result = $GLOBALS['db']->query($query); + + $row = $GLOBALS['db']->fetchByAssoc($result); + + $this->assertEquals($row['is_published'],'no'); + } + + public function testMarkPublishedNameNotAdmin() + { + $GLOBALS['current_user']->is_admin = '0'; + + $this->_addMapping(); + $this->assertFalse($this->_importMap->mark_published( + $GLOBALS['current_user']->id,true)); + } + + public function testMarkUnpublished() + { + $this->_addMapping(); + $this->_importMap->mark_published( + $GLOBALS['current_user']->id,true); + $id = $this->_importMap->id; + + $importMapRetrieve = new ImportMap(); + $importMapRetrieve->retrieve($id, false); + $this->assertTrue($this->_importMap->mark_published( + $GLOBALS['current_user']->id,false)); + + $query = "SELECT * FROM import_maps + WHERE id = '$id'"; + + $result = $GLOBALS['db']->query($query); + + $row = $GLOBALS['db']->fetchByAssoc($result); + + $this->assertEquals($row['is_published'],'no'); + } + + public function testMarkUnpublishedNameConflict() + { + $this->_addMapping(); + $this->_importMap->mark_published( + $GLOBALS['current_user']->id,true); + $id = $this->_importMap->id; + + $GLOBALS['current_user'] = SugarTestUserUtilities::createAnonymousUser(); + $this->_importMap = new ImportMap(); + $this->_addMapping(); + + $importMapRetrieve = new ImportMap(); + $importMapRetrieve->retrieve($id, false); + $this->assertFalse($this->_importMap->mark_published( + $GLOBALS['current_user']->id,false)); + + $query = "SELECT * FROM import_maps + WHERE id = '$id'"; + + $result = $GLOBALS['db']->query($query); + + $row = $GLOBALS['db']->fetchByAssoc($result); + + $this->assertEquals($row['is_published'],'yes'); + } + + public function testMarkDeleted() + { + $this->_addMapping(); + $id = $this->_importMap->id; + + $this->_importMap = new ImportMap(); + $this->_importMap->mark_deleted($id); + + $query = "SELECT * FROM import_maps + WHERE id = '$id'"; + + $result = $GLOBALS['db']->query($query); + + $row = $GLOBALS['db']->fetchByAssoc($result); + + $this->assertEquals($row['deleted'],'1'); + } + + public function testMarkDeletedAdminDifferentUser() + { + $this->_addMapping(); + $id = $this->_importMap->id; + + $GLOBALS['current_user'] = SugarTestUserUtilities::createAnonymousUser(); + $GLOBALS['current_user']->is_admin = '1'; + $this->_importMap = new ImportMap(); + $this->_importMap->mark_deleted($id); + + $query = "SELECT * FROM import_maps + WHERE id = '$id'"; + + $result = $GLOBALS['db']->query($query); + + $row = $GLOBALS['db']->fetchByAssoc($result); + + $this->assertEquals($row['deleted'],'1'); + } + + public function testMarkDeletedNotAdminDifferentUser() + { + $this->_addMapping(); + $id = $this->_importMap->id; + + $GLOBALS['current_user'] = SugarTestUserUtilities::createAnonymousUser(); + $GLOBALS['current_user']->is_admin = '0'; + $this->_importMap = new ImportMap(); + $this->assertFalse($this->_importMap->mark_deleted($id),'Record should not be allowed to be deleted'); + } + + public function testRetrieveAllByStringFields() + { + $this->_addMapping(); + $this->_importMap = new ImportMap(); + $this->_addMapping('test mapping 2'); + $this->_importMap = new ImportMap(); + $this->_addMapping('test mapping 3'); + + $objarr = $this->_importMap->retrieve_all_by_string_fields( + array('assigned_user_id' => $GLOBALS['current_user']->id) + ); + + $this->assertEquals(count($objarr),3); + + $this->assertEquals($objarr[0]->assigned_user_id, + $GLOBALS['current_user']->id); + $this->assertEquals($objarr[1]->assigned_user_id, + $GLOBALS['current_user']->id); + $this->assertEquals($objarr[2]->assigned_user_id, + $GLOBALS['current_user']->id); + } +} diff --git a/tests/modules/Import/UsersLastImportTest.php b/tests/modules/Import/UsersLastImportTest.php new file mode 100755 index 00000000..b8e678e2 --- /dev/null +++ b/tests/modules/Import/UsersLastImportTest.php @@ -0,0 +1,173 @@ +_importModule = 'Notes'; + $this->_importObject = 'Note'; + $this->_importRecordCount = 3; + $this->_importIds = array(); + $this->_usersLastImport = new UsersLastImport(); + $this->_addImportedRecords(); + } + + public function tearDown() + { + $focus = $this->_loadBean($this->_importModule); + $GLOBALS['db']->query( + 'DELETE FROM ' . $focus->table_name . ' + WHERE id IN (\'' . + implode("','",$this->_importIds) . '\')'); + $GLOBALS['db']->query( + 'DELETE FROM users_last_import + WHERE id IN (\'' . + implode("','",$this->_usersLastImportIds) . '\')'); + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + unset($GLOBALS['beanList']); + unset($GLOBALS['beanFiles']); + } + + private function _loadBean() + { + return loadBean($this->_importModule); + } + + private function _addImportedRecords() + { + for ( $i = 0; $i < $this->_importRecordCount; $i++ ) { + $focus = $this->_loadBean($this->_importModule); + $focus->name = "record $i"; + $focus->save(); + $this->_importIds[$i] = $focus->id; + + $last_import = new UsersLastImport(); + $last_import->assigned_user_id = $GLOBALS['current_user']->id; + $last_import->import_module = $this->_importModule; + $last_import->bean_type = $this->_importObject; + $last_import->bean_id = $this->_importIds[$i]; + $this->_usersLastImportIds[] = $last_import->save(); + } + } + + public function testMarkDeletedByUserId() + { + $this->_usersLastImport->mark_deleted_by_user_id($GLOBALS['current_user']->id); + + $query = "SELECT * FROM users_last_import + WHERE assigned_user_id = '{$GLOBALS['current_user']->id}'"; + + $result = $GLOBALS['db']->query($query); + + $this->assertNull($GLOBALS['db']->fetchByAssoc($result),'There should not be any records in the table now'); + } + + public function testUndo() + { + $this->assertTrue( + $this->_usersLastImport->undo( + $this->_importModule + ) + ); + + $focus = $this->_loadBean($this->_importModule); + + $query = "SELECT * FROM {$focus->table_name} + WHERE id IN ('" . + implode("','",$this->_importIds) . "')"; + + $result = $GLOBALS['db']->query($query); + + $this->assertNull($GLOBALS['db']->fetchByAssoc($result),'There should not be any records in the table now'); + } + + /** + * @group bug21828 + */ + public function testUndoRemovedAddedEmailAddresses() + { + $time = date('Y-m-d H:i:s'); + $unid = uniqid(); + + $focus = new Account(); + $focus->id = "Account_".$unid; + + $last_import = new UsersLastImport(); + $last_import->assigned_user_id = $GLOBALS['current_user']->id; + $last_import->import_module = 'Accounts'; + $last_import->bean_type = 'Account'; + $last_import->bean_id = $focus->id; + $last_import->save(); + + $this->email_addr_bean_rel_id = 'email_addr_bean_rel_'.$unid; + $this->email_address_id = 'email_address_id_'.$unid; + $GLOBALS['db']->query("insert into email_addr_bean_rel (id , email_address_id, bean_id, bean_module, primary_address, date_created , date_modified) values ('{$this->email_addr_bean_rel_id}', '{$this->email_address_id}', '{$focus->id}', 'Accounts', 1, '$time', '$time')"); + + $GLOBALS['db']->query("insert into email_addresses (id , email_address, email_address_caps, date_created, date_modified) values ('{$this->email_address_id}', 'test@g.com', 'TEST@G.COM', '$time', '$time')"); + + // setup + require('include/modules.php'); + $GLOBALS['beanList'] = $beanList; + $GLOBALS['beanFiles'] = $beanFiles; + + $this->assertTrue( + $last_import->undo( + $last_import->import_module + ) + ); + + // teardown + unset($GLOBALS['beanList']); + unset($GLOBALS['beanFiles']); + + $result = $GLOBALS['db']->query("SELECT * FROM email_addr_bean_rel where id = '{$this->email_addr_bean_rel_id}'"); + $rows = $GLOBALS['db']->fetchByAssoc($result); + $this->assertNull($rows); + + $result = $GLOBALS['db']->query("SELECT * FROM email_addresses where id = '{$this->email_address_id}'"); + $rows = $GLOBALS['db']->fetchByAssoc($result); + $this->assertNull($rows); + + $GLOBALS['db']->query("DELETE FROM users_last_import WHERE id = '{$last_import->id}'"); + } + + public function testUndoById() + { + $this->assertTrue( + $this->_usersLastImport->undoById( + $this->_usersLastImportIds[0] + ) + ); + + $focus = $this->_loadBean($this->_importModule); + + $query = "SELECT * FROM {$focus->table_name} + WHERE id = '{$this->_importIds[0]}'"; + + $result = $GLOBALS['db']->query($query); + + $this->assertNull($GLOBALS['db']->fetchByAssoc($result),'There should not be any records in the table now'); + + } + + public function testGetBeansByImport() + { + foreach ( UsersLastImport::getBeansByImport('Notes') as $objectName ) + $this->assertEquals($objectName,'Note'); + } +} diff --git a/tests/modules/InboundEmail/AutoCreateImportFolderTest.php b/tests/modules/InboundEmail/AutoCreateImportFolderTest.php new file mode 100755 index 00000000..4d32161b --- /dev/null +++ b/tests/modules/InboundEmail/AutoCreateImportFolderTest.php @@ -0,0 +1,52 @@ +_user = SugarTestUserUtilities::createAnonymousUser(); + $GLOBALS['current_user'] = $this->_user; + + $this->folder = new SugarFolder(); + $this->ie = new InboundEmail(); + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + + $GLOBALS['db']->query("DELETE FROM folders WHERE id='{$this->folder_id}'"); + + unset($this->ie); + } + + function testAutoImportFolderCreation(){ + global $current_user; + + $this->ie->name = "Sugar Test"; + $this->folder_id = $this->ie->createAutoImportSugarFolder(); + $this->folder_obj = new SugarFolder(); + $this->folder_obj->retrieve($this->folder_id); + + $this->assertEquals($this->ie->name, $this->folder_obj->name, "Could not create folder for Inbound Email auto folder creation" ); + $this->assertEquals(0, $this->folder_obj->has_child, "Could not create folder for Inbound Email auto folder creation" ); + $this->assertEquals(1, $this->folder_obj->is_group, "Could not create folder for Inbound Email auto folder creation" ); + $this->assertEquals($this->_user->id, $this->folder_obj->assign_to_id, "Could not create folder for Inbound Email auto folder creation" ); + + } +} +?> \ No newline at end of file diff --git a/tests/modules/InboundEmail/InboundEmailTest.php b/tests/modules/InboundEmail/InboundEmailTest.php new file mode 100755 index 00000000..ba897f90 --- /dev/null +++ b/tests/modules/InboundEmail/InboundEmailTest.php @@ -0,0 +1,162 @@ +markTestSkipped('Connection to mail server is down.'); + + if (empty($inbound_account_id)) { + $this->_setupTestUser(); + $this->_createInboundAccount(); + } // IF + } + + function _createInboundAccount() { + global $inbound_account_id, $current_user; + $stored_options = array(); + $stored_options['from_name'] = "UnitTest"; + $stored_options['from_addr'] = "ajaysales@sugarcrm.com"; + $stored_options['reply_to_name'] = "UnitTest"; + $stored_options['reply_to_addr'] = "ajaysales@sugarcrm.com"; + $stored_options['only_since'] = false; + $stored_options['filter_domain'] = ""; + $stored_options['trashFolder'] = "INBOX.Trash"; + $stored_options['leaveMessagesOnMailServer'] = 1; + + $useSsl = false; + $focus = new InboundEmail(); + $focus->name = "Ajay Sales Personal Unittest"; + $focus->email_user = "ajaysales@sugarcrm.com"; + $focus->email_password = "f00f004"; + $focus->server_url = "mail.sugarcrm.com"; + $focus->protocol = "imap"; + $focus->mailbox = "INBOX"; + $focus->port = "143"; + + $optimum = $focus->findOptimumSettings($useSsl); + + $focus->service = $optimum['serial']; + $focus->is_personal = 1; + $focus->status = "Active"; + $focus->mailbox_type = 'pick'; + $focus->group_id = $current_user->id; + $teamId = User::getPrivateTeam($current_user->id); + $focus->team_id = $teamId; + $focus->team_set_id = $focus->getTeamSetIdForTeams($teamId); + $focus->stored_options = base64_encode(serialize($stored_options)); + $inbound_account_id = $focus->save(); + } // fn + + /** + * retrieve an inbound account. + * + */ + function _retrieveInboundAccount() { + global $inbound_account_id; + $focus = new InboundEmail(); + $focus->retrieve($inbound_account_id); + $result = $focus->connectMailserver(); + if ( $result == 'false' ) + $this->markTestSkipped('Connection to mail server is down.'); + return $focus; + } // fn + + /** + * Create a folder in inbound account. + * + */ + function testCreateFolder() { + $focus = $this->_retrieveInboundAccount(); + $status = $focus->saveNewFolder("unittest1", "INBOX"); + $this->assertTrue($status,"INBOX.unittest1 can not be created = " . $status); + } // fn + + /** + * Delete a folder in inbound account. + * + */ + function testDeleteFolder() { + global $inbound_account_id; + $focus = $this->_retrieveInboundAccount(); + $statusArray = $focus->deleteFolder("INBOX.unittest1"); + if ($statusArray['status']) { + $this->_tearDownInboundAccount($inbound_account_id); + unset($inbound_account_id); + } + $this->assertTrue($statusArray['status'],"INBOX.unittest1 can not be deleted"); + } + + public function testIdWithSingleQuotesCanBeInsertedIntoCacheTable() + { + $focus = new InboundEmail(); + $focus->id = create_guid(); + $focus->setCacheTimestamp("John's House"); + + $r = $focus->db->getOne('select id from inbound_email_cache_ts where id = \''. + $focus->db->quote("{$focus->id}_John's House").'\''); + + $this->assertTrue($r !== false,"Could not find id \"{$focus->id}_John's House\" in inbound_email_cache_ts"); + + $focus->db->query('delete from inbound_email_cache_ts where id = \''. + $focus->db->quote("{$focus->id}_John's House").'\''); + } + + /** + * Remove anything that was used during this test + * + */ + function tearDown() { + global $inbound_account_id; + $this->_tearDownTestUser(); + } + + /** + * Delete this inbound account. + * + */ + function _tearDownInboundAccount($inbound_account_id) { + $focus = new InboundEmail(); + $focus->retrieve($inbound_account_id); + $focus->mark_deleted($inbound_account_id); + $focus->db->query("delete from inbound_email WHERE id = '{$inbound_account_id}'"); + } + + /** + * Create a test user + * + */ + function _setupTestUser() { + global $current_user; + $this->_user = SugarTestUserUtilities::createAnonymousUser(); + $GLOBALS['current_user'] = $this->_user; + $current_user = $this->_user; + $this->_user->status = 'Active'; + $this->_user->is_admin = 1; + $this->_user->save(); + } + + /** + * Remove user created for test + * + */ + function _tearDownTestUser() { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + } + +} +?> \ No newline at end of file diff --git a/tests/modules/Leads/ConvertLeadTests.php b/tests/modules/Leads/ConvertLeadTests.php new file mode 100755 index 00000000..f927b8cf --- /dev/null +++ b/tests/modules/Leads/ConvertLeadTests.php @@ -0,0 +1,63 @@ +opportunity_name = 'SBizzle Dollar Store'; + $lead->save(); + + $_REQUEST['module'] = 'Leads'; + $_REQUEST['action'] = 'ConvertLead'; + $_REQUEST['record'] = $lead->id; + + // Check that the opportunity name doesn't get populated when it's not in the Leads editview layout + require_once('include/MVC/Controller/ControllerFactory.php'); + require_once('include/MVC/View/ViewFactory.php'); + $GLOBALS['app']->controller = ControllerFactory::getController($_REQUEST['module']); + ob_start(); + $GLOBALS['app']->controller->execute(); + $output = ob_get_clean(); + + $matches_one = array(); + $pattern = '/SBizzle Dollar Store/'; + preg_match($pattern, $output, $matches_one); + $this->assertTrue(count($matches_one) == 0, "Opportunity name got carried over to the Convert Leads page when it shouldn't have."); + + // Add the opportunity_name to the Leads EditView + SugarTestStudioUtilities::addFieldToLayout('Leads', 'editview', 'opportunity_name'); + + // Check that the opportunity name now DOES get populated now that it's in the Leads editview layout + ob_start(); + $GLOBALS['app']->controller = ControllerFactory::getController($_REQUEST['module']); + $GLOBALS['app']->controller->execute(); + $output = ob_get_clean(); + $matches_two = array(); + $pattern = '/SBizzle Dollar Store/'; + preg_match($pattern, $output, $matches_two); + $this->assertTrue(count($matches_two) > 0, "Opportunity name did not carry over to the Convert Leads page when it should have."); + + SugarTestStudioUtilities::removeAllCreatedFields(); + unset($GLOBALS['app']->controller); + unset($_REQUEST['module']); + unset($_REQUEST['action']); + unset($_REQUEST['record']); + SugarTestLeadUtilities::removeAllCreatedLeads(); + } +} \ No newline at end of file diff --git a/tests/modules/ModuleBuilder/Module/StudioModuleTest.php b/tests/modules/ModuleBuilder/Module/StudioModuleTest.php new file mode 100755 index 00000000..7f902d40 --- /dev/null +++ b/tests/modules/ModuleBuilder/Module/StudioModuleTest.php @@ -0,0 +1,39 @@ +removeFieldFromLayouts("aFieldThatDoesntExist"); + $this->assertTrue(true); + } catch (Exception $e) + { + $this->assertTrue(false, "Studio module threw exception :" . $e->getMessage()); + } + } +} \ No newline at end of file diff --git a/tests/modules/ModuleBuilder/parsers/AbstractMetaDataParserTest.php b/tests/modules/ModuleBuilder/parsers/AbstractMetaDataParserTest.php new file mode 100755 index 00000000..4440223a --- /dev/null +++ b/tests/modules/ModuleBuilder/parsers/AbstractMetaDataParserTest.php @@ -0,0 +1,58 @@ + 'status', + 'vname' => 'LBL_STATUS', + 'type' => 'enum', + 'len' => '25', + 'options' => 'meeting_status_dom', + 'comment' => 'Meeting status (ex: Planned, Held, Not held)' + ); + + $invalidDef = array ( + 'name' => 'direction', + 'vname' => 'LBL_DIRECTION', + 'type' => 'enum', + 'len' => '25', + 'options' => 'call_direction_dom', + 'comment' => 'Indicates whether call is inbound or outbound', + 'source' => 'non-db', + 'importable' => 'false', + 'massupdate'=>false, + 'reportable'=>false + ); + + $this->assertTrue(AbstractMetaDataParser::validField($validDef)); + $this->assertFalse(AbstractMetaDataParser::validField($invalidDef)); + + //Test the studio override property + $invalidDef['studio'] = 'visible'; + $validDef['studio'] = false; + + $this->assertFalse(AbstractMetaDataParser::validField($validDef)); + $this->assertTrue(AbstractMetaDataParser::validField($invalidDef)); + + $invalidDef['studio'] = array('editview' => 'visible'); + + $this->assertTrue(AbstractMetaDataParser::validField($invalidDef, 'editview')); + $this->assertFalse(AbstractMetaDataParser::validField($invalidDef, 'detailview')); + } + +} \ No newline at end of file diff --git a/tests/modules/ModuleBuilder/views/ViewListVIewTest.php b/tests/modules/ModuleBuilder/views/ViewListVIewTest.php new file mode 100755 index 00000000..d2e80fe8 --- /dev/null +++ b/tests/modules/ModuleBuilder/views/ViewListVIewTest.php @@ -0,0 +1,38 @@ + "1", + "sugar_body_only"=>"1", + "module"=>"ModuleBuilder", + "view_package"=>"", + "view_module"=>"KBDocuments", + "view"=>"listview", + ); + $view = new ViewListView(); + $ajax = $view->constructAjax(); + $this->assertNotNull($ajax); + } + +} \ No newline at end of file diff --git a/tests/modules/MySettings/StoreQueryTest.php b/tests/modules/MySettings/StoreQueryTest.php new file mode 100755 index 00000000..beb9b496 --- /dev/null +++ b/tests/modules/MySettings/StoreQueryTest.php @@ -0,0 +1,20 @@ +assertTrue(empty($query), "StoreQuery::getStoredQueryForUser is not empty."); + } +} +?> \ No newline at end of file diff --git a/tests/modules/Notes/NotesTest.php b/tests/modules/Notes/NotesTest.php new file mode 100755 index 00000000..db78773d --- /dev/null +++ b/tests/modules/Notes/NotesTest.php @@ -0,0 +1,41 @@ +first_name = "Josh"; + $contact->last_name = "Chi"; + $contact->salutation = "Mr"; + $contact->title = 'VP Operations'; + $contact->disable_row_level_security = true; + $contact_id = $contact->save(); + + $note = new Note(); + $note->contact_id = $contact_id; + $note->disable_row_level_security = true; + $note->fill_in_additional_detail_fields(); + + $this->assertContains($contact->first_name,$note->contact_name); + $this->assertContains($contact->last_name,$note->contact_name); + + $GLOBALS['db']->query('DELETE FROM contacts WHERE id =\''.$contact_id.'\''); + } +} diff --git a/tests/modules/Tasks/TasksTest.php b/tests/modules/Tasks/TasksTest.php new file mode 100755 index 00000000..086f0694 --- /dev/null +++ b/tests/modules/Tasks/TasksTest.php @@ -0,0 +1,29 @@ +name = "New Task"; + $task->date_due = $GLOBALS['timedate']->to_display_date_time("2010-08-30 15:00:00"); + $listViewFields = $task->get_list_view_data(); + + $this->assertEquals($listViewFields['TIME_DUE'], $GLOBALS['timedate']->to_display_time("15:00:00")); + } +} diff --git a/tests/modules/Trackers/Bug40019_Test.php b/tests/modules/Trackers/Bug40019_Test.php new file mode 100755 index 00000000..a15013bf --- /dev/null +++ b/tests/modules/Trackers/Bug40019_Test.php @@ -0,0 +1,110 @@ +anonymous_user = SugarTestUserUtilities::createAnonymousUser(); + if(!empty($GLOBALS['current_user'])) + { + $this->saved_current_user = $GLOBALS['current_user']; + } + $GLOBALS['current_user'] = $this->anonymous_user; + + $i = 0; + while($i++ < 10) + { + $account = SugarTestAccountUtilities::createAccount(); + $contact = SugarTestContactUtilities::createContact(); + + $trackerManager = TrackerManager::getInstance(); + $trackerManager->unPause(); + if($monitor = $trackerManager->getMonitor('tracker')) { + $monitor->setEnabled(true); + + $monitor->setValue('date_modified', gmdate($GLOBALS['timedate']->get_db_date_time_format())); + $monitor->setValue('user_id', $GLOBALS['current_user']->id); + $monitor->setValue('module_name', $account->module_dir); + $monitor->setValue('action', 'detailview'); + $monitor->setValue('item_id', $account->id); + $monitor->setValue('item_summary', $account->name); + $monitor->setValue('visible',1); + $trackerManager->saveMonitor($monitor, true, true); + + $monitor = $trackerManager->getMonitor('tracker'); + $monitor->setValue('date_modified', gmdate($GLOBALS['timedate']->get_db_date_time_format())); + $monitor->setValue('user_id', $GLOBALS['current_user']->id); + $monitor->setValue('module_name', $contact->module_dir); + $monitor->setValue('action', 'detailview'); + $monitor->setValue('item_id', $contact->id); + $monitor->setValue('item_summary', $contact->name); + $monitor->setValue('visible',1); + $trackerManager->saveMonitor($monitor, true, true); + } + } + } + + public function tearDown() + { + $GLOBALS['db']->query("DELETE FROM tracker WHERE user_id = '{$this->anonymous_user->id}'"); + SugarTestAccountUtilities::removeAllCreatedAccounts(); + SugarTestContactUtilities::removeAllCreatedContacts(); + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + if(!empty($this->saved_current_user)) + { + $GLOBALS['current_user'] = $this->saved_current_user; + } + + + } + + public function testBreadCrumbStack() + { + $GLOBALS['sugar_config']['history_max_viewed'] = 50; + $breadCrumbStack = new BreadCrumbStack($GLOBALS['current_user']->id); + $list = $breadCrumbStack->getBreadCrumbList('Accounts'); + $this->assertEquals(count($list), 10, 'Assert that there are 10 entries for Accounts module'); + + $list = $breadCrumbStack->getBreadCrumbList('Contacts'); + $this->assertEquals(count($list), 10, 'Assert that there are 10 entries for Contacts module'); + + /* + $GLOBALS['sugar_config']['history_max_viewed'] = 10; + $breadCrumbStack = new BreadCrumbStack($GLOBALS['current_user']->id); + $list = $breadCrumbStack->getBreadCrumbList(array('Accounts', 'Contacts')); + $contacts = 0; + $accounts = 0; + foreach($list as $list_entry) + { + switch ($list_entry['module_name']) + { + case 'Contacts': + $contacts++; + break; + case 'Accounts': + $accounts++; + break; + } + } + + $this->assertEquals($contacts, 5, 'Assert there are 5 entries found for Contacts using array filter of Contacts & Accounts'); + $this->assertEquals($accounts, 5, 'Assert there are 5 entries found for Accounts using array filter of Contacts & Accounts'); + */ + } + +} + +?> \ No newline at end of file diff --git a/tests/modules/Trackers/TrackerCreateDefaultUserTest.php b/tests/modules/Trackers/TrackerCreateDefaultUserTest.php new file mode 100755 index 00000000..3a622a91 --- /dev/null +++ b/tests/modules/Trackers/TrackerCreateDefaultUserTest.php @@ -0,0 +1,100 @@ +skipTest) { + $this->markTestSkipped("Skipping unless otherwise specified"); + } + + $user = new User(); + $user->retrieve('1'); + $GLOBALS['current_user'] = $user; + + TrackerTestUtility::setUp(); + $_SESSION['reports_getACLAllowedModules'] = null; + $this->nonAdminUser = new User(); + $this->nonAdminUser->first_name = 'non'; + $this->nonAdminUser->last_name = 'admin'; + $this->nonAdminUser->user_name = 'nonadmin'; + $this->nonAdminUserId = $this->nonAdminUser->save(); + + $this->adminUser = new User(); + $this->adminUser->is_admin = true; + $this->adminUser->first_name = 'admin'; + $this->adminUser->last_name = 'test'; + $this->adminUser->user_name = 'admintest'; + $this->adminUserId = $this->adminUser->save(); + + global $beanFiles, $beanList, $moduleList, $modListHeader, $sugar_config; + require('config.php'); + require('include/modules.php'); + $modListHeader = $moduleList; + } + + function tearDown() { + TrackerTestUtility::tearDown(); + $GLOBALS['db']->query("DELETE FROM users WHERE id IN ('{$this->adminUser->id}', '{$this->nonAdminUser->id}')"); + $GLOBALS['db']->query("DELETE FROM team_memberships WHERE user_id IN ('{$this->adminUser->id}', '{$this->nonAdminUser->id}')"); + $GLOBALS['db']->query("DELETE FROM acl_roles_users WHERE user_id IN ('{$this->adminUser->id}', '{$this->nonAdminUser->id}')");; + + $user = new User(); + $user->retrieve('1'); + $GLOBALS['current_user'] = $user; + } + + function test_disabled_create_non_admin_user() { + global $current_user; + $current_user = $this->nonAdminUser; + require_once('modules/Reports/SavedReport.php'); + $allowedModules = getACLAllowedModules(); + $this->assertTrue(empty($allowedModules['Trackers'])); + $this->assertTrue(empty($allowedModules['TrackerSessions'])); + $this->assertTrue(empty($allowedModules['TrackerPerfs'])); + $this->assertTrue(empty($allowedModules['TrackerQueries'])); + } + + function test_disabled_create_admin_user() { + global $current_user; + $current_user = $this->adminUser; + + require_once('modules/Reports/SavedReport.php'); + $allowedModules = getACLAllowedModules(); + $this->assertTrue(!empty($allowedModules['Trackers'])); + $this->assertTrue(!empty($allowedModules['TrackerSessions'])); + $this->assertTrue(!empty($allowedModules['TrackerPerfs'])); + $this->assertTrue(!empty($allowedModules['TrackerQueries'])); + } + + + function test_disabled_non_admin_user_given_tracker_role() { + global $current_user; + $current_user = $this->nonAdminUser; + $result = $GLOBALS['db']->query("SELECT id FROM acl_roles where name='Tracker'"); + $trackerRoleId = $GLOBALS['db']->fetchByAssoc($result); + if(!empty($trackerRoleId['id'])) { + require_once('modules/ACLRoles/ACLRole.php'); + $role1= new ACLRole(); + $role1->retrieve($trackerRoleId['id']); + $role1->set_relationship('acl_roles_users', array('role_id'=>$role1->id ,'user_id'=>$this->nonAdminUserId), false); + } + + require_once('modules/Reports/SavedReport.php'); + $allowedModules = getACLAllowedModules(); + $this->assertTrue(!empty($allowedModules['Trackers'])); + $this->assertTrue(!empty($allowedModules['TrackerSessions'])); + $this->assertTrue(!empty($allowedModules['TrackerPerfs'])); + $this->assertTrue(!empty($allowedModules['TrackerQueries'])); + } + +} + +?> \ No newline at end of file diff --git a/tests/modules/Trackers/TrackerManagerTest.php b/tests/modules/Trackers/TrackerManagerTest.php new file mode 100755 index 00000000..029877f2 --- /dev/null +++ b/tests/modules/Trackers/TrackerManagerTest.php @@ -0,0 +1,61 @@ +retrieve('1'); + $GLOBALS['current_user'] = $user; + } + + function tearDown() + { + $trackerManager = TrackerManager::getInstance(); + $trackerManager->unPause(); + + $user = new User(); + $user->retrieve('1'); + $GLOBALS['current_user'] = $user; + } + + function testPausing() { + $trackerManager = TrackerManager::getInstance(); + $trackerManager->unPause(); + $this->assertFalse($trackerManager->isPaused()); + $trackerManager->pause(); + $this->assertTrue($trackerManager->isPaused()); + } + + function testPausing2() { + $query = "select count(id) as total from tracker"; + $result = $GLOBALS['db']->query($query); + $count1 = 0; + while($row = $GLOBALS['db']->fetchByAssoc($result)){ + $count1 = $row['total']; + } + + $trackerManager = TrackerManager::getInstance(); + $trackerManager->pause(); + + $monitor = $trackerManager->getMonitor('tracker'); + $monitor->setValue('module_name', 'Contacts'); + $monitor->setValue('item_id', '10909d69-2b55-094d-ba89-47b23d3121dd'); + $monitor->setValue('item_summary', 'Foo'); + $monitor->setValue('date_modified', gmdate($GLOBALS['timedate']->get_db_date_time_format()), strtotime("-1 day")+5000); + $monitor->setValue('action', 'index'); + $monitor->setValue('session_id', 'test_session'); + $monitor->setValue('user_id', 1); + $trackerManager->save(); + + $count2 = 0; + $query = "select count(id) as total from tracker"; + $result = $GLOBALS['db']->query($query); + while($row = $GLOBALS['db']->fetchByAssoc($result)){ + $count2 = $row['total']; + } + $this->assertEquals($count1, $count2); + } + + +} +?> \ No newline at end of file diff --git a/tests/modules/Trackers/TrackerMetricsTest.php b/tests/modules/Trackers/TrackerMetricsTest.php new file mode 100755 index 00000000..9a505da5 --- /dev/null +++ b/tests/modules/Trackers/TrackerMetricsTest.php @@ -0,0 +1,31 @@ +getMonitor('tracker'); + $metrics = $monitor->getMetrics(); + foreach($metrics as $metric) { + if($metric->name() == 'monitor_id') { + $this->assertFalse($metric->isMutable(), "Test that {$metric->name()} is not mutable"); + } else { + $this->assertTrue($metric->isMutable(), "Test that {$metric->name()} is mutable"); + } + } + } + +} +?> \ No newline at end of file diff --git a/tests/modules/Trackers/TrackerMonitorTest.php b/tests/modules/Trackers/TrackerMonitorTest.php new file mode 100755 index 00000000..5685a6c3 --- /dev/null +++ b/tests/modules/Trackers/TrackerMonitorTest.php @@ -0,0 +1,49 @@ +unsetMonitors(); + } + + function tearDown() { + + } + + function testValidMonitors() { + $trackerManager = TrackerManager::getInstance(); + $exceptionThrown = false; + try { + $monitor = $trackerManager->getMonitor('tracker'); + $monitor2 = $trackerManager->getMonitor('tracker_queries'); + $monitor3 = $trackerManager->getMonitor('tracker_perf'); + $monitor4 = $trackerManager->getMonitor('tracker_sessions'); + $monitor5 = $trackerManager->getMonitor('tracker_tracker_queries'); + } catch (Exception $ex) { + $exceptionThrown = true; + } + $this->assertFalse($exceptionThrown); + } + + function testInvalidMonitors() { + $trackerManager = TrackerManager::getInstance(); + $exceptionThrown = false; + $monitor = $trackerManager->getMonitor('invalid_tracker'); + $this->assertTrue(get_class($monitor) == 'BlankMonitor'); + } + + function testInvalidValue() { + $trackerManager = TrackerManager::getInstance(); + $monitor = $trackerManager->getMonitor('tracker'); + $exceptionThrown = false; + try { + $monitor->setValue('invalid_column', 'foo'); + } catch (Exception $exception) { + $exceptionThrown = true; + } + $this->assertTrue($exceptionThrown); + } + +} +?> \ No newline at end of file diff --git a/tests/modules/Trackers/TrackerReportsUsageTest.php b/tests/modules/Trackers/TrackerReportsUsageTest.php new file mode 100755 index 00000000..767c6f6f --- /dev/null +++ b/tests/modules/Trackers/TrackerReportsUsageTest.php @@ -0,0 +1,88 @@ +unPause(); + + $GLOBALS['current_user'] = SugarTestUserUtilities::createAnonymousUser(); + + //$tracker_sessions_monitor = $trackerManager->getMonitor('tracker_sessions'); + $monitor = $trackerManager->getMonitor('tracker'); + $monitor->setEnabled(true); + $monitor->setValue('module_name', 'Contacts'); + $monitor->setValue('item_id', '10909d69-2b55-094d-ba89-47b23d3121dd'); + $monitor->setValue('item_summary', 'Foo'); + $monitor->setValue('date_modified', gmdate($GLOBALS['timedate']->get_db_date_time_format()), strtotime("-1 day")+5000); + $monitor->setValue('action', 'index'); + $monitor->setValue('session_id', 'test_session'); + $monitor->setValue('user_id', $GLOBALS['current_user']->id); + $trackerManager->save(); + + $monitor->setValue('module_name', 'Contacts'); + $monitor->setValue('item_id', '10909d69-2b55-094d-ba89-47b23d3121dd'); + $monitor->setValue('item_summary', 'Foo'); + $monitor->setValue('date_modified', gmdate($GLOBALS['timedate']->get_db_date_time_format(), strtotime("-1 week")+5000)); + $monitor->setValue('action', 'index'); + $monitor->setValue('session_id', 'test_session'); + $monitor->setValue('user_id', $GLOBALS['current_user']->id); + $trackerManager->save(); + + $monitor->setValue('module_name', 'Contacts'); + $monitor->setValue('item_id', '10909d69-2b55-094d-ba89-47b23d3121dd'); + $monitor->setValue('item_summary', 'Foo'); + $monitor->setValue('date_modified', gmdate($GLOBALS['timedate']->get_db_date_time_format(), strtotime("-1 month")+5000)); + $monitor->setValue('action', 'index'); + $monitor->setValue('session_id', 'test_session'); + $monitor->setValue('user_id', $GLOBALS['current_user']->id); + $trackerManager->save(); + + $beanList = array(); + $beanFiles = array(); + require('include/modules.php'); + $GLOBALS['beanList'] = $beanList; + $GLOBALS['beanFiles'] = $beanFiles; + } + + public function tearDown() + { + $query = "DELETE FROM tracker WHERE session_id = 'test_session'"; + $GLOBALS['db']->query($query); + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + SugarTestTrackerUtility::restore(); + + unset($GLOBALS['beanList']); + unset($GLOBALS['beanFiles']); + } + + public function testUsageMetricsDay() + { + $query = "SELECT module_name, item_id, item_summary, date_modified from tracker where session_id = 'test_session' and user_id = '{$GLOBALS['current_user']->id}' and date_modified > "; + $query .= db_convert("'". gmdate($GLOBALS['timedate']->get_db_date_time_format(), strtotime("-1 day")) ."'" ,"datetime"); + $count = $GLOBALS['db']->getRowCount($GLOBALS['db']->query($query)); + $this->assertEquals($count,1); + } + + public function testUsageMetricsWeek() + { + $query = "SELECT module_name, item_id, item_summary, date_modified from tracker where session_id = 'test_session' and user_id = '{$GLOBALS['current_user']->id}' and date_modified > "; + $query .= db_convert("'". gmdate($GLOBALS['timedate']->get_db_date_time_format(), strtotime("-1 week")) ."'" ,"datetime"); + $count = $GLOBALS['db']->getRowCount($GLOBALS['db']->query($query)); + $this->assertEquals($count,2); + } + + public function testUsageMetricsMonth() + { + $query = "SELECT module_name, item_id, item_summary, date_modified from tracker where session_id = 'test_session' and user_id = '{$GLOBALS['current_user']->id}' and date_modified > "; + $query .= db_convert("'". gmdate($GLOBALS['timedate']->get_db_date_time_format(), strtotime("-1 month")) ."'" ,"datetime"); + $count = $GLOBALS['db']->getRowCount($GLOBALS['db']->query($query)); + $this->assertEquals($count,3); + } +} + +?> diff --git a/tests/modules/Trackers/TrackerSaveTest.php b/tests/modules/Trackers/TrackerSaveTest.php new file mode 100755 index 00000000..f0a54c8b --- /dev/null +++ b/tests/modules/Trackers/TrackerSaveTest.php @@ -0,0 +1,16 @@ +getMonitor('tracker'); + $monitor->setEnabled(true); + // Test to see how it handles saving an Array + $user = new User(); + $monitor->setValue('module_name', $user); + $this->assertTrue($monitor->module_name == "User"); + } + +} +?> \ No newline at end of file diff --git a/tests/modules/Trackers/TrackerTestUtility.php b/tests/modules/Trackers/TrackerTestUtility.php new file mode 100755 index 00000000..3eadce9c --- /dev/null +++ b/tests/modules/Trackers/TrackerTestUtility.php @@ -0,0 +1,29 @@ +query("SELECT category, name, value from config WHERE category = 'tracker' and name != 'prune_interval'"); + self::$trackerSettings = array(); + while($row = $GLOBALS['db']->fetchByAssoc($result)){ + self::$trackerSettings[$row['name']] = $row['value']; + $GLOBALS['db']->query("DELETE from config where category = 'tracker' and name = '{$row['name']}'"); + } +} + +static function tearDown() { + foreach(self::$trackerSettings as $name=>$value) { + $GLOBALS['db']->query("INSERT into config (category, name, value) values ('tracker', '{$name}', '{$value}')"); + } +} + +} +?> \ No newline at end of file diff --git a/tests/modules/Trackers/TrackerUpgradeDashletTest.php b/tests/modules/Trackers/TrackerUpgradeDashletTest.php new file mode 100755 index 00000000..15176230 --- /dev/null +++ b/tests/modules/Trackers/TrackerUpgradeDashletTest.php @@ -0,0 +1,95 @@ +markTestSkipped("Skipping unless otherwise specified"); + + TrackerTestUtility::setUp(); + $GLOBALS['mod_strings'] = return_module_language($GLOBALS['current_language'], 'Home'); + + $cuser = new User(); + $cuser->retrieve('1'); + $GLOBALS['current_user'] = $cuser; + + //Set the user theme to be 'Sugar' theme since this is run for CE flavor conversions + $cuser->setPreference('user_theme', 'Sugar5', 0, 'global'); + + if(ACLController::checkAccess('Trackers', 'view', false, 'Tracker')) { + $pages = $GLOBALS['current_user']->getPreference('pages', 'Home'); + $pages = !empty($pages) ? $pages : array(); + $dashlets = $GLOBALS['current_user']->getPreference('dashlets', 'Home'); + $dashlets = !empty($dashlets) ? $dashlets : array(); + $new_dashlets = array(); + + foreach($dashlets as $id=>$dashlet) { + if(!in_array($dashlet['className'], $this->defaultTrackingDashlets)) { + $new_dashlets[$id] = $dashlet; + } + } + + $GLOBALS['current_user']->setPreference('dashlets', $new_dashlets, 0, 'Home'); + + $new_pages = array(); + foreach($pages as $page) { + if(!empty($page['pageTitle']) && $page['pageTitle'] != 'Tracker') { + $new_pages[] = $page; + } + } + + $GLOBALS['current_user']->setPreference('pages', $new_pages, 0, 'Home'); + $GLOBALS['current_user']->save(); + } //if + } + + function tearDown() { + TrackerTestUtility::tearDown(); + $user = new User(); + $user->retrieve('1'); + $GLOBALS['current_user'] = $user; + } + + + function testUpgradeTrackerDashlet() { + $this->upgradeUserPreferencesCopy(); + $cuser = new User(); + $cuser->retrieve('1'); + $dashlets = $cuser->getPreference('dashlets', 'Home'); + $countAdded = 0; + + foreach($dashlets as $id=>$dashlet) { + if(in_array($dashlet['className'], $this->defaultTrackingDashlets)) { + $countAdded++; + } + } + + $this->assertEquals($countAdded, 3); + + $pages = $cuser->getPreference('pages', 'Home'); + $countAdded = 0; + foreach($pages as $id=>$page) { + if($page['pageTitle'] == 'Tracker') { + $countAdded++; + } + } + + $theme = $cuser->getPreference('user_theme', 'global'); + $this->assertTrue($theme == 'Sugar'); + $this->assertTrue($countAdded == 1); + } + + +/** + * upgradeUserPreferencesCopy + * + */ +private function upgradeUserPreferencesCopy() { + +} + +} +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/Bug30709Test.php b/tests/modules/UpgradeWizard/Bug30709Test.php new file mode 100755 index 00000000..2650dd04 --- /dev/null +++ b/tests/modules/UpgradeWizard/Bug30709Test.php @@ -0,0 +1,171 @@ + 'A', + 'b' => 'B', + 'c' => 'C', +); + +\$app_list_strings['a_test_1'] = array ( + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', +); + +//a_test_1 is the same, nothing was wrong with it +\$app_list_strings['a_test_that_is_okay'] = array ( + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', +); + +//b_test_2 has four entries, but "4" +\$app_list_strings['b_test_2'] = array ( + '0' => 'Zero', + '1' => 'One', + '2' => 'Two', + '4' => 'Four', +); + +//c_test_3 has four entries +\$app_list_strings['c_test_3'] = array ( + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', + 'd' => 'D', +); + +\$GLOBALS['app_list_strings']['b_test_2'] = array ( + '0' => 'Zero', + '1' => 'One', + '2' => 'Two', + '3' => 'Three', +); + +\$GLOBALS['app_list_strings']['c_test_3'] = array ( + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', + 'd' => 'D', + 'e' => 'E', +); + +\$GLOBALS['app_list_strings']['c_test_3'] = array ( + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', + 'd' => 'D', + 'f' => 'F', +); + + +EOQ; + fputs( $fh, $string); + fclose( $fh ); + } + + //Simulate the .php file that was created + if( $fh = @fopen('custom/include/language/en_us.lang.php', 'w+') ) + { +$string = << 'A', + 'b' => 'B', + 'c' => 'C', + ); + +\$GLOBALS['app_list_strings']['a_test__'] = array ( + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', +); + +\$GLOBALS['app_list_strings']['b_test__'] = array ( + '0' => 'Zero', + '1' => 'One', + '2' => 'Two', + '4' => 'Four', +); + +\$GLOBALS['app_list_strings']['c_test__'] = array ( + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', + 'd' => 'D', +); + + +EOQ; + fputs( $fh, $string); + fclose( $fh ); + } + +} + +function tearDown() { + if(file_exists('custom/include/language/en_us.lang.php.backup')) { + copy('custom/include/language/en_us.lang.php.backup', 'custom/include/language/en_us.lang.php'); + unlink('custom/include/language/en_us.lang.php.backup'); + } else { + unlink('custom/include/language/en_us.lang.php'); + } + + if(file_exists('custom/include/language/en_us.lang.php.bak')) { + unlink('custom/include/language/en_us.lang.php.bak'); + } + + if(file_exists('custom/include/language/en_us.lang.php.php_bak')) { + unlink('custom/include/language/en_us.lang.php.php_bak'); + } + + $GLOBALS['app_strings'] = return_application_language($GLOBALS['current_language']); + $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']); +} + + +function test_dropdown_fixed() { + require_once('modules/UpgradeWizard/uw_utils.php'); + fix_dropdown_list(); + + //Check to make sure we don't have the buggy format where '$GLOBALS["app_list_strings"] = array (...' was declared + $contents = file_get_contents('custom/include/language/en_us.lang.php'); + + unset($GLOBALS['app_list_strings']); + require('custom/include/language/en_us.lang.php'); + + $this->assertTrue(isset($GLOBALS['app_list_strings']['this_would_have_been_missed_'])); + + preg_match_all('/a_test_that_is_okay/', $contents, $matches); + $this->assertEquals(count($matches[0]),1); + + $this->assertEquals(count($GLOBALS['app_list_strings']['a_test_that_is_okay']),3); + + preg_match_all('/b_test__/', $contents, $matches); + $this->assertEquals(count($matches[0]),2); + + $this->assertEquals(count($GLOBALS['app_list_strings']['b_test__']),4); + + preg_match_all('/c_test__/', $contents, $matches); + $this->assertEquals(count($matches[0]),2); + + $this->assertEquals(count($GLOBALS['app_list_strings']['c_test__']),5); +} + + +} + +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/Bug30709_Part_2_Test.php b/tests/modules/UpgradeWizard/Bug30709_Part_2_Test.php new file mode 100755 index 00000000..a9163aab --- /dev/null +++ b/tests/modules/UpgradeWizard/Bug30709_Part_2_Test.php @@ -0,0 +1,150 @@ +array( + 'abc' => 'ABC', + 'cbs' => 'CBS', + 'nbc' => 'NBC', + ), + 'lead_source_dom' => + array ( + '' => '', + 'Cold Call' => 'Cold Call', + 'Existing Customer' => 'Existing Customer', + 'Self Generated' => 'Self Generated', + 'Employee' => 'Employee', + 'Partner' => 'Partner', + 'Public Relations' => 'Public Relations', + 'Direct Mail' => 'Direct Mail', + 'Conference' => 'Conference', + 'Trade Show' => 'Trade Show', + 'Web Site' => 'Web Site', + 'Word of mouth' => 'Word of mouth', + 'Email' => 'Email', + 'Campaign'=>'Campaign', + 'Other' => 'Other', + ), + 'opportunity_type_dom' => + array ( + '' => '', + 'Existing Business' => 'Existing Business', + 'New Business' => 'New Business', + ), + 'moduleList' => + array ( + 'Home' => 'Home', + 'Dashboard' => 'Dashboard', + 'Contacts' => 'Contacts', + 'Accounts' => 'Accounts Module', + 'Opportunities' => 'Opportunities', + 'Cases' => 'Cases', + 'Notes' => 'Notes', + 'Calls' => 'Calls', + 'Emails' => 'Emails', + 'Meetings' => 'Meetings', + 'Tasks' => 'Tasks', + 'Calendar' => 'Calendar', + 'Leads' => 'Leads', + 'Currencies' => 'Currencies', + 'Contracts' => 'Contracts', + 'Quotes' => 'Quotes', + 'Products' => 'Products', + 'ProductCategories' => 'Product Categories', + 'ProductTypes' => 'Product Types', + 'ProductTemplates' => 'Product Catalog', + 'Reports' => 'Reports', + 'Reports_1' => 'Reports', + 'Forecasts' => 'Forecasts', + 'ForecastSchedule' => 'Forecast Schedule', + 'MergeRecords' => 'Merge Records', + 'Quotas' => 'Quotas', + 'Teams' => 'Teams', + 'Activities' => 'Activities', + 'Bugs' => 'Bug Tracker', + 'Feeds' => 'RSS', + 'iFrames' => 'My Portal', + 'TimePeriods' => 'Time Periods', + 'Project' => 'Projects', + 'ProjectTask' => 'Project Tasks', + 'Campaigns' => 'Campaigns', + 'CampaignLog' => 'Campaign Log', + 'Documents' => 'Documents', + 'Sync' => 'Sync', + 'WorkFlow' => 'Work Flow', + 'Users' => 'Users', + 'Releases' => 'Releases', + 'Prospects' => 'Targets', + 'Queues' => 'Queues', + 'EmailMarketing' => 'Email Marketing', + 'EmailTemplates' => 'Email Templates', + 'ProspectLists' => 'Target Lists', + 'SavedSearch' => 'Saved Searches', + 'Trackers' => 'Trackers', + 'TrackerPerfs' => 'Tracker Performance', + 'TrackerSessions' => 'Tracker Sessions', + 'TrackerQueries' => 'Tracker Queries', + 'FAQ' => 'FAQ', + 'Newsletters' => 'Newsletters', + 'SugarFeed' => 'Sugar Feed', + 'Library' => 'Library', + 'EmailAddresses' => 'Email Address', + 'KBDocuments' => 'Knowledge Base', + 'my_personal_module' => 'My Personal Module', + ), +); + +\$GLOBALS['app_strings']['LBL_TEST'] = 'This is a test'; +EOQ; + fputs( $fh, $string); + fclose( $fh ); + } +} + +function tearDown() { + if(file_exists('custom/include/language/en_us.lang.php.backup')) { + copy('custom/include/language/en_us.lang.php.backup', 'custom/include/language/en_us.lang.php'); + unlink('custom/include/language/en_us.lang.php.backup'); + } else { + unlink('custom/include/language/en_us.lang.php'); + } + + if(file_exists('custom/include/language/en_us.lang.php.bak')) { + unlink('custom/include/language/en_us.lang.php.bak'); + } + + $GLOBALS['app_strings'] = return_application_language($GLOBALS['current_language']); + $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']); +} + +function test_dropdown_fixed() { + require_once('modules/UpgradeWizard/uw_utils.php'); + fix_dropdown_list(); + + //Check to make sure we don't have the buggy format where '$GLOBALS["app_list_strings"] = array (...' was declared + $contents = file_get_contents('custom/include/language/en_us.lang.php'); + //$this->assertFalse(preg_match('/\$GLOBALS\[\s*[\"|\']app_list_strings[\"|\']\s*\]\s+=\s+array\s+\(/', $contents)); + + unset($GLOBALS['app_list_strings']); + require('custom/include/language/en_us.lang.php'); + $this->assertEquals(count($GLOBALS['app_list_strings']),2); + $this->assertTrue(isset($GLOBALS['app_list_strings']['moduleList']['my_personal_module'])); + $this->assertEquals($GLOBALS['app_list_strings']['moduleList']['Accounts'],'Accounts Module'); + $this->assertEquals(count($GLOBALS['app_strings']),1); + $this->assertEquals($GLOBALS['app_strings']['LBL_TEST'],'This is a test'); +} + + +} + +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/Bug32003_Test.php b/tests/modules/UpgradeWizard/Bug32003_Test.php new file mode 100755 index 00000000..9ec29224 --- /dev/null +++ b/tests/modules/UpgradeWizard/Bug32003_Test.php @@ -0,0 +1,592 @@ + 'iframes' + ,'fields' => array ( + 'id' => + array ( + 'name' => 'id', + 'vname' => 'LBL_ID', + 'type' => 'id', + 'required'=>true, + ), + 'name' => + array ( + 'name' => 'name', + 'vname' => 'LBL_LIST_NAME', + 'type' => 'varchar', + 'len' => '255', + 'required'=>true, + 'importable' => 'required', + ), + 'url' => + array ( + 'name' => 'url', + 'vname' => 'LBL_LIST_URL', + 'type' => 'varchar', + 'len' => '255', + 'required'=>true, + 'importable' => 'required', + ), + 'type' => + array ( + 'name' => 'type', + 'vname' => 'LBL_LIST_TYPE', + 'type' => 'varchar', + 'len' => '255', + 'required'=>true, + ), + 'placement' => + array ( + 'name' => 'placement', + 'vname' => 'LBL_LIST_PLACEMENT', + 'type' => 'varchar', + 'len' => '255', + 'required'=>true, + 'importable' => 'required', + ), + 'status' => + array ( + 'name' => 'status', + 'vname' => 'LBL_LIST_STATUS', + 'type' => 'bool', + 'required'=>true, + ), + 'deleted' => + array ( + 'name' => 'deleted', + 'vname' => 'LBL_DELETED', + 'type' => 'bool', + 'required'=>true, + ), + 'date_entered' => + array ( + 'name' => 'date_entered', + 'vname' => 'LBL_DATE_ENTERED', + 'type' => 'datetime', + 'required'=>true, + ), + 'date_modified' => + array ( + 'name' => 'date_modified', + 'vname' => 'LBL_DATE_MODIFIED', + 'type' => 'datetime', + 'required'=>true, + ), + 'created_by' => + array ( + 'name' => 'created_by', + 'rname' => 'user_name', + 'id_name' => 'modified_user_id', + 'vname' => 'LBL_ASSIGNED_TO', + 'type' => 'assigned_user_name', + 'table' => 'users', + 'isnull' => 'false', + 'dbType' => 'id', + 'required'=>true, + ), +), +'indices' => array ( + array('name' =>'iframespk', 'type' =>'primary', 'fields'=>array('id')), + array('name' =>'idx_cont_name', 'type'=>'index', 'fields'=>array('name','deleted')) +) +); + + +$dictionary['Feed'] = array('table' => 'feeds', 'comment' => 'RSS Feeds' + ,'fields' => array ( + 'id' => + array ( + 'name' => 'id', + 'vname' => 'LBL_ID', + 'type' => 'id', + 'required'=>true, + 'reportable'=>true, + 'comment' => 'Unique identifier' + ), + 'deleted' => + array ( + 'name' => 'deleted', + 'vname' => 'LBL_CREATED_BY', + 'type' => 'bool', + 'required'=>true, + 'reportable'=>false, + 'comment' => 'Record deletion indicator' + ), + 'date_entered' => + array ( + 'name' => 'date_entered', + 'vname' => 'LBL_DATE_ENTERED', + 'type' => 'datetime', + 'required'=>true, + 'comment' => 'Date record created' + ), + 'date_modified' => + array ( + 'name' => 'date_modified', + 'vname' => 'LBL_DATE_MODIFIED', + 'type' => 'datetime', + 'required'=>true, + 'comment' => 'Date record last modified' + ), + 'modified_user_id' => + array ( + 'name' => 'modified_user_id', + 'rname' => 'user_name', + 'id_name' => 'modified_user_id', + 'vname' => 'LBL_ASSIGNED_TO', + 'type' => 'assigned_user_name', + 'table' => 'users', + 'isnull' => 'false', + 'dbType' => 'id', + 'required'=>true, + 'reportable'=>true, + 'comment' => 'User who last modified record' + ), + 'assigned_user_id' => + array ( + 'name' => 'assigned_user_id', + 'rname' => 'user_name', + 'id_name' => 'assigned_user_id', + 'vname' => 'LBL_ASSIGNED_TO', + 'type' => 'assigned_user_name', + 'table' => 'users', + 'isnull' => 'false', + 'dbType' => 'id', + 'reportable'=>true, + 'comment' => 'User assigned to record' + ), + 'created_by' => + array ( + 'name' => 'created_by', + 'rname' => 'user_name', + 'id_name' => 'modified_user_id', + 'vname' => 'LBL_ASSIGNED_TO', + 'type' => 'assigned_user_name', + 'table' => 'users', + 'isnull' => 'false', + 'dbType' => 'id', + 'comment' => 'User that created record' + ), + 'title' => + array ( + 'name' => 'title', + 'type' => 'varchar', + 'len' => '100', + 'vname' => 'LBL_TITLE', + 'comment' => 'Title of RSS feed' + ), + 'description' => + array ( + 'name' => 'description', + 'type' => 'text', + 'vname' => 'LBL_DESCRIPTION', + 'comment' => 'Description of RSS feed' + ), + 'url' => + array ( + 'name' => 'url', + 'type' => 'varchar', + 'len' => '255', + 'vname' => 'LBL_URL', + 'comment' => 'URL that represents the RSS feed', + 'importable' => 'required', + ), + 'created_by_link' => + array ( + 'name' => 'created_by_link', + 'type' => 'link', + 'relationship' => 'feeds_created_by', + 'vname' => 'LBL_CREATED_BY_USER', + 'link_type' => 'one', + 'module'=>'Users', + 'bean_name'=>'User', + 'source'=>'non-db', + ), + 'modified_user_link' => + array ( + 'name' => 'modified_user_link', + 'type' => 'link', + 'relationship' => 'feeds_modified_user', + 'vname' => 'LBL_MODIFIED_BY_USER', + 'link_type' => 'one', + 'module'=>'Users', + 'bean_name'=>'User', + 'source'=>'non-db', + ), + 'assigned_user_link' => + array ( + 'name' => 'assigned_user_link', + 'type' => 'link', + 'relationship' => 'feeds_assigned_user', + 'vname' => 'LBL_ASSIGNED_TO_USER', + 'link_type' => 'one', + 'module'=>'Users', + 'bean_name'=>'User', + 'source'=>'non-db', + ), +) +, + 'relationships' => array ( + + 'feeds_assigned_user' => + array('lhs_module'=> 'Users', 'lhs_table'=> 'users', 'lhs_key' => 'id', + 'rhs_module'=> 'Feeds', 'rhs_table'=> 'feeds', 'rhs_key' => 'assigned_user_id', + 'relationship_type'=>'one-to-many') + + ,'feeds_modified_user' => + array('lhs_module'=> 'Users', 'lhs_table'=> 'users', 'lhs_key' => 'id', + 'rhs_module'=> 'Feeds', 'rhs_table'=> 'feeds', 'rhs_key' => 'modified_user_id', + 'relationship_type'=>'one-to-many') + + ,'feeds_created_by' => + array('lhs_module'=> 'Users', 'lhs_table'=> 'users', 'lhs_key' => 'id', + 'rhs_module'=> 'Feeds', 'rhs_table'=> 'feeds', 'rhs_key' => 'created_by', + 'relationship_type'=>'one-to-many') +) + + , 'indices' => array ( + array('name' =>'feedspk', 'type' =>'primary', 'fields'=>array('id')), + array('name' =>'idx_feed_name', 'type'=>'index', 'fields'=>array('title','deleted')) + ) + + ); + +VardefManager::createVardef('Feeds','Feed', array( +)); + + require_once('include/database/DBManagerFactory.php'); + $db = DBManagerFactory::getInstance(); + + if(!$db->tableExists('iframes')){ + $db->createTableParams('iframes', $dictionary['iFrame']['fields'], $dictionary['iFrame']['indices']); + } + + if(!$db->tableExists('feeds')){ + $db->createTableParams('feeds', $dictionary['Feed']['fields'], $dictionary['Feed']['indices']); + } + + global $moduleList; + $moduleList['Feeds'] = 'Feeds'; + $moduleList['iFrames'] = 'iFrames'; + + require_once("modules/MySettings/TabController.php"); + $this->controller = new TabController(); + + global $current_user; + if ( !( $current_user instanceOf User ) ) { + $current_user = new User; + $current_user->retrieve('1'); + } + $this->original_current_user_id = $current_user->id; +} + +function tearDown() { + $db = DBManagerFactory::getInstance(); + if($db->tableExists('iframes')) { + $db->dropTableName('iframes'); + } + + if($db->tableExists('feeds')) { + $db->dropTableName('feeds'); + } + + global $moduleList; + require_once("modules/MySettings/TabController.php"); + $this->controller = new TabController(); + + global $moduleList; + $keys = array_flip($moduleList); + if(in_array('Feeds', $moduleList)) { + unset($moduleList[$keys['Feeds']]); + } + + if(in_array('iFrames', $moduleList)) { + unset($moduleList[$keys['iFrames']]); + } + + $this->controller->set_system_tabs($moduleList); + + if(file_exists('custom/Extension/application/Ext/Include/Feed.php')) { + unlink('custom/Extension/application/Ext/Include/Feed.php'); + } + + if(file_exists('custom/Extension/application/Ext/Include/iFrame.php')) { + unlink('custom/Extension/application/Ext/Include/iFrame.php'); + } + + global $current_user; + $current_user->retrieve($this->original_current_user_id); +} + + +function disabled_post_install_upgrade_with_iframes() { + $db = DBManagerFactory::getInstance(); + $db->query('INSERT into iframes(id, name, url) values (\'' . mktime() . '\', \'test\', \'www.test.com\')'); + hide_iframes_and_feeds_modules(); + $this->assertTrue($db->tableExists('iframes')); + $this->assertTrue(file_exists('custom/Extension/application/Ext/Include/iFrame.php')); +} + + +function disabled_post_install_upgrade_without_iframes() { + hide_iframes_and_feeds_modules(); + $db = DBManagerFactory::getInstance(); + $this->assertTrue(!$db->tableExists('iframes')); + + $this->assertTrue(!file_exists('custom/Extension/application/Ext/Include/iFrame.php')); +} + + +function disabled_post_install_upgrade_with_feeds() { + $this->markTestSkipped("Skip test_post_install_upgrade_with_feeds"); + $tabs = $this->controller->get_tabs_system(); + echo var_export($tabs, true); + + //If it is hidden, set it to show + if(isset($tabs[1]['Feeds'])) { + $db = DBManagerFactory::getInstance(); + $db->query('DELETE FROM config WHERE category = \'MySettings\' AND name = \'tab\''); + unset($tabs[1]['Feeds']); + $tabs[0]['Feeds'] = 'Feeds'; + + $administration = new Administration(); + $serialized = base64_encode(serialize($moduleList)); + $administration->saveSetting('MySettings', 'tab', $serialized); + $this->controller->set_system_tabs($tabs); + } + + /* + //It's as if this never changes + $tabs = $this->controller->get_tabs_system(); + echo var_export($tabs, true); + + */ + hide_iframes_and_feeds_modules(); + $this->assertTrue($db->tableExists('feeds')); + $this->assertTrue(file_exists('custom/Extension/application/Ext/Include/Feed.php')); +} + + +function disabled_post_install_upgrade_without_feeds() { + hide_iframes_and_feeds_modules(); + $db = DBManagerFactory::getInstance(); + $this->assertTrue(!$db->tableExists('feeds')); + $this->assertTrue(!file_exists('custom/Extension/application/Ext/Include/Feed.php')); +} + +/* + * Added a minimum of 1 test to make sure that + */ +function test_donothing() { + echo ""; +} + +function disabled_dashlets_module_changed() { + + $db = DBManagerFactory::getInstance(); + $query = "SELECT id, contents, assigned_user_id FROM user_preferences WHERE deleted = 0 AND category = 'Home'"; + $result = $db->query($query, true, "Unable to update iFrames and Feeds dashlets!"); + while ($row = $GLOBALS['db']->fetchByAssoc($result)) { + $content = unserialize(base64_decode($row['contents'])); + $assigned_user_id = $row['assigned_user_id']; + $record_id = $row['id']; + $current_user = new User(); + $current_user->retrieve($row['assigned_user_id']); + + if(!empty($content['dashlets']) && !empty($content['pages'])){ + $originalDashlets = $content['dashlets']; + $originalPages = $content['pages']; + + //Determine if the original perference has already had the two dashlets or not + foreach($originalDashlets as $key=>$ds){ + + if(!empty($ds['options']['title']) && $ds['options']['title'] == 'LBL_DASHLET_DISCOVER_SUGAR_PRO'){ + $originalDashlets[$key]['module'] = 'iFrames'; + } + if(!empty($ds['options']['title']) && $ds['options']['title'] == 'LBL_DASHLET_SUGAR_NEWS'){ + $originalDashlets[$key]['module'] = 'iFrames'; + } + } + + $current_user->setPreference('dashlets', $originalDashlets, 0, 'Home'); + $current_user->setPreference('pages', $originalPages, 0, 'Home'); + } + } //while + + + hide_iframes_and_feeds_modules(); + $result = $db->query($query, true, "Unable to update iFrames and Feeds dashlets!"); + $not_home_module = false; + + while ($row = $db->fetchByAssoc($result)) { + $content = unserialize(base64_decode($row['contents'])); + $assigned_user_id = $row['assigned_user_id']; + $record_id = $row['id']; + $current_user = new User(); + $current_user->retrieve($row['assigned_user_id']); + + if(!empty($content['dashlets']) && !empty($content['pages'])){ + $originalDashlets = $content['dashlets']; + $originalPages = $content['pages']; + + //Determine if the original perference has already had the two dashlets or not + foreach($originalDashlets as $key=>$ds){ + if(!empty($ds['options']['title']) && $ds['options']['title'] == 'LBL_DASHLET_DISCOVER_SUGAR_PRO' && $originalDashlets[$key]['module'] != 'Home') { + $not_home_module = true; + } + if(!empty($ds['options']['title']) && $ds['options']['title'] == 'LBL_DASHLET_SUGAR_NEWS' && $originalDashlets[$key]['module'] != 'Home'){ + $not_home_module = true; + } + } + } + } //while + + $this->assertFalse($not_home_module, 'Assert that dashlet\'s module were correctly set to Home module'); +} + +} + + +//BEGIN INLINE METHODS FROM BUILD (post_install.php) + +/** + * hide_iframes_and_feeds_modules + * This method determines whether or not to hide the iFrames and Feeds module + * for an upgrade to 551 + */ +function hide_iframes_and_feeds_modules() { + global $path; + + _logThis('Updating the iFrames Dashlets', $path); + $query = "SELECT id, contents, assigned_user_id FROM user_preferences WHERE deleted = 0 AND category = 'Home'"; + $result = $GLOBALS['db']->query($query, true, "Unable to update iFrames and Feeds dashlets!"); + while ($row = $GLOBALS['db']->fetchByAssoc($result)) { + $content = unserialize(base64_decode($row['contents'])); + $assigned_user_id = $row['assigned_user_id']; + $record_id = $row['id']; + $current_user = new User(); + $current_user->retrieve($row['assigned_user_id']); + + if(!empty($content['dashlets']) && !empty($content['pages'])){ + $originalDashlets = $content['dashlets']; + $originalPages = $content['pages']; + + //Determine if the original perference has already had the two dashlets or not + foreach($originalDashlets as $key=>$ds){ + if(!empty($ds['options']['title']) && $ds['options']['title'] == 'LBL_DASHLET_DISCOVER_SUGAR_PRO'){ + $originalDashlets[$key]['module'] = 'Home'; + } + if(!empty($ds['options']['title']) && $ds['options']['title'] == 'LBL_DASHLET_SUGAR_NEWS'){ + $originalDashlets[$key]['module'] = 'Home'; + } + } + + $current_user->setPreference('dashlets', $originalDashlets, 0, 'Home'); + $current_user->setPreference('pages', $originalPages, 0, 'Home'); + } + } //while + + $remove_iframes = false; + $remove_feeds = false; + + //Check if we should remove iframes. Use the count of entries in iframes table + $result = $GLOBALS['db']->query('SELECT count(id) as total from iframes'); + if(!empty($result)) { + $row = $GLOBALS['db']->fetchByAssoc($result); + if($row['total'] == 0) { + $remove_iframes = true; + } + } + + //Check if we should remove Feeds. We check if the tab is hidden + require_once("modules/MySettings/TabController.php"); + $controller = new TabController(); + $tabs = $controller->get_tabs_system(); + + //If the Feeds tab is hidden then remove it + if(!isset($tabs[0]['Feeds'])) { + $remove_feeds = true; + } + + if($remove_feeds) { + //Remove the modules/Feeds files + if(is_dir('modules/Feeds')) { + _logThis('Removing the Feeds files', $path); + rmdir_recursive('modules/Feeds'); + } + + //Drop the table + _logThis('Removing the Feeds table', $path); + $GLOBALS['db']->dropTableName('feeds'); + } else { + if(file_exists('modules/Feeds')) { + _logThis('Writing Feed.php module to custom/Extension/application/Ext/Include', $path); + write_to_modules_ext_php('Feed', 'Feeds', 'modules/Feeds/Feed.php', true); + } + } + + if($remove_iframes) { + //Remove the module/iFrames files + if(is_dir('modules/iFrames')) { + _logThis('Removing the iFrames files', $path); + rmdir_recursive('modules/iFrames'); + } + + //Drop the table + _logThis('Removing the iframes table', $path); + $GLOBALS['db']->dropTableName('iframes'); + } else { + if(file_exists('modules/iFrames')) { + _logThis('Writing iFrame.php module to custom/Extension/application/Ext/Include', $path); + write_to_modules_ext_php('iFrame', 'iFrames', 'modules/iFrames/iFrame.php', true); + } + } +} + +function write_to_modules_ext_php($module, $class, $path, $show=false) { + + global $beanList, $beanFiles; + include('include/modules.php'); + if(!isset($beanFiles[$module])) { + $str = ""; + if(!file_exists("custom/Extension/application/Ext/Include")) { + mkdir_recursive("custom/Extension/application/Ext/Include", true); + } + + $out = sugar_fopen("custom/Extension/application/Ext/Include/{$module}.php", 'w'); + fwrite($out, $str); + fclose($out); + } + +} + +function _logThis($string, $path) { + //echo $string . "\n"; + //no-opt +} + + + + +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/Bug32382Test.php b/tests/modules/UpgradeWizard/Bug32382Test.php new file mode 100755 index 00000000..e4229ddd --- /dev/null +++ b/tests/modules/UpgradeWizard/Bug32382Test.php @@ -0,0 +1,166 @@ + 'A', + 'b' => 'B', + 'c' => 'C', +); + +\$app_list_strings['a_test_1'] = array ( + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', +); + +//a_test_1 is the same, nothing was wrong with it +\$app_list_strings['a_test_that_is_okay'] = array ( + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', +); + +//b_test_2 has four entries, but "4" +\$app_list_strings['b_test_2'] = array ( + '0' => 'Zero', + '1' => 'One', + '2' => 'Two', + '4' => 'Four', +); + +//c_test_3 has four entries +\$app_list_strings['c_test_3'] = array ( + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', + 'd' => 'D', +); + +\$GLOBALS['app_list_strings']['b_test_2'] = array ( + '0' => 'Zero', + '1' => 'One', + '2' => 'Two', + '3' => 'Three', +); + +\$GLOBALS['app_list_strings']['c_test_3'] = array ( + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', + 'd' => 'D', + 'e' => 'E', +); + +\$GLOBALS['app_list_strings']['c_test_3'] = array ( + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', + 'd' => 'D', + 'f' => 'F', +); +EOQ; + fputs( $fh, $string); + fclose( $fh ); + } + + + //Simulate the .php file that was created + if( $fh = @fopen('custom/include/language/en_us.lang.php', 'w+') ) + { + $string = << 'A', + 'b' => 'B', + 'c' => 'C', + ); + +\$GLOBALS['app_list_strings']['a_test__'] = array ( + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', +); + +\$GLOBALS['app_list_strings']['b_test__'] = array ( + '0' => 'Zero', + '1' => 'One', + '2' => 'Two', + '4' => 'Four', +); + +\$GLOBALS['app_list_strings']['c_test__'] = array ( + 'a' => 'A', + 'b' => 'B', + 'c' => 'C', + 'd' => 'D', +); +EOQ; + fputs( $fh, $string); + fclose( $fh ); + } + + } + + public function tearDown() + { + if(file_exists('custom/include/language/en_us.lang.php.backup')) { + copy('custom/include/language/en_us.lang.php.backup', 'custom/include/language/en_us.lang.php'); + unlink('custom/include/language/en_us.lang.php.backup'); + } else { + unlink('custom/include/language/en_us.lang.php'); + } + + if(file_exists('custom/include/language/en_us.lang.php.bak')) { + unlink('custom/include/language/en_us.lang.php.bak'); + } + + if(file_exists('custom/include/language/en_us.lang.php.php_bak')) { + unlink('custom/include/language/en_us.lang.php.php_bak'); + } + + $GLOBALS['app_strings'] = return_application_language($GLOBALS['current_language']); + $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']); + } + + public function test_dropdown_fixed() + { + require_once('modules/UpgradeWizard/uw_utils.php'); + fix_dropdown_list(); + + //Check to make sure we don't have the buggy format where '$GLOBALS["app_list_strings"] = array (...' was declared + $contents = file_get_contents('custom/include/language/en_us.lang.php'); + + unset($GLOBALS['app_list_strings']); + require('custom/include/language/en_us.lang.php'); + + $this->assertTrue(isset($GLOBALS['app_list_strings']['this_would_have_been_missed_']), "Assert that 'this would have been missed! key was fixed"); + + preg_match_all('/a_test_that_is_okay/', $contents, $matches); + $this->assertEquals(count($matches[0]), 1, "Assert that a_test_is_okay entry exists"); + + $this->assertEquals(count($GLOBALS['app_list_strings']['a_test_that_is_okay']), 3, "Assert that a_test_that_is_okay has 3 items"); + + preg_match_all('/b_test__/', $contents, $matches); + $this->assertEquals(count($matches[0]), 2, "Assert that b_test__ is declared twice"); + + $this->assertEquals(count($GLOBALS['app_list_strings']['b_test__']), 4, "Assert that b_test__ is additive and has 4 entries"); + + preg_match_all('/c_test__/', $contents, $matches); + $this->assertEquals(count($matches[0]), 2, "Assert that c_test__ is declared twice"); + + $this->assertEquals(count($GLOBALS['app_list_strings']['c_test__']), 5, "Assert that c_test__ is additive and contains 5 entries"); + } +} \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/Bug42643Test.php b/tests/modules/UpgradeWizard/Bug42643Test.php new file mode 100755 index 00000000..51e7d4c1 --- /dev/null +++ b/tests/modules/UpgradeWizard/Bug42643Test.php @@ -0,0 +1,46 @@ +studio_file)) + { + //This really shouldn't be happening, but just in case... + $this->has_notification_studio_file = true; + $this->backup_file = $this->studio_file . '.' . gmmktime() . '.bak'; + copy($this->studio_file, $this->backup_file); + } else { + //Create the test file + write_array_to_file("test", array(), $this->studio_file); + } + } + + public function tearDown() + { + if($this->has_notification_studio_file) + { + copy($this->backup_file, $this->studio_file); + unlink($this->backup_file); + } else { + if(file_exists($this->studio_file)) + { + unlink($this->studio_file); + } + } + } + + public function testUnlinkUpgradeFilesPre614() + { + $this->assertTrue(file_exists($this->studio_file), 'Assert the ' . $this->studio_file . ' exists'); + unlinkUpgradeFiles('610'); + $this->assertFalse(file_exists($this->studio_file), 'Assert the ' . $this->studio_file . ' no longer exists'); + } +} \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SilentUpgradeSessionVarsTest.php b/tests/modules/UpgradeWizard/SilentUpgradeSessionVarsTest.php new file mode 100755 index 00000000..f9176b4c --- /dev/null +++ b/tests/modules/UpgradeWizard/SilentUpgradeSessionVarsTest.php @@ -0,0 +1,76 @@ +writeExternalTestFile(); + } + + public function tearDown() + { + $this->removeExternalTestFile(); + } + + public function testSilentUpgradeSessionVars() + { + + require_once('modules/UpgradeWizard/uw_utils.php'); + + $varsCacheFileName = "{$GLOBALS['sugar_config']['cache_dir']}/silentUpgrader/silentUpgradeCache.php"; + + $loaded = loadSilentUpgradeVars(); + $this->assertTrue($loaded, "Could not load the silent upgrade vars"); + global $silent_upgrade_vars_loaded; + $this->assertTrue(!empty($silent_upgrade_vars_loaded), "\$silent_upgrade_vars_loaded array should not be empty"); + + $set = setSilentUpgradeVar('SDizzle', 'BSnizzle'); + $this->assertTrue($set, "Could not set a silent upgrade var"); + + $get = getSilentUpgradeVar('SDizzle'); + $this->assertEquals('BSnizzle', $get, "Unexpected value when getting silent upgrade var before resetting"); + + $write = writeSilentUpgradeVars(); + $this->assertTrue($write, "Could not write the silent upgrade vars to the cache file. Function returned false"); + $this->assertFileExists($varsCacheFileName, "Cache file doesn't exist after call to writeSilentUpgradeVars()"); + + $output = shell_exec("php {$this->externalTestFileName}"); + + $this->assertEquals('BSnizzle', $output, "Running custom script didn't successfully retrieve the value"); + + $remove = removeSilentUpgradeVarsCache(); + $this->assertTrue(empty($silent_upgrade_vars_loaded), "Silent upgrade vars variable should have been unset in removeSilentUpgradeVarsCache() call"); + $this->assertFileNotExists($varsCacheFileName, "Cache file exists after call to removeSilentUpgradeVarsCache()"); + + $get = getSilentUpgradeVar('SDizzle'); + $this->assertNotEquals('BSnizzle', $get, "Unexpected value when getting silent upgrade var after resetting"); + } + + private function writeExternalTestFile() + { + $externalTestFileContents = <<externalTestFileName, $externalTestFileContents); + } + + private function removeExternalTestFile() + { + if(file_exists($this->externalTestFileName)) + { + unlink($this->externalTestFileName); + } + } +} +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/Bug36257Test.php b/tests/modules/UpgradeWizard/SugarMerge/Bug36257Test.php new file mode 100755 index 00000000..c76d2bf3 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/Bug36257Test.php @@ -0,0 +1,98 @@ +modules = array('Contacts'); + $this->has_dir = array(); + + foreach($this->modules as $module) { + if(!file_exists("custom/modules/{$module}/metadata")){ + mkdir_recursive("custom/modules/{$module}/metadata", true); + } + + if(file_exists("custom/modules/{$module}")) { + $this->has_dir[$module] = true; + } + + $files = array('editviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}")) { + copy("custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php.bak"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.php", "custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } + + if(file_exists("tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/{$module}/metadata/{$file}.php")) { + copy("tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php"); + } + } //foreach + } //foreach +} + + +function tearDown() { + + foreach($this->modules as $module) { + if(!$this->has_dir[$module]) { + rmdir_recursive("custom/modules/{$module}"); + } else { + $files = array('editviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.bak", "custom/modules/{$module}/metadata/{$file}.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$module}.php.suback.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.bak", "custom/modules/{$module}/metadata/{$file}.php.suback.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.php"); + } + } + } + } //foreach +} + + +function test_textarea_fields_on_contacts_editview_merge() { + require_once 'modules/UpgradeWizard/SugarMerge/EditViewMerge.php'; + $this->merge = new EditViewMerge(); + $this->merge->merge('Contacts', 'tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Contacts/metadata/editviewdefs.php', 'modules/Contacts/metadata/editviewdefs.php', 'custom/modules/Contacts/metadata/editviewdefs.php'); + $this->assertTrue(file_exists('custom/modules/Contacts/metadata/editviewdefs.php.suback.php')); + require('custom/modules/Contacts/metadata/editviewdefs.php'); + $fields = array(); + $panels = array(); + + foreach($viewdefs['Contacts']['EditView']['panels'] as $panel_key=>$panel) { + $panels[$panel_key] = $panel_key; + foreach($panel as $row) { + foreach($row as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $fields[$id] = $col; + } + } //foreach + } //foreach + } //foreach + + $this->assertTrue(!isset($fields['description']['displayParams']), 'Assert that a regular description field has displayParams attribute removed'); + $this->assertTrue(isset($fields['custom_description_c']['displayParams']), 'Assert that a customized description field has displayParams attribute preserved'); + $this->assertTrue($fields['custom_description_c']['displayParams']['rows'] == 10, 'Assert that the displayParams->rows attribute is 10'); + $this->assertTrue($fields['custom_description_c']['displayParams']['cols'] == 100, 'Assert that the displayParams->cols attribute is 100'); + +} + +} +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/Bug36481Test.php b/tests/modules/UpgradeWizard/SugarMerge/Bug36481Test.php new file mode 100755 index 00000000..85ef3e25 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/Bug36481Test.php @@ -0,0 +1,67 @@ +has_contacts_dir = true; + copy('custom/modules/Contacts/metadata/editviewdefs.php', 'custom/modules/Contacts/metadata/editviewdefs.php.bak'); + } + + $this->has_suback_file = file_exists('custom/modules/Contacts/metadata/editviewdefs.php.suback.php'); + + copy('tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/Contacts/metadata/editviewdefs.php', 'custom/modules/Contacts/metadata/editviewdefs.php'); +} + +function tearDown() { + return; + if(!$this->has_contacts_dir) { + rmdir_recursive('custom/modules/Contacts'); + } else if(file_exists('custom/modules/Contacts/metadata/editviewdefs.php.bak')) { + copy('custom/modules/Contacts/metadata/editviewdefs.php.bak', 'custom/modules/Contacts/metadata/editviewdefs.php'); + unlink('custom/modules/Contacts/metadata/editviewdefs.php.bak'); + + if(!$this->has_suback_file) { + unlink('custom/modules/Contacts/metadata/editviewdefs.php.suback.php'); + } + } + + +} + +function test_contacts_editview_merge() { + require_once('modules/UpgradeWizard/SugarMerge/EditViewMerge.php'); + $this->ev_merge = new EditViewMerge(); + $this->ev_merge->merge('Contacts', 'tests/modules/UpgradeWizard/SugarMerge/metadata_files/550/modules/Contacts/metadata/editviewdefs.php', 'modules/Contacts/metadata/editviewdefs.php', 'custom/modules/Contacts/metadata/editviewdefs.php'); + $this->assertTrue(file_exists('custom/modules/Contacts/metadata/editviewdefs.php.suback.php')); + require('custom/modules/Contacts/metadata/editviewdefs.php'); + $fields = array(); + foreach($viewdefs['Contacts']['EditView']['panels'] as $panel) { + foreach($panel as $row) { + foreach($row as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + $fields[$id] = $col; + } + } + } + + $this->assertTrue(isset($fields['test_c']), 'Assert that test_c custom field exists'); +} + + +} + +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/Bug37231Test.php b/tests/modules/UpgradeWizard/SugarMerge/Bug37231Test.php new file mode 100755 index 00000000..ed08499f --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/Bug37231Test.php @@ -0,0 +1,245 @@ +modules = array('Accounts', 'Opportunities'); + $this->has_dir = array(); + + foreach($this->modules as $module) { + if(!file_exists("custom/modules/{$module}/metadata")){ + mkdir_recursive("custom/modules/{$module}/metadata", true); + } + + if(file_exists("custom/modules/{$module}")) { + $this->has_dir[$module] = true; + } + + $files = array('detailviewdefs', 'editviewdefs', 'searchdefs', 'listviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}")) { + copy("custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php.bak"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.php", "custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } + + if(file_exists("tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/{$module}/metadata/{$file}.php")) { + copy("tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php"); + } + } //foreach + } //foreach +} + + +function tearDown() { + + foreach($this->modules as $module) { + if(!$this->has_dir[$module]) { + rmdir_recursive("custom/modules/{$module}"); + } else { + $files = array('detailviewdefs', 'editviewdefs', 'searchdefs', 'listviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.bak", "custom/modules/{$module}/metadata/{$file}.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$module}.php.suback.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.bak", "custom/modules/{$module}/metadata/{$file}.php.suback.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.php"); + } + } + } + } //foreach +} + + +function test_accounts_editview_merge() { + $original_panels = array(); + require('custom/modules/Accounts/metadata/editviewdefs.php'); + foreach($viewdefs['Accounts']['EditView']['panels'] as $panel_key=>$panel) { + $original_panels[$panel_key] = $panel_key; + } + + + require_once 'modules/UpgradeWizard/SugarMerge/EditViewMerge.php'; + $this->merge = new EditViewMerge(); + $this->merge->merge('Accounts', 'tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/editviewdefs.php', 'modules/Accounts/metadata/editviewdefs.php', 'custom/modules/Accounts/metadata/editviewdefs.php'); + $this->assertTrue(file_exists('custom/modules/Accounts/metadata/editviewdefs.php.suback.php')); + require('custom/modules/Accounts/metadata/editviewdefs.php'); + $fields = array(); + $panels = array(); + + foreach($viewdefs['Accounts']['EditView']['panels'] as $panel_key=>$panel) { + $panels[$panel_key] = $panel_key; + foreach($panel as $row) { + foreach($row as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $fields[$id] = $col; + } + } + } + } + + //echo var_export($original_panels, true); + //echo var_export($panels, true); + $this->assertTrue(count($panels) == count($original_panels), "Assert that orignal number of panels are preserved in custom Accounts EditView layout"); + $this->assertTrue(isset($panels['lbl_address_information']), "Assert that 'lbl_address_information' panel id is present"); + $this->assertTrue(isset($panels['lbl_email_addresses']), "Assert that 'lbl_email_addresses' panel id is present"); + $this->assertTrue(isset($panels['lbl_description_information']), "Assert that 'lbl_description_information' panel id is present"); + + + $custom_fields = array('reference_code_c', 'code_customized_by_c', 'customer_reference_c', 'type_of_reference_c', + 'reference_contact_c', 'last_used_as_reference_c', 'reference_status_c', 'reference_notes_c', + 'last_used_reference_notes_c', 'training_credits_purchased_c', 'remaining_training_credits_c', + 'training_credits_pur_date_c', 'training_credits_exp_date_c', 'support_cases_purchased_c', + ); + + foreach($custom_fields as $c_field) { + $this->assertTrue(isset($fields["{$c_field}"]), "Assert that custom field {$c_field} is present"); + } + + +} + + +function test_accounts_detailview_merge() { + require_once 'modules/UpgradeWizard/SugarMerge/DetailViewMerge.php'; + $this->merge = new DetailViewMerge(); + $this->merge->merge('Accounts', 'tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/detailviewdefs.php', 'modules/Accounts/metadata/detailviewdefs.php', 'custom/modules/Accounts/metadata/detailviewdefs.php'); + $this->assertTrue(file_exists('custom/modules/Accounts/metadata/detailviewdefs.php.suback.php')); + require('custom/modules/Accounts/metadata/detailviewdefs.php'); + $fields = array(); + $panels = array(); + + foreach($viewdefs['Accounts']['DetailView']['panels'] as $panel_key=>$panel) { + $panels[$panel_key] = $panel_key; + foreach($panel as $row) { + foreach($row as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $fields[$id] = $col; + } + } + } + } + + //echo var_export($panels, true); + //echo var_export($viewdefs['Accounts']['DetailView']['panels'], true); + $this->assertTrue(count($panels) == 5, "Assert that there are 5 panels matching the custom Accounts DetailView layout"); + $this->assertTrue(isset($panels['DEFAULT']), "Assert that 'DEFAULT' panel id is present"); + $this->assertTrue(isset($panels['lbl_panel7']), "Assert that 'lbl_panel7' panel id is present"); + $this->assertTrue(isset($panels['LBL_PANEL1']), "Assert that 'LBL_PANEL1' panel id is present"); + $this->assertTrue(isset($panels['LBL_PANEL6']), "Assert that 'LBL_PANEL6' panel id is present"); + $this->assertTrue(isset($panels['LBL_PANEL4']), "Assert that 'LBL_PANEL4' panel id is present"); + + //Test fields that were specified in other OOTB panels, but that are moved back to the default panel for + //this customization + $this->assertTrue(isset($fields['team_name']), "Assert that team_name field is present"); + $this->assertTrue(isset($fields['date_modified']), "Assert that date_modified field is present"); +} + + +function test_accounts_searchdefs_merge() { + require_once 'modules/UpgradeWizard/SugarMerge/SearchMerge.php'; + $this->merge = new SearchMerge(); + $this->merge->merge('Accounts', 'tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/searchdefs.php', 'modules/Accounts/metadata/searchdefs.php', 'custom/modules/Accounts/metadata/searchdefs.php'); + $this->assertTrue(file_exists('custom/modules/Accounts/metadata/searchdefs.php.suback.php')); + require('custom/modules/Accounts/metadata/searchdefs.php'); + $fields = array(); + + foreach($searchdefs['Accounts']['layout']['basic_search'] as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $fields[$id] = $col; + } + } + + + $this->assertTrue(count($fields) == 6, "Assert that there are 6 fields in the basic_search layout for Accounts metadata"); + + $fields = array(); + foreach($searchdefs['Accounts']['layout']['advanced_search'] as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id)) { + $fields[$id] = $col; + } + } + $this->assertTrue(count($fields) == 18, "Assert that there are 18 fields in the advanced_search layout for Accounts metadata"); +} + + +function test_accounts_listviewdefs_merge() { + require_once 'modules/UpgradeWizard/SugarMerge/ListViewMerge.php'; + $this->merge = new ListViewMerge(); + $this->merge->merge('Accounts', 'tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/listviewdefs.php', 'modules/Accounts/metadata/listviewdefs.php', 'custom/modules/Accounts/metadata/listviewdefs.php'); + $this->assertTrue(file_exists('custom/modules/Accounts/metadata/listviewdefs.php.suback.php')); + require('custom/modules/Accounts/metadata/listviewdefs.php'); + $fields = array(); + $displayed_fields = array(); + foreach($listViewDefs['Accounts'] as $col_key=>$col) { + $fields[$col_key] = $col; + if(isset($col['default']) && $col['default']) { + $displayed_fields[$col_key] = $col; + } + } + + + $this->assertTrue(count($displayed_fields) == 6, "Assert that there are 6 fields displayed in the listview layout for Accounts metadata"); + $this->assertTrue(isset($displayed_fields['NAME']), "Assert that NAME field is present"); + $this->assertTrue(isset($displayed_fields['BILLING_ADDRESS_CITY']), "Assert that BILLING_ADDRESS_CITY field is present"); + $this->assertTrue(isset($displayed_fields['BILLING_ADDRESS_STATE']), "Assert that BILLING_ADDRESS_STATE field is present"); + $this->assertTrue(isset($displayed_fields['PHONE_OFFICE']), "Assert that PHONE_OFFICE field is present"); + $this->assertTrue(isset($displayed_fields['TEAM_NAME']), "Assert that TEAM_NAME field is present"); + $this->assertTrue(isset($displayed_fields['ASSIGNED_USER_NAME']), "Assert that ASSIGNED_USER_NAME field is present"); +} + + +function test_opportunities_searchdefs_merge() { + require_once 'modules/UpgradeWizard/SugarMerge/SearchMerge.php'; + $this->merge = new SearchMerge(); + $this->merge->merge('Opportunities', 'tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Opportunities/metadata/searchdefs.php', 'modules/Opportunities/metadata/searchdefs.php', 'custom/modules/Opportunities/metadata/searchdefs.php'); + $this->assertTrue(file_exists('custom/modules/Opportunities/metadata/searchdefs.php.suback.php')); + require('custom/modules/Opportunities/metadata/searchdefs.php'); + $fields = array(); + + foreach($searchdefs['Opportunities']['layout']['basic_search'] as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $fields[$id] = $col; + } + } + + $this->assertTrue(count($fields) == 4, "Assert that there are 4 fields in the basic_search layout for Opportunities metadata"); + $this->assertTrue(isset($fields['name']), "Assert that name field is present"); + $this->assertTrue(isset($fields['opportunity_type']), "Assert that opportunity_type field is present"); + $this->assertTrue(isset($fields['account_name']), "Assert that account_name field is present"); + $this->assertTrue(isset($fields['current_user_only']), "Assert that current_user_only field is present"); + + $fields = array(); + foreach($searchdefs['Opportunities']['layout']['advanced_search'] as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $fields[$id] = $col; + } + } + + $this->assertTrue(count($fields) == 12, "Assert that there are 12 fields in the advanced_search layout for Opportunities metadata"); + $this->assertTrue(isset($fields['partner_assigned_to_c']), "Assert that partner_assigned_to_c field is present"); + +} + +} +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/Bug37295Test.php b/tests/modules/UpgradeWizard/SugarMerge/Bug37295Test.php new file mode 100755 index 00000000..646b8953 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/Bug37295Test.php @@ -0,0 +1,131 @@ +modules = array('Contacts'); + $this->has_dir = array(); + + foreach($this->modules as $module) { + if(!file_exists("custom/modules/{$module}/metadata")){ + mkdir_recursive("custom/modules/{$module}/metadata", true); + } + + if(file_exists("custom/modules/{$module}")) { + $this->has_dir[$module] = true; + } + + $files = array('editviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}")) { + copy("custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php.bak"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.php", "custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } + + if(file_exists("tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/{$module}/metadata/{$file}.php")) { + copy("tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php"); + } + } //foreach + } //foreach +} + + +function tearDown() { + + foreach($this->modules as $module) { + if(!$this->has_dir[$module]) { + rmdir_recursive("custom/modules/{$module}"); + } else { + $files = array('editviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.bak", "custom/modules/{$module}/metadata/{$file}.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$module}.php.suback.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.bak", "custom/modules/{$module}/metadata/{$file}.php.suback.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.php"); + } + } + } + } //foreach +} + + +function test_contacts_editview_merge() { + + require('custom/modules/Contacts/metadata/editviewdefs.php'); + $pre_upgrade_fields = array(); + $pre_upgrade_panels = array(); + foreach($viewdefs['Contacts']['EditView']['panels'] as $panel_key=>$panel) { + $pre_upgrade_panels[$panel_key] = $panel_key; + foreach($panel as $row) { + foreach($row as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $pre_upgrade_fields[$id] = $col; + } + } + } + } + + + require_once 'modules/UpgradeWizard/SugarMerge/EditViewMerge.php'; + $this->merge = new EditViewMerge(); + $this->merge->merge('Contacts', 'tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Contacts/metadata/editviewdefs.php', 'modules/Contacts/metadata/editviewdefs.php', 'custom/modules/Contacts/metadata/editviewdefs.php'); + $this->assertTrue(file_exists('custom/modules/Contacts/metadata/editviewdefs.php.suback.php')); + require('custom/modules/Contacts/metadata/editviewdefs.php'); + $fields = array(); + $panels = array(); + + //echo var_export($viewdefs['Contacts']['EditView']['panels'], true); + $new_fields = array(); + + foreach($viewdefs['Contacts']['EditView']['panels'] as $panel_key=>$panel) { + $panels[$panel_key] = $panel_key; + foreach($panel as $row) { + foreach($row as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $fields[$id] = $col; + if(!isset($pre_upgrade_fields[$id])) { + $new_fields[$id] = $id; + } + } + } + } + } + + + + $this->assertTrue(isset($panels['lbl_panel1']), "Assert that 'panel1' panel id is present"); + $this->assertTrue(isset($panels['lbl_address_information']), "Assert that 'lbl_address_information' panel id is present"); + $this->assertTrue(isset($panels['lbl_email_addresses']), "Assert that 'lbl_email_addresses' panel id is present"); + $this->assertTrue(isset($panels['lbl_description_information']), "Assert that 'lbl_description_information' panel id is present"); + + + $custom_fields = array('primary_business_c', 'support_authorized_c', 'university_enabled_c', 'billing_contact_c', + 'oppq_active_c', 'technical_proficiency_'); + + foreach($custom_fields as $c_field) { + $this->assertTrue(isset($fields["{$c_field}"]), "Assert that custom field {$c_field} is present"); + } + +} + + +} +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/Bug37461Test.php b/tests/modules/UpgradeWizard/SugarMerge/Bug37461Test.php new file mode 100755 index 00000000..3f338738 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/Bug37461Test.php @@ -0,0 +1,139 @@ +modules = array('Accounts'); + $this->has_dir = array(); + + foreach($this->modules as $module) { + if(!file_exists("custom/modules/{$module}/metadata")){ + mkdir_recursive("custom/modules/{$module}/metadata", true); + } + + if(file_exists("custom/modules/{$module}")) { + $this->has_dir[$module] = true; + } + + $files = array('searchdefs', 'listviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}")) { + copy("custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php.bak"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.php", "custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } + + if(file_exists("tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/{$module}/metadata/{$file}.php")) { + copy("tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php"); + } + } //foreach + } //foreach +} + + +function tearDown() { + + foreach($this->modules as $module) { + if(!$this->has_dir[$module]) { + rmdir_recursive("custom/modules/{$module}"); + } else { + $files = array('searchdefs', 'listviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.bak", "custom/modules/{$module}/metadata/{$file}.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$module}.php.suback.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.bak", "custom/modules/{$module}/metadata/{$file}.php.suback.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.php"); + } + } + } + } //foreach +} + + +function test_accounts_searchdefs_merge() { + require_once 'modules/UpgradeWizard/SugarMerge/SearchMerge.php'; + $this->merge = new SearchMerge(); + $this->merge->merge('Accounts', 'tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/searchdefs.php', 'modules/Accounts/metadata/searchdefs.php', 'custom/modules/Accounts/metadata/searchdefs.php'); + $this->assertTrue(file_exists('custom/modules/Accounts/metadata/searchdefs.php.suback.php')); + require('custom/modules/Accounts/metadata/searchdefs.php'); + $fields = array(); + + //echo var_export($searchdefs, true); + + foreach($searchdefs['Accounts']['layout']['basic_search'] as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $fields[$id] = $col; + } + } + + + $this->assertTrue(count($fields) == 6, "Assert that there are 6 fields in the basic_search layout for Accounts metadata"); + + $fields = array(); + foreach($searchdefs['Accounts']['layout']['advanced_search'] as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id)) { + $fields[$id] = $col; + } + } + $this->assertTrue(count($fields) == 18, "Assert that there are 18 fields in the advanced_search layout for Accounts metadata"); +} + + +function test_accounts_listviewdefs_merge() { + require('custom/modules/Accounts/metadata/listviewdefs.php'); + $original_fields = array(); + $original_displayed_fields = array(); + foreach($listViewDefs['Accounts'] as $col_key=>$col) { + $original_fields[$col_key] = $col; + if(isset($col['default']) && $col['default']) { + $original_displayed_fields[$col_key] = $col; + } + } + + //echo var_export($original_displayed_fields, true); + + require_once 'modules/UpgradeWizard/SugarMerge/ListViewMerge.php'; + $this->merge = new ListViewMerge(); + $this->merge->merge('Accounts', 'tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/listviewdefs.php', 'modules/Accounts/metadata/listviewdefs.php', 'custom/modules/Accounts/metadata/listviewdefs.php'); + $this->assertTrue(file_exists('custom/modules/Accounts/metadata/listviewdefs.php.suback.php')); + require('custom/modules/Accounts/metadata/listviewdefs.php'); + $fields = array(); + $displayed_fields = array(); + foreach($listViewDefs['Accounts'] as $col_key=>$col) { + $fields[$col_key] = $col; + if(isset($col['default']) && $col['default']) { + $displayed_fields[$col_key] = $col; + } + } + + //echo var_export($displayed_fields, true); + //echo var_export($listViewDefs['Accounts'], true); + + $this->assertTrue(count($displayed_fields) == count($original_displayed_fields), "Assert that there are the same number of fields displayed in the listview layout for Accounts metadata"); + $this->assertTrue(isset($displayed_fields['NAME']), "Assert that NAME field is present"); + $this->assertTrue(isset($displayed_fields['BILLING_ADDRESS_CITY']), "Assert that BILLING_ADDRESS_CITY field is present"); + $this->assertTrue(isset($displayed_fields['BILLING_ADDRESS_STATE']), "Assert that BILLING_ADDRESS_CITY field is present"); + $this->assertTrue(isset($displayed_fields['TEAM_NAME']), "Assert that TEAM_NAME (removed in 6.0 OOTB) field is present"); + $this->assertTrue(!isset($displayed_fields['BILLING_ADDRESS_COUNTRY']), "Assert that BILLING_ADDRESS_COUNTRY (added in 6.0 OOTB) field is not present"); +} + + +} +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/Bug37597Test.php b/tests/modules/UpgradeWizard/SugarMerge/Bug37597Test.php new file mode 100755 index 00000000..b7500f72 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/Bug37597Test.php @@ -0,0 +1,139 @@ +modules = array('Meetings'); + $this->has_dir = array(); + + foreach($this->modules as $module) { + if(!file_exists("custom/modules/{$module}/metadata")){ + mkdir_recursive("custom/modules/{$module}/metadata", true); + } + + if(file_exists("custom/modules/{$module}")) { + $this->has_dir[$module] = true; + } + + $files = array('detailviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}")) { + copy("custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php.bak"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.php", "custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } + + if(file_exists("tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/{$module}/metadata/{$file}.php")) { + copy("tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php"); + } + } //foreach + } //foreach +} + + +function tearDown() { + + foreach($this->modules as $module) { + if(!$this->has_dir[$module]) { + rmdir_recursive("custom/modules/{$module}"); + } else { + $files = array('detailviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.bak", "custom/modules/{$module}/metadata/{$file}.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$module}.php.suback.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.bak", "custom/modules/{$module}/metadata/{$file}.php.suback.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.php"); + } + } + } + } //foreach +} + + +function test_meetings_detailview_merge() { + require_once 'modules/UpgradeWizard/SugarMerge/DetailViewMerge.php'; + $this->merge = new DetailViewMerge(); + $this->merge->merge('Meetings', 'tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/551/modules/Meetings/metadata/detailviewdefs.php', 'modules/Meetings/metadata/detailviewdefs.php', 'custom/modules/Meetings/metadata/detailviewdefs.php'); + $this->assertTrue(file_exists('custom/modules/Meetings/metadata/detailviewdefs.php.suback.php')); + require('custom/modules/Meetings/metadata/detailviewdefs.php'); + $fields = array(); + $panels = array(); + + //echo var_export($viewdefs['Meetings']['DetailView']['panels'], true); + $columns_sanitized = true; + foreach($viewdefs['Meetings']['DetailView']['panels'] as $panel_key=>$panel) { + $panels[$panel_key] = $panel_key; + foreach($panel as $r=>$row) { + $new_row = true; + foreach($row as $col_key=>$col) { + if($new_row && $col_key != 0) { + $columns_sanitized = false; + } + + $new_row = false; + + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $fields[$id] = $col; + } + } + } + } + + //$this->assertTrue($columns_sanitized, "Assert that the column keys are sanitized (start with 0)"); + $this->assertTrue(isset($fields['meetings_opportunities_name']), "Assert that meetings_opportunities_name field is preserved"); + $this->assertTrue($viewdefs['Meetings']['DetailView']['panels']['default'][0][0]['name'] == 'name', "Assert that position of name field has not changed"); + $this->assertTrue($viewdefs['Meetings']['DetailView']['panels']['default'][0][1]['name'] == 'status', "Assert that position of status field has not changed"); + $this->assertTrue(isset($fields['date_modified']), "Assert that date_modified field is added"); + $this->assertTrue(isset($fields['date_entered']), "Assert that date_entered field is added"); + + //echo var_export($fields, true); + //echo var_export($panels, true); + + //$this->assertTrue(count($panels) == 2, "Assert that there are 2 panels matching the custom Meetings DetailView layout"); + //$this->assertTrue(isset($panels['lbl_panel1']), "Assert that 'lbl_panel1' panel id is present"); + + /* + $custom_fields = array('score_c', 'support_authorized_c', 'university_enabled_c', 'billing_contact_c', + 'oppq_active_c', 'technical_proficiency_'); + + foreach($custom_fields as $c_field) { + $this->assertTrue(isset($fields["{$c_field}"]), "Assert that custom field {$c_field} is present"); + } + */ + + /* + $found_team_name = false; + foreach($viewdefs['Meetings']['DetailView']['panels']['default'] as $row) { + foreach($row as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if($id == 'team_name') { + $found_team_name = true; + } + } + } + + $this->assertTrue($found_team_name, "Assert that team_name is present in default panel"); + */ + + +} + + +} +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/Bug37692Test.php b/tests/modules/UpgradeWizard/SugarMerge/Bug37692Test.php new file mode 100755 index 00000000..c944b5ca --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/Bug37692Test.php @@ -0,0 +1,82 @@ +modules = array('Project'); + $this->has_dir = array(); + + foreach($this->modules as $module) { + if(!file_exists("custom/modules/{$module}/metadata")){ + mkdir_recursive("custom/modules/{$module}/metadata", true); + } + + if(file_exists("custom/modules/{$module}")) { + $this->has_dir[$module] = true; + } + + $files = array('editviewdefs','detailviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}")) { + copy("custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php.bak"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.php", "custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } + + if(file_exists("tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/{$module}/metadata/{$file}.php")) { + copy("tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php"); + } + } //foreach + } //foreach +} + + +function tearDown() { + + foreach($this->modules as $module) { + if(!$this->has_dir[$module]) { + rmdir_recursive("custom/modules/{$module}"); + } else { + $files = array('editviewdefs','detailviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.bak", "custom/modules/{$module}/metadata/{$file}.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$module}.php.suback.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.bak", "custom/modules/{$module}/metadata/{$file}.php.suback.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.php"); + } + } + } + } //foreach +} + + +function test_project_merge() { + require_once('modules/UpgradeWizard/SugarMerge/SugarMerge.php'); + $sugar_merge = new SugarMerge('tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom'); + $sugar_merge->mergeModule('Project'); + $this->assertTrue(file_exists('custom/modules/Project/metadata/detailviewdefs.php.suback.php')); + $this->assertTrue(file_exists('custom/modules/Project/metadata/editviewdefs.php.suback.php')); + require('custom/modules/Project/metadata/detailviewdefs.php'); + $this->assertTrue(isset($viewdefs['Project']['DetailView']['panels']['lbl_panel_1']), 'Assert that the original panel index is preserved'); + require('custom/modules/Project/metadata/editviewdefs.php'); + $this->assertTrue(isset($viewdefs['Project']['EditView']['panels']['default']), 'Assert that the original panel index is preserved'); +} + + +} +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/Bug37704Test.php b/tests/modules/UpgradeWizard/SugarMerge/Bug37704Test.php new file mode 100755 index 00000000..ea825639 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/Bug37704Test.php @@ -0,0 +1,118 @@ +modules = array('Accounts'); + $this->has_dir = array(); + + foreach($this->modules as $module) { + if(!file_exists("custom/modules/{$module}/metadata")){ + mkdir_recursive("custom/modules/{$module}/metadata", true); + } + + if(file_exists("custom/modules/{$module}")) { + $this->has_dir[$module] = true; + } + + $files = array('detailviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}")) { + copy("custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php.bak"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.php", "custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } + + if(file_exists("tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/{$module}/metadata/{$file}.php")) { + copy("tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php"); + } + } //foreach + } //foreach +} + + +function tearDown() { + + foreach($this->modules as $module) { + if(!$this->has_dir[$module]) { + rmdir_recursive("custom/modules/{$module}"); + } else { + $files = array('detailviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.bak", "custom/modules/{$module}/metadata/{$file}.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$module}.php.suback.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.bak", "custom/modules/{$module}/metadata/{$file}.php.suback.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.php"); + } + } + } + } //foreach +} + + +function test_accounts_detailview_merge() { + require_once 'modules/UpgradeWizard/SugarMerge/DetailViewMerge.php'; + $this->merge = new DetailViewMerge(); + $this->merge->merge('Accounts', 'tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/detailviewdefs.php', 'modules/Accounts/metadata/detailviewdefs.php', 'custom/modules/Accounts/metadata/detailviewdefs.php'); + $this->assertTrue(file_exists('custom/modules/Accounts/metadata/detailviewdefs.php.suback.php')); + require('custom/modules/Accounts/metadata/detailviewdefs.php'); + $fields = array(); + $panels = array(); + + //echo var_export($viewdefs['Accounts']['DetailView']['panels'], true); + $columns_sanitized = true; + + $date_entered_field = ''; + $date_modified_field = ''; + $blank = 0; + + foreach($viewdefs['Accounts']['DetailView']['panels'] as $panel_key=>$panel) { + $panels[$panel_key] = $panel_key; + foreach($panel as $r=>$row) { + $new_row = true; + foreach($row as $col_key=>$col) { + if($new_row && $col_key != 0) { + $columns_sanitized = false; + } + + $new_row = false; + + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $fields[$id] = $col; + } else { + $blank++; + } + + if($id == 'date_entered') { + $date_entered_field = $col; + } else if($id == 'date_modified') { + $date_modified_field = $col; + } + } + } + } + + $this->assertTrue(count($fields) == 15, "Assert that there are 15 fields found"); + $this->assertTrue($blank == 4, "Assert that there are 4 filler fields"); + +} + + +} +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/Bug37725Test.php b/tests/modules/UpgradeWizard/SugarMerge/Bug37725Test.php new file mode 100755 index 00000000..7725c360 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/Bug37725Test.php @@ -0,0 +1,120 @@ +modules = array('Meetings'); + $this->has_dir = array(); + + foreach($this->modules as $module) { + if(!file_exists("custom/modules/{$module}/metadata")){ + mkdir_recursive("custom/modules/{$module}/metadata", true); + } + + if(file_exists("custom/modules/{$module}")) { + $this->has_dir[$module] = true; + } + + $files = array('detailviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}")) { + copy("custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php.bak"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.php", "custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } + + if(file_exists("tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/{$module}/metadata/{$file}.php")) { + copy("tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php"); + } + } //foreach + } //foreach +} + + +function tearDown() { + + foreach($this->modules as $module) { + if(!$this->has_dir[$module]) { + rmdir_recursive("custom/modules/{$module}"); + } else { + $files = array('detailviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.bak", "custom/modules/{$module}/metadata/{$file}.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$module}.php.suback.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.bak", "custom/modules/{$module}/metadata/{$file}.php.suback.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.php"); + } + } + } + } //foreach +} + + +function test_meetings_detailview_merge() { + require_once 'modules/UpgradeWizard/SugarMerge/DetailViewMerge.php'; + $this->merge = new DetailViewMerge(); + $this->merge->merge('Meetings', 'tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/551/modules/Meetings/metadata/detailviewdefs.php', 'modules/Meetings/metadata/detailviewdefs.php', 'custom/modules/Meetings/metadata/detailviewdefs.php'); + $this->assertTrue(file_exists('custom/modules/Meetings/metadata/detailviewdefs.php.suback.php')); + require('custom/modules/Meetings/metadata/detailviewdefs.php'); + $fields = array(); + $panels = array(); + + //echo var_export($viewdefs['Meetings']['DetailView']['panels'], true); + $columns_sanitized = true; + + $date_entered_field = ''; + $date_modified_field = ''; + + foreach($viewdefs['Meetings']['DetailView']['panels'] as $panel_key=>$panel) { + $panels[$panel_key] = $panel_key; + foreach($panel as $r=>$row) { + $new_row = true; + foreach($row as $col_key=>$col) { + if($new_row && $col_key != 0) { + $columns_sanitized = false; + } + + $new_row = false; + + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $fields[$id] = $col; + } + + if($id == 'date_entered') { + $date_entered_field = $col; + } else if($id == 'date_modified') { + $date_modified_field = $col; + } + } + } + } + + $this->assertTrue(isset($fields['meetings_opportunities_name']), "Assert that meetings_opportunities_name field is preserved"); + $this->assertTrue($viewdefs['Meetings']['DetailView']['panels']['default'][0][0]['name'] == 'name', "Assert that position of name field has not changed"); + $this->assertTrue($viewdefs['Meetings']['DetailView']['panels']['default'][0][1]['name'] == 'status', "Assert that position of status field has not changed"); + $this->assertTrue(isset($fields['date_modified']), "Assert that date_modified field is added"); + $this->assertTrue(isset($fields['date_entered']), "Assert that date_entered field is added"); + $this->assertTrue(!isset($fields['created_by_name']), "Assert that the created_by_name was merged"); + $this->assertTrue(isset($date_entered_field) && $date_entered_field['customCode'] == '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}', "Assert that date_entered field is correctly merged"); + $this->assertTrue(isset($date_modified_field) && $date_modified_field['label'] == 'LBL_DATE_MODIFIED' && $date_modified_field['customCode'] == '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', "Assert that date_modified field is correctly merged"); +} + + +} +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/Bug37841Test.php b/tests/modules/UpgradeWizard/SugarMerge/Bug37841Test.php new file mode 100755 index 00000000..d1447724 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/Bug37841Test.php @@ -0,0 +1,147 @@ +modules = array('Accounts'); + $this->has_dir = array(); + + foreach($this->modules as $module) { + if(!file_exists("custom/modules/{$module}/metadata")){ + mkdir_recursive("custom/modules/{$module}/metadata", true); + } + + if(file_exists("custom/modules/{$module}")) { + $this->has_dir[$module] = true; + } + } //foreach + $this->clearFilesInDirectory('custom/modules/Accounts/metadata'); + $this->clearFilesInDirectory('custom/history/modules/Accounts/metadata'); + } + + + function tearDown() { + $this->clearFilesInDirectory('custom/history/modules/Accounts/metadata'); + foreach($this->modules as $module) { + if(!$this->has_dir[$module]) { + rmdir_recursive("custom/modules/{$module}"); + } else { + $files = array('editviewdefs','detailviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.bak", "custom/modules/{$module}/metadata/{$file}.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$module}.php.suback.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.bak", "custom/modules/{$module}/metadata/{$file}.php.suback.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.php"); + } + } + } + } //foreach + } + + + + /** + * Ensure that no custom metadata is created and no history item created. + * + */ + function testHistoryCreationForNonUpgradedMetadataFiles() + { + $this->clearFilesInDirectory('custom/modules/Accounts/metadata'); + $this->clearFilesInDirectory('custom/history/modules/Accounts/metadata'); + require_once('modules/UpgradeWizard/SugarMerge/SugarMerge.php'); + $sugar_merge = new SugarMerge('tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/610/oob'); + + //Using oob defs make sure nothing is merged + $mergedFiles = $sugar_merge->mergeModule('Accounts'); + $this->assertFalse(file_exists('custom/modules/Accounts/metadata/detailviewdefs.php')); + $this->assertFalse($this->checkForHistoryRecords('Accounts')); + } + + /** + * Ensure that a history item is created when SugarMerge executes and that the file contents are identical. + * + */ + function testHistoryCreationForUpgradedMetadataFiles() + { + + $accountsHistoryMetadataLocation = 'custom/history/modules/Accounts/metadata'; + $this->clearFilesInDirectory('custom/modules/Accounts/metadata'); + $this->clearFilesInDirectory($accountsHistoryMetadataLocation); + $customFile = "tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/610/custom/modules/Accounts/metadata/detailviewdefs.php"; + $customFileTo = "custom/modules/Accounts/metadata/detailviewdefs.php"; + copy($customFile, $customFileTo); + require_once('modules/UpgradeWizard/SugarMerge/SugarMerge.php'); + $sugar_merge = new SugarMerge('tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/610/custom'); + $mergedFiles = $sugar_merge->mergeModule('Accounts'); + + $this->assertTrue(file_exists('custom/modules/Accounts/metadata/detailviewdefs.php'), "Custom metadata file not created."); + $this->assertTrue($this->checkForHistoryRecords('Accounts')); + //Ensure history file and custom file are the same. + $oldCustomFile = file_get_contents($customFile); + $newHistoryFile = $this->getFirstFileContentsInDirectory($accountsHistoryMetadataLocation); + $this->assertEquals($oldCustomFile, $newHistoryFile, "Error previous custom file before merge and new history record are not identical."); + } + + + private function clearFilesInDirectory($path) + { + $dir_handle = @opendir($path); + if ($dir_handle === false) + return; + while (($filename = readdir($dir_handle)) !== false) + { + if ($filename == '.' || $filename == '..') + continue; + else + unlink("{$path}/{$filename}"); + } + } + + private function getFirstFileContentsInDirectory($path) + { + $results = ""; + $dir_handle = opendir($path); + if ($dir_handle === false) + return ""; + while (($filename = readdir($dir_handle)) !== false) + { + if ($filename == '.' || $filename == '..') + continue; + else + return file_get_contents("{$path}/{$filename}"); + } + return $results; + } + private function checkForHistoryRecords($module_dir) + { + $parth = "custom/history/modules/$module_dir/metadata"; + $dir_handle = @opendir($parth); + if ($dir_handle === false) + return FALSE; + $found = FALSE; + while (($filename = readdir($dir_handle)) !== false) + { + if ($filename == '.' || $filename == '..') + continue; + else + return TRUE; + } + return $found; + } +} +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/Bug37850Test.php b/tests/modules/UpgradeWizard/SugarMerge/Bug37850Test.php new file mode 100755 index 00000000..8283555b --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/Bug37850Test.php @@ -0,0 +1,66 @@ +assertTrue(file_exists('custom/modules/Leads/metadata/detailviewdefs.php')); + require('custom/modules/Leads/metadata/detailviewdefs.php'); + $pre_upgrade_fields = array(); + $pre_upgrade_panels = array(); + foreach($viewdefs['Leads']['DetailView']['panels'] as $panel_key=>$panel) { + $pre_upgrade_panels[$panel_key] = $panel_key; + foreach($panel as $row) { + foreach($row as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $pre_upgrade_fields[$id] = $col; + } + } + } + } + + $this->assertTrue(isset($pre_upgrade_fields['created_by']), 'Assert that the created_by index existed in 551 metadata file'); + $this->assertTrue(!isset($pre_upgrade_fields['date_entered']), 'Assert that the date_entered did not exist in 551 metadata file'); + + require_once('modules/UpgradeWizard/SugarMerge/DetailViewMerge.php'); + $this->merge = new DetailViewMerge(); + $this->merge->merge('Leads', 'tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Leads/metadata/detailviewdefs.php', 'modules/Leads/metadata/detailviewdefs.php', 'custom/modules/Leads/metadata/detailviewdefs.php'); + $this->assertTrue(file_exists('custom/modules/Leads/metadata/detailviewdefs.php.suback.php')); + require('custom/modules/Leads/metadata/detailviewdefs.php'); + $fields = array(); + $new_fields = array(); + foreach($viewdefs['Leads']['DetailView']['panels'] as $panel) { + foreach($panel as $row) { + foreach($row as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + $fields[$id] = $col; + if(!empty($id) && !isset($pre_upgrade_fields[$id])) { + $new_fields[$id] = $id; + } + } + } + } + + $this->assertTrue(!isset($new_fields['created_by']), 'Assert that the created_by index does not exists in the merged metadata file'); + $this->assertTrue(isset($new_fields['date_entered']), 'Assert that the date_entered field now exists in the merged metadata file'); +} + + + + +} + +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/Bug37862Test.php b/tests/modules/UpgradeWizard/SugarMerge/Bug37862Test.php new file mode 100755 index 00000000..acaee13c --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/Bug37862Test.php @@ -0,0 +1,127 @@ +modules = array('Contacts'); + $this->has_dir = array(); + + foreach($this->modules as $module) { + if(!file_exists("custom/modules/{$module}/metadata")){ + mkdir_recursive("custom/modules/{$module}/metadata", true); + } + + if(file_exists("custom/modules/{$module}")) { + $this->has_dir[$module] = true; + } + + $files = array('searchdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}")) { + copy("custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php.bak"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.php", "custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } + + if(file_exists("tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/{$module}/metadata/{$file}.php")) { + copy("tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php"); + } + } //foreach + } //foreach +} + + +function tearDown() { + + foreach($this->modules as $module) { + if(!$this->has_dir[$module]) { + rmdir_recursive("custom/modules/{$module}"); + } else { + $files = array('searchdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.bak", "custom/modules/{$module}/metadata/{$file}.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$module}.php.suback.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.bak", "custom/modules/{$module}/metadata/{$file}.php.suback.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.php"); + } + } + } + } //foreach +} + + +function test_contacts_searchdefs_merge() { + require('custom/modules/Contacts/metadata/searchdefs.php'); + $original_basic_fields = array(); + + //echo var_export($searchdefs, true); + foreach($searchdefs['Contacts']['layout']['basic_search'] as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $original_basic_fields[$id] = $col; + } + } + + $original_advanced_fields = array(); + foreach($searchdefs['Contacts']['layout']['advanced_search'] as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id)) { + $original_advanced_fields[$id] = $col; + } + } + + + require_once 'modules/UpgradeWizard/SugarMerge/SearchMerge.php'; + $this->merge = new SearchMerge(); + $this->merge->merge('Contacts', 'tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Contacts/metadata/searchdefs.php', 'modules/Contacts/metadata/searchdefs.php', 'custom/modules/Contacts/metadata/searchdefs.php'); + $this->assertTrue(file_exists('custom/modules/Contacts/metadata/searchdefs.php.suback.php')); + require('custom/modules/Contacts/metadata/searchdefs.php'); + $fields = array(); + + //echo var_export($searchdefs, true); + foreach($searchdefs['Contacts']['layout']['basic_search'] as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $fields[$id] = $col; + } + } + + //echo var_export($original_basic_fields, true); + //echo var_export($fields, true); + //echo var_export(array_diff(array_keys($fields), array_keys($original_basic_fields)), true); + + + $this->assertTrue(count($fields) == 5, "Assert that there are 5 fields in the basic_search layout for Contacts metadata"); + $this->assertTrue(count(array_diff(array_keys($fields), array_keys($original_basic_fields))) == 0, 'Assert that there is no difference between original basic search and merged basic search Array'); + + + $fields = array(); + foreach($searchdefs['Contacts']['layout']['advanced_search'] as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id)) { + $fields[$id] = $col; + } + } + + $this->assertTrue(count($fields) == 16, "Assert that there are 18 fields in the advanced_search layout for Contacts metadata"); + $this->assertTrue(count(array_diff(array_keys($fields), array_keys($original_advanced_fields))) == 0, 'Assert that there is no difference between original advanced search and merged advanced search Array'); +} + + +} +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/Bug37917Test.php b/tests/modules/UpgradeWizard/SugarMerge/Bug37917Test.php new file mode 100755 index 00000000..e1a9721f --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/Bug37917Test.php @@ -0,0 +1,48 @@ +merge = new EditViewMerge(); + $this->merge->merge('Contacts', 'tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Contacts/metadata/editviewdefs.php', 'modules/Contacts/metadata/editviewdefs.php', 'custom/modules/Contacts/metadata/editviewdefs.php'); + $this->assertTrue(file_exists('custom/modules/Contacts/metadata/editviewdefs.php.suback.php')); + require('custom/modules/Contacts/metadata/editviewdefs.php'); + $fields = array(); + $panels = array(); + + //echo var_export($viewdefs['Contacts']['EditView']['panels'], true); + foreach($viewdefs['Contacts']['EditView']['panels'] as $panel_key=>$panel) { + $panels[$panel_key] = $panel_key; + foreach($panel as $r=>$row) { + $new_row = true; + foreach($row as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $fields[$id] = $col; + } + } + } + } + + $this->assertTrue(isset($fields['alt_address_postalcode']) && isset($fields['alt_address_city']), 'Assert that alt_address_postalcode and alt_address_city are preserved'); + $this->assertTrue(isset($fields['alt_address_street']) && !isset($fields['alt_address_street']['displayParams']), 'Assert that the original alt_address_street field contents were preserved'); + $this->assertTrue(isset($fields['primary_address_postalcode']) && isset($fields['primary_address_city']), 'Assert that primary_address_postalcode and primary_address_city are preserved'); + $this->assertTrue(isset($fields['primary_address_street']) && !isset($fields['primary_address_street']['displayParams']), 'Assert that the original primary_address_street field contents were preserved'); +} + + +} + +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/Bug37921Test.php b/tests/modules/UpgradeWizard/SugarMerge/Bug37921Test.php new file mode 100755 index 00000000..94fff13c --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/Bug37921Test.php @@ -0,0 +1,48 @@ +merge = new SearchMerge(); + $this->merge->merge('Notes', 'tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Notes/metadata/searchdefs.php', 'modules/Notes/metadata/searchdefs.php', 'custom/modules/Notes/metadata/searchdefs.php'); + $this->assertTrue(file_exists('custom/modules/Notes/metadata/searchdefs.php.suback.php')); + require('custom/modules/Notes/metadata/searchdefs.php'); + $fields = array(); + + + foreach($searchdefs['Notes']['layout']['basic_search'] as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $fields[$id] = $col; + } + } + + $this->assertTrue(count($fields) == 2, "Assert that there are 2 fields in the basic_search layout for Notes metadata"); + + $fields = array(); + foreach($searchdefs['Notes']['layout']['advanced_search'] as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id)) { + $fields[$id] = $col; + } + } + $this->assertTrue(count($fields) == 7, "Assert that there are 7 fields in the advanced_search layout for Notes metadata"); +} + + +} +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/Bug39057Test.php b/tests/modules/UpgradeWizard/SugarMerge/Bug39057Test.php new file mode 100755 index 00000000..1573a339 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/Bug39057Test.php @@ -0,0 +1,57 @@ +$col) { + $original_fields[$col_key] = $col; + if(isset($col['default']) && $col['default']) { + $original_displayed_fields[$col_key] = $col; + } + } + + require_once 'modules/UpgradeWizard/SugarMerge/ListViewMerge.php'; + $this->merge = new ListViewMerge(); + $this->merge->merge('Opportunities', 'tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/554/modules/Opportunities/metadata/listviewdefs.php', 'modules/Opportunities/metadata/listviewdefs.php', 'custom/modules/Opportunities/metadata/listviewdefs.php'); + $this->assertTrue(file_exists('custom/modules/Opportunities/metadata/listviewdefs.php.suback.php')); + require('custom/modules/Opportunities/metadata/listviewdefs.php'); + $fields = array(); + $displayed_fields = array(); + foreach($listViewDefs['Opportunities'] as $col_key=>$col) { + $fields[$col_key] = $col; + if(isset($col['default']) && $col['default']) { + $displayed_fields[$col_key] = $col; + } + } + + //echo var_export($displayed_fields, true); + + $this->assertTrue(isset($original_displayed_fields['AMOUNT_USDOLLAR']['label'])); + $this->assertTrue(isset($displayed_fields['AMOUNT_USDOLLAR']['label'])); + //This tests to ensure that the label value is the same from the custom file even though in the new + //file we changed the label value, we should preserve the custom value + if(isset($original_displayed_fields['AMOUNT_USDOLLAR']['label']) && isset($displayed_fields['AMOUNT_USDOLLAR']['label'])) + { + $this->assertNotEquals($original_displayed_fields['AMOUNT_USDOLLAR']['label'], $displayed_fields['AMOUNT_USDOLLAR']['label']); + } +} + + +} +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/Bug39059Test.php b/tests/modules/UpgradeWizard/SugarMerge/Bug39059Test.php new file mode 100755 index 00000000..27113bc9 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/Bug39059Test.php @@ -0,0 +1,38 @@ +allow_call_time_pass_reference = ini_get('allow_call_time_pass_reference'); +} + + +function tearDown() { + SugarTestMergeUtilities::teardownFiles(); + ini_set('allow_call_time_pass_reference', $this->allow_call_time_pass_reference); +} + + +function test_600_leads_detailview_merge() { + require('custom/modules/Leads/metadata/detailviewdefs.php'); + $this->assertTrue(!isset($viewdefs['Leads']['DetailView']['panels']['default'])); + ini_set('allow_call_time_pass_reference', 'Off'); + require_once('modules/UpgradeWizard/SugarMerge/DetailViewMerge.php'); + $this->merge = new DetailViewMerge(); + $this->merge->merge('Leads', 'tests/modules/UpgradeWizard/SugarMerge/cit_metadata_files/554/modules/Leads/metadata/detailviewdefs.php', 'modules/Leads/metadata/detailviewdefs.php', 'custom/modules/Leads/metadata/detailviewdefs.php'); + $this->assertTrue(file_exists('custom/modules/Leads/metadata/detailviewdefs.php.suback.php')); + require('custom/modules/Leads/metadata/detailviewdefs.php'); + $this->assertTrue(isset($viewdefs['Leads']['DetailView']['panels']['default'])); +} + + + + +} + +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/LeadsMergeTest.php b/tests/modules/UpgradeWizard/SugarMerge/LeadsMergeTest.php new file mode 100755 index 00000000..49c04e56 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/LeadsMergeTest.php @@ -0,0 +1,169 @@ +modules = array('Leads'); + $this->has_dir = array(); + + foreach($this->modules as $module) { + if(!file_exists("custom/modules/{$module}/metadata")){ + mkdir_recursive("custom/modules/{$module}/metadata", true); + } + + if(file_exists("custom/modules/{$module}")) { + $this->has_dir[$module] = true; + } + + $files = array('detailviewdefs', 'editviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}")) { + copy("custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php.bak"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.php", "custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } + + if(file_exists("tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/{$module}/metadata/{$file}.php")) { + copy("tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/{$module}/metadata/{$file}.php", "custom/modules/{$module}/metadata/{$file}.php"); + } + } //foreach + } //foreach +} + + +function tearDown() { + + foreach($this->modules as $module) { + if(!$this->has_dir[$module]) { + rmdir_recursive("custom/modules/{$module}"); + } else { + $files = array('detailviewdefs', 'editviewdefs'); + foreach($files as $file) { + if(file_exists("custom/modules/{$module}/metadata/{$file}.php.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.bak", "custom/modules/{$module}/metadata/{$file}.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php"); + } + + if(file_exists("custom/modules/{$module}/metadata/{$module}.php.suback.bak")) { + copy("custom/modules/{$module}/metadata/{$file}.php.suback.bak", "custom/modules/{$module}/metadata/{$file}.php.suback.php"); + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.bak"); + } else if(file_exists("custom/modules/{$module}/metadata/{$file}.php.suback.php")) { + unlink("custom/modules/{$module}/metadata/{$file}.php.suback.php"); + } + } + } + } //foreach +} + +/* +function test_600_leads_detailview_merge() { + $this->assertTrue(file_exists('custom/modules/Leads/metadata/detailviewdefs.php')); + require('custom/modules/Leads/metadata/detailviewdefs.php'); + $pre_upgrade_fields = array(); + $pre_upgrade_panels = array(); + foreach($viewdefs['Leads']['DetailView']['panels'] as $panel_key=>$panel) { + $pre_upgrade_panels[$panel_key] = $panel_key; + foreach($panel as $row) { + foreach($row as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $pre_upgrade_fields[$id] = $col; + } + } + } + } + + require_once('modules/UpgradeWizard/SugarMerge/DetailViewMerge.php'); + $this->merge = new DetailViewMerge(); + $this->merge->merge('Leads', 'tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Leads/metadata/detailviewdefs.php', 'modules/Leads/metadata/detailviewdefs.php', 'custom/modules/Leads/metadata/detailviewdefs.php'); + $this->assertTrue(file_exists('custom/modules/Leads/metadata/detailviewdefs.php.suback.php')); + require('custom/modules/Leads/metadata/detailviewdefs.php'); + $fields = array(); + $new_fields = array(); + foreach($viewdefs['Leads']['DetailView']['panels'] as $panel) { + foreach($panel as $row) { + foreach($row as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + $fields[$id] = $col; + if(!empty($id) && !isset($pre_upgrade_fields[$id])) { + $new_fields[$id] = $id; + } + } + } + } + + //echo var_export($new_fields, true); + //echo var_export($viewdefs['Leads']['DetailView']['panels'], true); + $this->assertTrue(count($new_fields) == 1 && isset($new_fields['website']), 'Assert that website was the only field added'); + $this->assertTrue(isset($fields['website']), 'Assert that website field was added'); + + $panel_keys = array_keys($viewdefs['Leads']['DetailView']['panels']); + $end_key = end($panel_keys); + + $end_row = end(array_keys($viewdefs['Leads']['DetailView']['panels'][$end_key])); + $this->assertTrue($viewdefs['Leads']['DetailView']['panels'][$end_key][$end_row][0] == 'website', 'Assert that website field was added to new space in new row'); +} +*/ + +function test_600_leads_editview_merge() { + + $this->assertTrue(file_exists('custom/modules/Leads/metadata/editviewdefs.php')); + require('custom/modules/Leads/metadata/editviewdefs.php'); + $pre_upgrade_fields = array(); + $pre_upgrade_panels = array(); + foreach($viewdefs['Leads']['EditView']['panels'] as $panel_key=>$panel) { + foreach($panel as $row) { + foreach($row as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + if(!empty($id) && !is_array($id)) { + $pre_upgrade_fields[$id] = $col; + } + } + } + } + + require_once('modules/UpgradeWizard/SugarMerge/EditViewMerge.php'); + $this->merge = new EditViewMerge(); + $this->merge->merge('Leads', 'tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Leads/metadata/editviewdefs.php', 'modules/Leads/metadata/editviewdefs.php', 'custom/modules/Leads/metadata/editviewdefs.php'); + $this->assertTrue(file_exists('custom/modules/Leads/metadata/editviewdefs.php.suback.php')); + require('custom/modules/Leads/metadata/editviewdefs.php'); + $fields = array(); + $new_fields = array(); + foreach($viewdefs['Leads']['EditView']['panels'] as $panel) { + foreach($panel as $row) { + foreach($row as $col_key=>$col) { + $id = is_array($col) && isset($col['name']) ? $col['name'] : $col; + + if(empty($id) || !is_string($id)) { + continue; + } + + $fields[$id] = $col; + if(!isset($pre_upgrade_fields[$id])) { + $new_fields[$id] = $id; + } + } + } + } + + //echo var_export($new_fields, true); + //echo var_export($viewdefs['Leads']['EditView'], true); + $this->assertTrue(count($new_fields) == 1 && isset($new_fields['website']), 'Assert that website was the only field added'); + $this->assertTrue(isset($fields['website']), 'Assert that website field was added'); + $end = end(array_keys($viewdefs['Leads']['EditView']['panels']['lbl_description_information'])); + $this->assertTrue(isset($viewdefs['Leads']['EditView']['panels']['lbl_description_information'][$end][0]) && ($viewdefs['Leads']['EditView']['panels']['lbl_description_information'][$end][0] == 'website'), 'Assert that website field was added to new space in row on lbl_description_information panel'); +} + + +} + +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/detailviewdefs.php new file mode 100755 index 00000000..78654b23 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/detailviewdefs.php @@ -0,0 +1,216 @@ + array('form' => array('buttons'=>array('EDIT', 'DUPLICATE', 'DELETE', 'FIND_DUPLICATES', + array('customCode'=>''), + ), + ), + 'maxColumns' => '2', + 'widths' => array( + array('label' => '10', 'field' => '30'), + array('label' => '10', 'field' => '30') + ), + + 'includes'=> array( + array('file'=>'modules/Leads/Lead.js'), + ), + ), + + + + 'panels' => + array ( + 'lbl_contact_information' => + array ( + + array ( + + array ( + 'name' => 'full_name', + 'label' => 'LBL_NAME', + ), + + ), + + array ( + + array ( + 'name' => 'title', + 'comment' => 'The title of the contact', + 'label' => 'LBL_TITLE', + ), + array ( + 'name' => 'phone_mobile', + 'label' => 'LBL_MOBILE_PHONE', + ), + + ), + + array ( + 'department', + array ( + 'name' => 'phone_work', + 'label' => 'LBL_OFFICE_PHONE', + ), + ), + + array ( + array ( + 'name' => 'account_name', + 'label' => 'LBL_ACCOUNT_NAME', + ), + array ( + 'name' => 'phone_fax', + 'label' => 'LBL_FAX_PHONE', + ), + ), + + array ( + + array ( + 'name' => 'primary_address_street', + 'label' => 'LBL_PRIMARY_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'primary', + ), + ), + + array ( + 'name' => 'alt_address_street', + 'label' => 'LBL_ALTERNATE_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'alt', + ), + ), + ), + + array ( + + array ( + 'name' => 'email1', + 'studio' => 'false', + 'label' => 'LBL_EMAIL_ADDRESS', + ), + ), + + array ( + + array ( + 'name' => 'description', + 'comment' => 'Full text of the note', + 'label' => 'LBL_DESCRIPTION', + ), + ), + ), + + 'LBL_PANEL_ADVANCED' => + array ( + + array ( + + array ( + 'name' => 'report_to_name', + 'label' => 'LBL_REPORTS_TO', + ), + + array ( + 'name' => 'sync_contact', + 'comment' => 'Synch to outlook? (Meta-Data only)', + 'label' => 'LBL_SYNC_CONTACT', + ), + ), + + array ( + + array ( + 'name' => 'lead_source', + 'comment' => 'How did the contact come about', + 'label' => 'LBL_LEAD_SOURCE', + ), + + array ( + 'name' => 'do_not_call', + 'comment' => 'An indicator of whether contact can be called', + 'label' => 'LBL_DO_NOT_CALL', + ), + ), + + array ( + + array ( + 'name' => 'campaign_name', + 'label' => 'LBL_CAMPAIGN', + ), + + ), + + + ), + 'LBL_PANEL_ASSIGNMENT' => + array ( + + array ( + + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO_NAME', + ), + + array ( + 'name' => 'date_modified', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', + 'label' => 'LBL_DATE_MODIFIED', + ), + ), + + array ( + + array ( + 'name' => 'date_entered', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}', + 'label' => 'LBL_DATE_ENTERED', + ), + + ), + ), + ) +); +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/editviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/editviewdefs.php new file mode 100755 index 00000000..327147a8 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/editviewdefs.php @@ -0,0 +1,220 @@ + array('form'=>array('hidden'=>array('', + '', + '', + '', + '')), + 'maxColumns' => '2', + 'widths' => array( + array('label' => '10', 'field' => '30'), + array('label' => '10', 'field' => '30'), + ), +), + + + 'panels' => + array ( + 'lbl_contact_information' => + array ( + array ( + array ( + 'name' => 'first_name', + 'customCode' => '{html_options name="salutation" options=$fields.salutation.options selected=$fields.salutation.value} ', + ), + + + ), + array ( + array ( + 'name' => 'last_name', + 'displayParams' => + array ( + 'required' => true, + ), + ), + array ( + 'name' => 'phone_mobile', + 'comment' => 'Mobile phone number of the contact', + 'label' => 'LBL_MOBILE_PHONE', + ), + ), + + array ( + + array ( + 'name' => 'title', + 'comment' => 'The title of the contact', + 'label' => 'LBL_TITLE', + ), + + array ( + 'name' => 'phone_work', + 'comment' => 'Work phone number of the contact', + 'label' => 'LBL_OFFICE_PHONE', + ), + + ), + + array ( + 'department', + array ( + 'name' => 'phone_fax', + 'comment' => 'Contact fax number', + 'label' => 'LBL_FAX_PHONE', + ), + ), + array( + array ( + 'name' => 'account_name', + 'displayParams' => + array ( + 'key' => 'billing', + 'copy' => 'primary', + 'billingKey' => 'primary', + 'additionalFields' => + array ( + 'phone_office' => 'phone_work', + ), + ), + ), + ), + + array ( + + array ( + 'name' => 'primary_address_street', + 'hideLabel' => true, + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'primary', + 'rows' => 2, + 'cols' => 30, + 'maxlength' => 150, + ), + ), + + array ( + 'name' => 'alt_address_street', + 'hideLabel' => true, + 'colspan' => 2, + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'alt', + 'copy' => 'primary', + 'rows' => 2, + 'cols' => 30, + 'maxlength' => 150, + ), + ), + ), + + array ( + + array ( + 'name' => 'email1', + 'studio' => 'false', + 'label' => 'LBL_EMAIL_ADDRESS', + ), + ), + + array ( + + array ( + 'name' => 'description', + 'label' => 'LBL_DESCRIPTION', + ), + ), + ), + + + 'LBL_PANEL_ADVANCED' => + array ( + + array ( + + array ( + 'name' => 'report_to_name', + 'label' => 'LBL_REPORTS_TO', + ), + + array ( + 'name' => 'sync_contact', + 'comment' => 'Synch to outlook? (Meta-Data only)', + 'label' => 'LBL_SYNC_CONTACT', + ), + ), + + array ( + + array ( + 'name' => 'lead_source', + 'comment' => 'How did the contact come about', + 'label' => 'LBL_LEAD_SOURCE', + ), + + array ( + 'name' => 'do_not_call', + 'comment' => 'An indicator of whether contact can be called', + 'label' => 'LBL_DO_NOT_CALL', + ), + ), + + array ( + 'campaign_name', + ), + ), + + + + 'LBL_PANEL_ASSIGNMENT' => + array ( + array ( + + + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO_NAME', + ), + ), + ), + ) +); +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/listviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/listviewdefs.php new file mode 100755 index 00000000..d50d1b99 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/listviewdefs.php @@ -0,0 +1,169 @@ + array( + 'width' => '20%', + 'label' => 'LBL_LIST_NAME', + 'link' => true, + 'contextMenu' => array('objectType' => 'sugarPerson', + 'metaData' => array('contact_id' => '{$ID}', + 'module' => 'Contacts', + 'return_action' => 'ListView', + 'contact_name' => '{$FULL_NAME}', + 'parent_id' => '{$ACCOUNT_ID}', + 'parent_name' => '{$ACCOUNT_NAME}', + 'return_module' => 'Contacts', + 'return_action' => 'ListView', + 'parent_type' => 'Account', + 'notes_parent_type' => 'Account') + ), + 'orderBy' => 'name', + 'default' => true, + 'related_fields' => array('first_name', 'last_name', 'salutation', 'account_name', 'account_id'), + ), + 'TITLE' => array( + 'width' => '15%', + 'label' => 'LBL_LIST_TITLE', + 'default' => true), + 'ACCOUNT_NAME' => array( + 'width' => '34%', + 'label' => 'LBL_LIST_ACCOUNT_NAME', + 'module' => 'Accounts', + 'id' => 'ACCOUNT_ID', + 'link' => true, + 'contextMenu' => array('objectType' => 'sugarAccount', + 'metaData' => array('return_module' => 'Contacts', + 'return_action' => 'ListView', + 'module' => 'Accounts', + 'return_action' => 'ListView', + 'parent_id' => '{$ACCOUNT_ID}', + 'parent_name' => '{$ACCOUNT_NAME}', + 'account_id' => '{$ACCOUNT_ID}', + 'account_name' => '{$ACCOUNT_NAME}'), + ), + 'default' => true, + 'sortable'=> true, + 'ACLTag' => 'ACCOUNT', + 'related_fields' => array('account_id')), + 'EMAIL1' => array( + 'width' => '15%', + 'label' => 'LBL_LIST_EMAIL_ADDRESS', + 'sortable' => false, + 'link' => true, + 'customCode' => '{$EMAIL1_LINK}{$EMAIL1}', + 'default' => true + ), + 'PHONE_WORK' => array( + 'width' => '15%', + 'label' => 'LBL_OFFICE_PHONE', + 'default' => true), + 'DEPARTMENT' => array( + 'width' => '10', + 'label' => 'LBL_DEPARTMENT'), + 'DO_NOT_CALL' => array( + 'width' => '10', + 'label' => 'LBL_DO_NOT_CALL'), + 'PHONE_HOME' => array( + 'width' => '10', + 'label' => 'LBL_HOME_PHONE'), + 'PHONE_MOBILE' => array( + 'width' => '10', + 'label' => 'LBL_MOBILE_PHONE'), + 'PHONE_OTHER' => array( + 'width' => '10', + 'label' => 'LBL_OTHER_PHONE'), + 'PHONE_FAX' => array( + 'width' => '10', + 'label' => 'LBL_FAX_PHONE'), + 'EMAIL2' => array( + 'width' => '15', + 'label' => 'LBL_LIST_EMAIL_ADDRESS', + 'sortable' => false, + 'customCode' => '{$EMAIL2_LINK}{$EMAIL2}'), + 'EMAIL_OPT_OUT' => array( + 'width' => '10', + + 'label' => 'LBL_EMAIL_OPT_OUT'), + 'PRIMARY_ADDRESS_STREET' => array( + 'width' => '10', + 'label' => 'LBL_PRIMARY_ADDRESS_STREET'), + 'PRIMARY_ADDRESS_CITY' => array( + 'width' => '10', + 'label' => 'LBL_PRIMARY_ADDRESS_CITY'), + 'PRIMARY_ADDRESS_STATE' => array( + 'width' => '10', + 'label' => 'LBL_PRIMARY_ADDRESS_STATE'), + 'PRIMARY_ADDRESS_POSTALCODE' => array( + 'width' => '10', + 'label' => 'LBL_PRIMARY_ADDRESS_POSTALCODE'), + 'ALT_ADDRESS_COUNTRY' => array( + 'width' => '10', + 'label' => 'LBL_ALT_ADDRESS_COUNTRY'), + 'ALT_ADDRESS_STREET' => array( + 'width' => '10', + 'label' => 'LBL_ALT_ADDRESS_STREET'), + 'ALT_ADDRESS_CITY' => array( + 'width' => '10', + 'label' => 'LBL_ALT_ADDRESS_CITY'), + 'ALT_ADDRESS_STATE' => array( + 'width' => '10', + 'label' => 'LBL_ALT_ADDRESS_STATE'), + 'ALT_ADDRESS_POSTALCODE' => array( + 'width' => '10', + 'label' => 'LBL_ALT_ADDRESS_POSTALCODE'), + 'ALT_ADDRESS_COUNTRY' => array( + 'width' => '10', + 'label' => 'LBL_ALT_ADDRESS_COUNTRY'), + 'DATE_ENTERED' => array( + 'width' => '10', + 'label' => 'LBL_DATE_ENTERED'), + 'CREATED_BY_NAME' => array( + 'width' => '10', + 'label' => 'LBL_CREATED'), + 'ASSIGNED_USER_NAME' => array( + 'width' => '10', + 'label' => 'LBL_LIST_ASSIGNED_USER', + 'default' => true), + 'MODIFIED_BY_NAME' => array( + 'width' => '10', + 'label' => 'LBL_MODIFIED') +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/popupdefs.php b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/popupdefs.php new file mode 100755 index 00000000..e66fe97c --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/popupdefs.php @@ -0,0 +1,93 @@ + 'Contact', + 'varName' => 'CONTACT', + 'orderBy' => 'contacts.first_name, contacts.last_name', + 'whereClauses' => + array('first_name' => 'contacts.first_name', + 'last_name' => 'contacts.last_name', + 'account_name' => 'accounts.name', + 'account_id' => 'accounts.id'), + 'searchInputs' => + array('first_name', 'last_name', 'account_name'), + 'create' => + array('formBase' => 'ContactFormBase.php', + 'formBaseClass' => 'ContactFormBase', + 'getFormBodyParams' => array('','','ContactSave'), + 'createButton' => $mod_strings['LNK_NEW_CONTACT'] + ), + 'listviewdefs' => array( + 'NAME' => array( + 'width' => '20%', + 'label' => 'LBL_LIST_NAME', + 'link' => true, + 'default' => true, + 'related_fields' => array('first_name', 'last_name', 'salutation', 'account_name', 'account_id')), + 'ACCOUNT_NAME' => array( + 'width' => '25', + 'label' => 'LBL_LIST_ACCOUNT_NAME', + 'module' => 'Accounts', + 'id' => 'ACCOUNT_ID', + 'default' => true, + 'sortable'=> true, + 'ACLTag' => 'ACCOUNT', + 'related_fields' => array('account_id')), + 'TITLE' => array( + 'width' => '15%', + 'label' => 'LBL_LIST_TITLE', + 'default' => true), + 'LEAD_SOURCE' => array( + 'width' => '15%', + 'label' => 'LBL_LEAD_SOURCE', + 'default' => true), + ), + 'searchdefs' => array( + 'first_name', + 'last_name', + array('name' => 'account_name', 'displayParams' => array('hideButtons'=>'true', 'size'=>30, 'class'=>'sqsEnabled sqsNoAutofill')), + 'title', + 'lead_source', + array('name' => 'campaign_name', 'displayParams' => array('hideButtons'=>'true', 'size'=>30, 'class'=>'sqsEnabled sqsNoAutofill')), + array('name' => 'assigned_user_id', 'type' => 'enum', 'label' => 'LBL_ASSIGNED_TO', 'function' => array('name' => 'get_user_array', 'params' => array(false))), + ) + ); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/quickcreatedefs.php b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/quickcreatedefs.php new file mode 100755 index 00000000..dea6a18e --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/quickcreatedefs.php @@ -0,0 +1,147 @@ + + array ( + 'QuickCreate' => + array ( + 'templateMeta' => + array ( + 'form' => + array ( + 'hidden' => + array ( + '', + '', + '', + '', + '', + '', + '', + ), + ), + 'maxColumns' => '2', + 'widths' => + array ( + array ( + 'label' => '10', + 'field' => '30', + ), + array ( + 'label' => '10', + 'field' => '30', + ), + ), + ), + 'panels' => + array ( + 'default' => + array ( + + array ( + + array ( + 'name' => 'first_name', + ), + + array ( + 'name' => 'account_name', + ), + ), + + array ( + + array ( + 'name' => 'last_name', + 'displayParams'=>array('required'=>true), + ), + + array ( + 'name' => 'phone_work', + ), + ), + + array ( + + array ( + 'name' => 'title', + ), + + array ( + 'name' => 'phone_mobile', + ), + ), + + array ( + + array ( + 'name' => 'phone_fax', + ), + + array ( + 'name' => 'do_not_call', + ), + ), + + array ( + array ( + 'name' => 'email1', + ), + array ( + 'name' => 'lead_source', + ), + ), + + array ( + + array ( + 'name' => 'assigned_user_name', + ), + ), + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/searchdefs.php b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/searchdefs.php new file mode 100755 index 00000000..25a67412 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/600/modules/Contacts/metadata/searchdefs.php @@ -0,0 +1,153 @@ + array('maxColumns' => '3', + 'widths' => array('label' => '10', 'field' => '30'), + ), + 'layout' => array ( + 'basic_search' => + array ( + array('name'=>'search_name','label' =>'LBL_NAME', 'type' => 'name'), + array ( + 'name' => 'current_user_only', + 'label' => 'LBL_CURRENT_USER_FILTER', + 'type' => 'bool', + ), + ), + 'advanced_search' => + array ( + 'first_name' => + array ( + 'name' => 'first_name', + 'default' => true, + 'width' => '10%', + ), + 'email' => + array ( + 'name' => 'email', + 'label' => 'LBL_ANY_EMAIL', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'phone' => + array ( + 'name' => 'phone', + 'label' => 'LBL_ANY_PHONE', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'last_name' => + array ( + 'name' => 'last_name', + 'default' => true, + 'width' => '10%', + ), + 'address_street' => + array ( + 'name' => 'address_street', + 'label' => 'LBL_ANY_ADDRESS', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'address_city' => + array ( + 'name' => 'address_city', + 'label' => 'LBL_CITY', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'account_name' => + array ( + 'name' => 'account_name', + 'default' => true, + 'width' => '10%', + ), + 'address_state' => + array ( + 'name' => 'address_state', + 'label' => 'LBL_STATE', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'address_postalcode' => + array ( + 'name' => 'address_postalcode', + 'label' => 'LBL_POSTAL_CODE', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'assigned_user_id' => + array ( + 'name' => 'assigned_user_id', + 'type' => 'enum', + 'label' => 'LBL_ASSIGNED_TO', + 'function' => + array ( + 'name' => 'get_user_array', + 'params' => + array ( + 0 => false, + ), + ), + 'default' => true, + 'width' => '10%', + ), + 'primary_address_country' => + array ( + 'name' => 'primary_address_country', + 'label' => 'LBL_COUNTRY', + 'type' => 'name', + 'options' => 'countries_dom', + 'default' => true, + 'width' => '10%', + ), + 'lead_source' => + array ( + 'name' => 'lead_source', + 'default' => true, + 'width' => '10%', + ), + ), + ) +); +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/detailviewdefs.php new file mode 100755 index 00000000..4d9fb784 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/detailviewdefs.php @@ -0,0 +1,234 @@ + + array ( + 'templateMeta' => + array ( + 'form' => + array ( + 'buttons' => + array ( + 0 => 'EDIT', + 1 => 'DUPLICATE', + 2 => 'DELETE', + 3 => 'FIND_DUPLICATES', + 4 => + array ( + 'customCode' => '', + ), + ), + ), + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + 'includes' => + array ( + 0 => + array ( + 'file' => 'modules/Leads/Lead.js', + ), + ), + 'useTabs' => false, + ), + 'panels' => + array ( + 'lbl_contact_information' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'full_name', + 'label' => 'LBL_NAME', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'phone_mobile', + 'label' => 'LBL_MOBILE_PHONE', + ), + 1 => + array ( + 'name' => 'title', + 'comment' => 'The title of the contact', + 'label' => 'LBL_TITLE', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'department', + 'comment' => 'The department of the contact', + 'label' => 'LBL_DEPARTMENT', + ), + 1 => + array ( + 'name' => 'phone_work', + 'label' => 'LBL_OFFICE_PHONE', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'account_name', + 'label' => 'LBL_ACCOUNT_NAME', + 'displayParams' => + array ( + 'enableConnectors' => true, + 'module' => 'Contacts', + 'connectors' => + array ( + 0 => 'ext_rest_linkedin', + ), + ), + ), + 1 => + array ( + 'name' => 'phone_fax', + 'label' => 'LBL_FAX_PHONE', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'primary_address_street', + 'label' => 'LBL_PRIMARY_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'primary', + ), + ), + 1 => + array ( + 'name' => 'alt_address_street', + 'label' => 'LBL_ALTERNATE_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'alt', + ), + ), + ), + 5 => + array ( + 0 => + array ( + 'name' => 'email1', + 'studio' => 'false', + 'label' => 'LBL_EMAIL_ADDRESS', + ), + ), + 6 => + array ( + 0 => + array ( + 'name' => 'description', + 'comment' => 'Full text of the note', + 'label' => 'LBL_DESCRIPTION', + ), + ), + ), + 'lbl_detailview_panel1' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'test_c', + 'label' => 'LBL_TEST', + ), + 1 => + array ( + 'name' => 'test2_c', + 'label' => 'LBL_TEST2', + ), + ), + ), + 'LBL_PANEL_ADVANCED' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'report_to_name', + 'label' => 'LBL_REPORTS_TO', + ), + 1 => + array ( + 'name' => 'sync_contact', + 'comment' => 'Synch to outlook? (Meta-Data only)', + 'label' => 'LBL_SYNC_CONTACT', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'lead_source', + 'comment' => 'How did the contact come about', + 'label' => 'LBL_LEAD_SOURCE', + ), + 1 => + array ( + 'name' => 'do_not_call', + 'comment' => 'An indicator of whether contact can be called', + 'label' => 'LBL_DO_NOT_CALL', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'campaign_name', + 'label' => 'LBL_CAMPAIGN', + ), + ), + ), + 'LBL_PANEL_ASSIGNMENT' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO_NAME', + ), + 1 => + array ( + 'name' => 'date_modified', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', + 'label' => 'LBL_DATE_MODIFIED', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'date_entered', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}', + 'label' => 'LBL_DATE_ENTERED', + ), + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/editviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/editviewdefs.php new file mode 100755 index 00000000..087bb20f --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/editviewdefs.php @@ -0,0 +1,231 @@ + + array ( + 'templateMeta' => + array ( + 'form' => + array ( + 'hidden' => + array ( + 0 => '', + 1 => '', + 2 => '', + 3 => '', + 4 => '', + ), + ), + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + 'useTabs' => false, + ), + 'panels' => + array ( + 'lbl_contact_information' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'first_name', + 'customCode' => '{html_options name="salutation" options=$fields.salutation.options selected=$fields.salutation.value} ', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'last_name', + 'displayParams' => + array ( + 'required' => true, + ), + ), + 1 => + array ( + 'name' => 'phone_mobile', + 'comment' => 'Mobile phone number of the contact', + 'label' => 'LBL_MOBILE_PHONE', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'title', + 'comment' => 'The title of the contact', + 'label' => 'LBL_TITLE', + ), + 1 => + array ( + 'name' => 'phone_work', + 'comment' => 'Work phone number of the contact', + 'label' => 'LBL_OFFICE_PHONE', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'department', + 'comment' => 'The department of the contact', + 'label' => 'LBL_DEPARTMENT', + ), + 1 => + array ( + 'name' => 'phone_fax', + 'comment' => 'Contact fax number', + 'label' => 'LBL_FAX_PHONE', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'account_name', + 'displayParams' => + array ( + 'key' => 'billing', + 'copy' => 'primary', + 'billingKey' => 'primary', + 'additionalFields' => + array ( + 'phone_office' => 'phone_work', + ), + ), + ), + ), + 5 => + array ( + 0 => + array ( + 'name' => 'primary_address_street', + 'hideLabel' => true, + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'primary', + 'rows' => 2, + 'cols' => 30, + 'maxlength' => 150, + ), + ), + 1 => + array ( + 'name' => 'alt_address_street', + 'hideLabel' => true, + 'colspan' => 2, + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'alt', + 'copy' => 'primary', + 'rows' => 2, + 'cols' => 30, + 'maxlength' => 150, + ), + ), + ), + 6 => + array ( + 0 => + array ( + 'name' => 'email1', + 'studio' => 'false', + 'label' => 'LBL_EMAIL_ADDRESS', + ), + ), + 7 => + array ( + 0 => + array ( + 'name' => 'description', + 'label' => 'LBL_DESCRIPTION', + ), + ), + ), + 'lbl_editview_panel1' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'test_c', + 'label' => 'LBL_TEST', + ), + 1 => + array ( + 'name' => 'test2_c', + 'label' => 'LBL_TEST2', + ), + ), + ), + 'LBL_PANEL_ADVANCED' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'report_to_name', + 'label' => 'LBL_REPORTS_TO', + ), + 1 => + array ( + 'name' => 'sync_contact', + 'comment' => 'Synch to outlook? (Meta-Data only)', + 'label' => 'LBL_SYNC_CONTACT', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'lead_source', + 'comment' => 'How did the contact come about', + 'label' => 'LBL_LEAD_SOURCE', + ), + 1 => + array ( + 'name' => 'do_not_call', + 'comment' => 'An indicator of whether contact can be called', + 'label' => 'LBL_DO_NOT_CALL', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'campaign_name', + 'comment' => 'The first campaign name for Contact (Meta-data only)', + 'label' => 'LBL_CAMPAIGN', + ), + ), + ), + 'LBL_PANEL_ASSIGNMENT' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO_NAME', + ), + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/listviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/listviewdefs.php new file mode 100755 index 00000000..c6d78890 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/listviewdefs.php @@ -0,0 +1,223 @@ + + array ( + 'width' => '20%', + 'label' => 'LBL_LIST_NAME', + 'link' => true, + 'contextMenu' => + array ( + 'objectType' => 'sugarPerson', + 'metaData' => + array ( + 'contact_id' => '{$ID}', + 'module' => 'Contacts', + 'return_action' => 'ListView', + 'contact_name' => '{$FULL_NAME}', + 'parent_id' => '{$ACCOUNT_ID}', + 'parent_name' => '{$ACCOUNT_NAME}', + 'return_module' => 'Contacts', + 'parent_type' => 'Account', + 'notes_parent_type' => 'Account', + ), + ), + 'orderBy' => 'name', + 'default' => true, + 'related_fields' => + array ( + 0 => 'first_name', + 1 => 'last_name', + 2 => 'salutation', + 3 => 'account_name', + 4 => 'account_id', + ), + ), + 'TEST_C' => + array ( + 'type' => 'varchar', + 'default' => true, + 'label' => 'LBL_TEST', + 'width' => '10%', + ), + 'TEST2_C' => + array ( + 'type' => 'varchar', + 'default' => true, + 'label' => 'LBL_TEST2', + 'width' => '10%', + ), + 'TITLE' => + array ( + 'width' => '15%', + 'label' => 'LBL_LIST_TITLE', + 'default' => true, + ), + 'ACCOUNT_NAME' => + array ( + 'width' => '34%', + 'label' => 'LBL_LIST_ACCOUNT_NAME', + 'module' => 'Accounts', + 'id' => 'ACCOUNT_ID', + 'link' => true, + 'contextMenu' => + array ( + 'objectType' => 'sugarAccount', + 'metaData' => + array ( + 'return_module' => 'Contacts', + 'return_action' => 'ListView', + 'module' => 'Accounts', + 'parent_id' => '{$ACCOUNT_ID}', + 'parent_name' => '{$ACCOUNT_NAME}', + 'account_id' => '{$ACCOUNT_ID}', + 'account_name' => '{$ACCOUNT_NAME}', + ), + ), + 'default' => true, + 'sortable' => true, + 'ACLTag' => 'ACCOUNT', + 'related_fields' => + array ( + 0 => 'account_id', + ), + ), + 'EMAIL1' => + array ( + 'width' => '15%', + 'label' => 'LBL_LIST_EMAIL_ADDRESS', + 'sortable' => false, + 'link' => true, + 'customCode' => '{$EMAIL1_LINK}{$EMAIL1}', + 'default' => true, + ), + 'PHONE_WORK' => + array ( + 'width' => '15%', + 'label' => 'LBL_OFFICE_PHONE', + 'default' => true, + ), + 'ASSIGNED_USER_NAME' => + array ( + 'width' => '10%', + 'label' => 'LBL_LIST_ASSIGNED_USER', + 'default' => true, + ), + 'DEPARTMENT' => + array ( + 'width' => '10%', + 'label' => 'LBL_DEPARTMENT', + 'default' => false, + ), + 'DO_NOT_CALL' => + array ( + 'width' => '10%', + 'label' => 'LBL_DO_NOT_CALL', + 'default' => false, + ), + 'PHONE_HOME' => + array ( + 'width' => '10%', + 'label' => 'LBL_HOME_PHONE', + 'default' => false, + ), + 'PHONE_MOBILE' => + array ( + 'width' => '10%', + 'label' => 'LBL_MOBILE_PHONE', + 'default' => false, + ), + 'PHONE_OTHER' => + array ( + 'width' => '10%', + 'label' => 'LBL_OTHER_PHONE', + 'default' => false, + ), + 'PHONE_FAX' => + array ( + 'width' => '10%', + 'label' => 'LBL_FAX_PHONE', + 'default' => false, + ), + 'EMAIL2' => + array ( + 'width' => '15%', + 'label' => 'LBL_LIST_EMAIL_ADDRESS', + 'sortable' => false, + 'customCode' => '{$EMAIL2_LINK}{$EMAIL2}', + 'default' => false, + ), + 'PRIMARY_ADDRESS_STREET' => + array ( + 'width' => '10%', + 'label' => 'LBL_PRIMARY_ADDRESS_STREET', + 'default' => false, + ), + 'PRIMARY_ADDRESS_CITY' => + array ( + 'width' => '10%', + 'label' => 'LBL_PRIMARY_ADDRESS_CITY', + 'default' => false, + ), + 'PRIMARY_ADDRESS_STATE' => + array ( + 'width' => '10%', + 'label' => 'LBL_PRIMARY_ADDRESS_STATE', + 'default' => false, + ), + 'PRIMARY_ADDRESS_POSTALCODE' => + array ( + 'width' => '10%', + 'label' => 'LBL_PRIMARY_ADDRESS_POSTALCODE', + 'default' => false, + ), + 'ALT_ADDRESS_COUNTRY' => + array ( + 'width' => '10%', + 'label' => 'LBL_ALT_ADDRESS_COUNTRY', + 'default' => false, + ), + 'ALT_ADDRESS_STREET' => + array ( + 'width' => '10%', + 'label' => 'LBL_ALT_ADDRESS_STREET', + 'default' => false, + ), + 'ALT_ADDRESS_CITY' => + array ( + 'width' => '10%', + 'label' => 'LBL_ALT_ADDRESS_CITY', + 'default' => false, + ), + 'ALT_ADDRESS_STATE' => + array ( + 'width' => '10%', + 'label' => 'LBL_ALT_ADDRESS_STATE', + 'default' => false, + ), + 'ALT_ADDRESS_POSTALCODE' => + array ( + 'width' => '10%', + 'label' => 'LBL_ALT_ADDRESS_POSTALCODE', + 'default' => false, + ), + 'DATE_ENTERED' => + array ( + 'width' => '10%', + 'label' => 'LBL_DATE_ENTERED', + 'default' => false, + ), + 'CREATED_BY_NAME' => + array ( + 'width' => '10%', + 'label' => 'LBL_CREATED', + 'default' => false, + ), + 'MODIFIED_BY_NAME' => + array ( + 'width' => '10%', + 'label' => 'LBL_MODIFIED', + 'default' => false, + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/popupdefs.php b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/popupdefs.php new file mode 100755 index 00000000..e946ced1 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/popupdefs.php @@ -0,0 +1,173 @@ + 'Contact', + 'varName' => 'CONTACT', + 'orderBy' => 'contacts.first_name, contacts.last_name', + 'whereClauses' => array ( + 'first_name' => 'contacts.first_name', + 'last_name' => 'contacts.last_name', + 'account_name' => 'accounts.name', + 'test_c' => 'contacts_cstm.test_c', + 'test2_c' => 'contacts_cstm.test2_c', + 'title' => 'contacts.title', + 'lead_source' => 'contacts.lead_source', + 'campaign_name' => 'contacts.campaign_name', + 'assigned_user_id' => 'contacts.assigned_user_id', +), + 'searchInputs' => array ( + 0 => 'first_name', + 1 => 'last_name', + 2 => 'account_name', + 3 => 'test_c', + 4 => 'test2_c', + 5 => 'title', + 6 => 'lead_source', + 7 => 'campaign_name', + 8 => 'assigned_user_id', +), + 'create' => array ( + 'formBase' => 'ContactFormBase.php', + 'formBaseClass' => 'ContactFormBase', + 'getFormBodyParams' => + array ( + 0 => '', + 1 => '', + 2 => 'ContactSave', + ), + 'createButton' => 'Create Contact', +), + 'searchdefs' => array ( + 'first_name' => + array ( + 'name' => 'first_name', + 'width' => '10%', + ), + 'test_c' => + array ( + 'type' => 'varchar', + 'label' => 'LBL_TEST', + 'width' => '10%', + 'name' => 'test_c', + ), + 'test2_c' => + array ( + 'type' => 'varchar', + 'label' => 'LBL_TEST2', + 'width' => '10%', + 'name' => 'test2_c', + ), + 'last_name' => + array ( + 'name' => 'last_name', + 'width' => '10%', + ), + 'account_name' => + array ( + 'name' => 'account_name', + 'displayParams' => + array ( + 'hideButtons' => 'true', + 'size' => 30, + 'class' => 'sqsEnabled sqsNoAutofill', + ), + 'width' => '10%', + ), + 'title' => + array ( + 'name' => 'title', + 'width' => '10%', + ), + 'lead_source' => + array ( + 'name' => 'lead_source', + 'width' => '10%', + ), + 'campaign_name' => + array ( + 'name' => 'campaign_name', + 'displayParams' => + array ( + 'hideButtons' => 'true', + 'size' => 30, + 'class' => 'sqsEnabled sqsNoAutofill', + ), + 'width' => '10%', + ), + 'assigned_user_id' => + array ( + 'name' => 'assigned_user_id', + 'type' => 'enum', + 'label' => 'LBL_ASSIGNED_TO', + 'function' => + array ( + 'name' => 'get_user_array', + 'params' => + array ( + 0 => false, + ), + ), + 'width' => '10%', + ), +), + 'listviewdefs' => array ( + 'NAME' => + array ( + 'width' => '20%', + 'label' => 'LBL_LIST_NAME', + 'link' => true, + 'default' => true, + 'related_fields' => + array ( + 0 => 'first_name', + 1 => 'last_name', + 2 => 'salutation', + 3 => 'account_name', + 4 => 'account_id', + ), + 'name' => 'name', + ), + 'TEST_C' => + array ( + 'type' => 'varchar', + 'default' => true, + 'label' => 'LBL_TEST', + 'width' => '10%', + ), + 'TEST2_C' => + array ( + 'type' => 'varchar', + 'default' => true, + 'label' => 'LBL_TEST2', + 'width' => '10%', + ), + 'ACCOUNT_NAME' => + array ( + 'width' => '25%', + 'label' => 'LBL_LIST_ACCOUNT_NAME', + 'module' => 'Accounts', + 'id' => 'ACCOUNT_ID', + 'default' => true, + 'sortable' => true, + 'ACLTag' => 'ACCOUNT', + 'related_fields' => + array ( + 0 => 'account_id', + ), + 'name' => 'account_name', + ), + 'TITLE' => + array ( + 'width' => '15%', + 'label' => 'LBL_LIST_TITLE', + 'default' => true, + 'name' => 'title', + ), + 'LEAD_SOURCE' => + array ( + 'width' => '15%', + 'label' => 'LBL_LEAD_SOURCE', + 'default' => true, + 'name' => 'lead_source', + ), +), +); diff --git a/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/quickcreatedefs.php b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/quickcreatedefs.php new file mode 100755 index 00000000..84affa06 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/quickcreatedefs.php @@ -0,0 +1,124 @@ + + array ( + 'templateMeta' => + array ( + 'form' => + array ( + 'hidden' => + array ( + 0 => '', + 1 => '', + 2 => '', + 3 => '', + 4 => '', + 5 => '', + 6 => '', + ), + ), + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + 'useTabs' => false, + ), + 'panels' => + array ( + 'default' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'first_name', + ), + 1 => + array ( + 'name' => 'account_name', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'last_name', + 'displayParams' => + array ( + 'required' => true, + ), + ), + 1 => + array ( + 'name' => 'phone_work', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'title', + ), + 1 => + array ( + 'name' => 'phone_mobile', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'phone_fax', + ), + 1 => + array ( + 'name' => 'do_not_call', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'email1', + ), + 1 => + array ( + 'name' => 'lead_source', + ), + ), + 5 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + ), + ), + 6 => + array ( + 0 => + array ( + 'name' => 'test_c', + 'label' => 'LBL_TEST', + ), + 1 => + array ( + 'name' => 'test2_c', + 'label' => 'LBL_TEST2', + ), + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/searchdefs.php b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/searchdefs.php new file mode 100755 index 00000000..3e332af4 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/ce_metadata_files/custom/modules/Contacts/metadata/searchdefs.php @@ -0,0 +1,160 @@ + + array ( + 'basic_search' => + array ( + 'search_name' => + array ( + 'name' => 'search_name', + 'label' => 'LBL_NAME', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'test_c' => + array ( + 'type' => 'varchar', + 'default' => true, + 'label' => 'LBL_TEST', + 'width' => '10%', + 'name' => 'test_c', + ), + 'current_user_only' => + array ( + 'name' => 'current_user_only', + 'label' => 'LBL_CURRENT_USER_FILTER', + 'type' => 'bool', + 'default' => true, + 'width' => '10%', + ), + ), + 'advanced_search' => + array ( + 'first_name' => + array ( + 'name' => 'first_name', + 'default' => true, + 'width' => '10%', + ), + 'email' => + array ( + 'name' => 'email', + 'label' => 'LBL_ANY_EMAIL', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'phone' => + array ( + 'name' => 'phone', + 'label' => 'LBL_ANY_PHONE', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'last_name' => + array ( + 'name' => 'last_name', + 'default' => true, + 'width' => '10%', + ), + 'address_street' => + array ( + 'name' => 'address_street', + 'label' => 'LBL_ANY_ADDRESS', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'address_city' => + array ( + 'name' => 'address_city', + 'label' => 'LBL_CITY', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'account_name' => + array ( + 'name' => 'account_name', + 'default' => true, + 'width' => '10%', + ), + 'address_state' => + array ( + 'name' => 'address_state', + 'label' => 'LBL_STATE', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'address_postalcode' => + array ( + 'name' => 'address_postalcode', + 'label' => 'LBL_POSTAL_CODE', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'assigned_user_id' => + array ( + 'name' => 'assigned_user_id', + 'type' => 'enum', + 'label' => 'LBL_ASSIGNED_TO', + 'function' => + array ( + 'name' => 'get_user_array', + 'params' => + array ( + 0 => false, + ), + ), + 'default' => true, + 'width' => '10%', + ), + 'primary_address_country' => + array ( + 'name' => 'primary_address_country', + 'label' => 'LBL_COUNTRY', + 'type' => 'name', + 'options' => 'countries_dom', + 'default' => true, + 'width' => '10%', + ), + 'lead_source' => + array ( + 'name' => 'lead_source', + 'default' => true, + 'width' => '10%', + ), + 'test_c' => + array ( + 'type' => 'varchar', + 'default' => true, + 'label' => 'LBL_TEST', + 'width' => '10%', + 'name' => 'test_c', + ), + 'test2_c' => + array ( + 'type' => 'varchar', + 'default' => true, + 'label' => 'LBL_TEST2', + 'width' => '10%', + 'name' => 'test2_c', + ), + ), + ), + 'templateMeta' => + array ( + 'maxColumns' => '3', + 'widths' => + array ( + 'label' => '10', + 'field' => '30', + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/cit_metadata_files/554/modules/Leads/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/cit_metadata_files/554/modules/Leads/metadata/detailviewdefs.php new file mode 100755 index 00000000..7c234897 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/cit_metadata_files/554/modules/Leads/metadata/detailviewdefs.php @@ -0,0 +1,184 @@ + array ( + 'form' => array ( + 'buttons' => array ( + 'EDIT', + 'DUPLICATE', + 'DELETE', + array ( + 'customCode' => '' + ), + array ( + 'customCode' => '' + ), + array ( + 'customCode' => '' + ), + + ), + 'headerTpl'=>'modules/Leads/tpls/DetailViewHeader.tpl', + ), + 'maxColumns' => '2', + 'widths' => array ( + array ( + 'label' => '10', + 'field' => '30' + ), + array ( + 'label' => '10', + 'field' => '30' + ) + ), + 'includes'=> array( + array('file'=>'modules/Leads/Lead.js'), + ), + ), + 'panels' => array ( + + 'LBL_CONTACT_INFORMATION' => + array ( + array ( + array ( + 'name' => 'full_name', + 'label' => 'LBL_NAME', + ), + 'phone_work', + ), + + array ( + 'title', + 'phone_mobile', + ), + + array ( + 'department', + 'phone_fax' + ), + + array ( + 'account_name', + 'website' + ), + + array ( + array ( + 'name' => 'primary_address_street', + 'label' => 'LBL_PRIMARY_ADDRESS', + 'type' => 'address', + 'displayParams' => array ( + 'key' => 'primary' + ), + + ), + + array ( + 'name' => 'alt_address_street', + 'label' => 'LBL_ALTERNATE_ADDRESS', + 'type' => 'address', + 'displayParams' => array ( + 'key' => 'alt' + ), + + ), + + ), + + array ( + 'email1', + ), + + array ( + 'description', + ), + + ), + + 'LBL_PANEL_ADVANCED' => + array ( + + array ( + 'status', + 'lead_source' + ), + + array ( + 'status_description', + 'lead_source_description', + ), + + array ( + array ( + 'name' => 'campaign_name', + 'label' => 'LBL_CAMPAIGN', + + ), + 'refered_by', + ), + + array ( + '', + 'do_not_call' + ) + + ), + + 'LBL_PANEL_ASSIGNMENT' => + array( + array ( + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO', + ), + array ( + 'name' => 'date_modified', + 'label' => 'LBL_DATE_MODIFIED', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', + ), + ), + array ( + array ( + 'name' => 'date_entered', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}', + ), + ), + ), + + ) +); +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/cit_metadata_files/custom/modules/Leads/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/cit_metadata_files/custom/modules/Leads/metadata/detailviewdefs.php new file mode 100755 index 00000000..d2f123c4 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/cit_metadata_files/custom/modules/Leads/metadata/detailviewdefs.php @@ -0,0 +1,194 @@ + + array ( + 'templateMeta' => + array ( + 'form' => + array ( + 'buttons' => + array ( + 0 => 'EDIT', + 1 => 'DUPLICATE', + 2 => 'DELETE', + 3 => + array ( + 'customCode' => '', + ), + 4 => + array ( + 'customCode' => '', + ), + 5 => + array ( + 'customCode' => '', + ), + ), + 'headerTpl' => 'modules/Leads/tpls/DetailViewHeader.tpl', + ), + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + 'includes' => + array ( + 0 => + array ( + 'file' => 'modules/Leads/Lead.js', + ), + ), + ), + 'panels' => + array ( + 0 => + array ( + 0 => 'lead_source', + 1 => 'status', + ), + 1 => + array ( + 0 => 'lead_source_description', + 1 => 'status_description', + ), + 2 => + array ( + 0 => + array ( + 'name' => 'campaign_name', + 'label' => 'LBL_CAMPAIGN', + ), + 1 => 'opportunity_amount', + ), + 3 => + array ( + 0 => 'refered_by', + 1 => + array ( + 'name' => 'phone_work', + 'label' => 'LBL_OFFICE_PHONE', + 'customCode' => '{fonality_phone value=$fields.phone_work.value this_module=Leads this_id=$fields.id.value}', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'full_name', + 'label' => 'LBL_NAME', + ), + 1 => + array ( + 'name' => 'phone_mobile', + 'label' => 'LBL_MOBILE_PHONE', + 'customCode' => '{fonality_phone value=$fields.phone_mobile.value this_module=Leads this_id=$fields.id.value}', + ), + ), + 5 => + array ( + 0 => 'birthdate', + 1 => + array ( + 'name' => 'phone_home', + 'label' => 'LBL_HOME_PHONE', + 'customCode' => '{fonality_phone value=$fields.phone_home.value this_module=Leads this_id=$fields.id.value}', + ), + ), + 6 => + array ( + 0 => 'account_name', + 1 => + array ( + 'name' => 'phone_other', + 'label' => 'LBL_OTHER_PHONE', + 'customCode' => '{fonality_phone value=$fields.phone_other.value this_module=Leads this_id=$fields.id.value}', + ), + ), + 7 => + array ( + 0 => 'title', + 1 => + array ( + 'name' => 'phone_fax', + 'label' => 'LBL_FAX_PHONE', + 'customCode' => '{fonality_phone value=$fields.phone_fax.value this_module=Leads this_id=$fields.id.value}', + ), + ), + 8 => + array ( + 0 => 'department', + 1 => 'do_not_call', + ), + 9 => + array ( + 0 => 'team_name', + 1 => + array ( + 'name' => 'date_modified', + 'label' => 'LBL_DATE_MODIFIED', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', + ), + ), + 10 => + array ( + ), + 11 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO', + ), + 1 => + array ( + 'name' => 'created_by', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value} ', + 'label' => 'LBL_DATE_ENTERED', + ), + ), + 12 => + array ( + 0 => + array ( + 'name' => 'primary_address_street', + 'label' => 'LBL_PRIMARY_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'primary', + ), + ), + 1 => + array ( + 'name' => 'alt_address_street', + 'label' => 'LBL_ALTERNATE_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'alt', + ), + ), + ), + 13 => + array ( + 0 => 'description', + 1 => '', + ), + 14 => + array ( + 0 => 'email1', + ), + ), + ), +); +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/metadata_files/520/modules/Quotes/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/520/modules/Quotes/metadata/detailviewdefs.php new file mode 100755 index 00000000..02d6e537 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/520/modules/Quotes/metadata/detailviewdefs.php @@ -0,0 +1,138 @@ + array('form' =>array('closeFormBeforeCustomButtons' => true, + 'links'=>array('{$MOD.PDF_FORMAT} '), + 'buttons'=>array('EDIT', 'DUPLICATE', 'DELETE', + array('customCode'=>'

'), + array('customCode'=>'
')), + 'footerTpl'=>'modules/Quotes/tpls/DetailViewFooter.tpl'), + 'maxColumns' => '2', + 'widths' => array( + array('label' => '10', 'field' => '30'), + array('label' => '10', 'field' => '30') + ), + ), +'panels' => array ( + +'default' => array( + array ( + array ( + 'name' => 'name', + 'label' => 'LBL_QUOTE_NAME', + ), + array( + 'name'=>'opportunity_name', + ), + ), + + array ( + 'quote_num', + 'quote_stage', + ), + + array ( + 'purchase_order_num', + + array ( + 'name' => 'date_quote_expected_closed', + 'label' => 'LBL_DATE_QUOTE_EXPECTED_CLOSED', + ), + ), + + array ( + 'payment_terms', + 'original_po_date', + ), + + array ( + + 'team_name', + + + array ( + 'name' => 'date_entered', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}', + 'label' => 'LBL_DATE_ENTERED', + ), + ), + + array ( + 'assigned_user_name', + + array ( + 'name' => 'date_modified', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', + 'label' => 'LBL_DATE_MODIFIED', + ), + ), + + array ( + 'billing_account_name', + 'shipping_account_name', + ), + + array ( + 'billing_contact_name', + 'shipping_contact_name' + ), + + array ( + + array ( + 'name' => 'billing_address_street', + 'label'=> 'LBL_BILL_TO', + 'type' => 'address', + 'displayParams'=>array('key'=>'billing'), + ), + + array ( + 'name' => 'shipping_address_street', + 'label'=> 'LBL_SHIP_TO', + 'type' => 'address', + 'displayParams'=>array('key'=>'shipping'), + ), + ), + + array ( + 'description', + ), +) + +) +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/metadata_files/550/modules/Contacts/metadata/editviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/550/modules/Contacts/metadata/editviewdefs.php new file mode 100755 index 00000000..ed4476c6 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/550/modules/Contacts/metadata/editviewdefs.php @@ -0,0 +1,184 @@ + array('form'=>array('hidden'=>array('', + + + + '', + '', + '', + '')), + 'maxColumns' => '2', + 'widths' => array( + array('label' => '10', 'field' => '30'), + array('label' => '10', 'field' => '30'), + ), +), + 'panels' =>array ( + 'lbl_contact_information' => + array ( + + array ( + array ( + 'name' => 'first_name', + 'customCode' => '{html_options name="salutation" options=$fields.salutation.options selected=$fields.salutation.value} ', + ), + 'phone_work', + ), + + array ( + array('name'=>'last_name', + 'displayParams'=>array('required'=>true), + ), + 'phone_mobile', + ), + + array ( + array('name'=>'account_name', 'displayParams'=>array('key'=>'billing', 'copy'=>'primary', 'billingKey'=>'primary', 'additionalFields'=>array('phone_office'=>'phone_work'))), + 'phone_home', + ), + + array ( + 'lead_source', + 'phone_other', + ), + + array ( + 'campaign_name', + 'phone_fax', + ), + + array ( + 'title', + 'birthdate', + ), + + array ( + 'department', + ), + + array ( + 'report_to_name', + 'assistant', + ), + + array ( + 'sync_contact', + 'assistant_phone', + ), + + array ( + 'do_not_call', + ), + + + array ( + array('name'=>'team_name', 'displayParams'=>array('display'=>true)), + '' + ), + + + array ( + 'assigned_user_name', + ), + ), + 'lbl_email_addresses'=>array( + array('email1') + ), + 'lbl_address_information' => + array ( + array ( + array ( + 'name' => 'primary_address_street', + 'hideLabel' => true, + 'type' => 'address', + 'displayParams'=>array('key'=>'primary', 'rows'=>2, 'cols'=>30, 'maxlength'=>150), + ), + + array ( + 'name' => 'alt_address_street', + 'hideLabel'=>true, + 'type' => 'address', + 'displayParams'=>array('key'=>'alt', 'copy'=>'primary', 'rows'=>2, 'cols'=>30, 'maxlength'=>150), + ), + ), + ), + + 'lbl_description_information' => + array ( + array ( + array('name'=>'description', + 'displayParams'=>array('rows'=>6, 'cols'=>80), + 'label'=>'LBL_DESCRIPTION'), + ), + ), + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +) + + +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Contacts/metadata/editviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Contacts/metadata/editviewdefs.php new file mode 100755 index 00000000..a129aa39 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Contacts/metadata/editviewdefs.php @@ -0,0 +1,146 @@ + array('form'=>array('hidden'=>array('', + '', + '', + '', + '')), + 'maxColumns' => '2', + 'widths' => array( + array('label' => '10', 'field' => '30'), + array('label' => '10', 'field' => '30'), + ), +), + 'panels' =>array ( + 'lbl_contact_information' => + array ( + + array ( + array ( + 'name' => 'first_name', + 'customCode' => '{html_options name="salutation" options=$fields.salutation.options selected=$fields.salutation.value} ', + ), + 'phone_work', + ), + + array ( + array('name'=>'last_name', + 'displayParams'=>array('required'=>true), + ), + 'phone_mobile', + ), + + array ( + array('name'=>'account_name', 'displayParams'=>array('key'=>'billing', 'copy'=>'primary', 'billingKey'=>'primary', 'additionalFields'=>array('phone_office'=>'phone_work'))), + 'phone_home', + ), + + array ( + 'lead_source', + 'phone_other', + ), + + array ( + 'campaign_name', + 'phone_fax', + ), + + array ( + 'title', + 'birthdate', + ), + + array ( + 'department', + ), + + array ( + 'report_to_name', + 'assistant', + ), + + array ( + 'sync_contact', + 'assistant_phone', + ), + + array ( + 'do_not_call', + ), + + + array ( + 'assigned_user_name', + ), + ), + 'lbl_email_addresses'=>array( + array('email1') + ), + 'lbl_address_information' => + array ( + array ( + array ( + 'name' => 'primary_address_street', + 'hideLabel' => true, + 'type' => 'address', + 'displayParams'=>array('key'=>'primary', 'rows'=>2, 'cols'=>30, 'maxlength'=>150), + ), + + array ( + 'name' => 'alt_address_street', + 'hideLabel'=>true, + 'type' => 'address', + 'displayParams'=>array('key'=>'alt', 'copy'=>'primary', 'rows'=>2, 'cols'=>30, 'maxlength'=>150), + ), + ), + ), + + 'lbl_description_information' => + array ( + array ( + array('name'=>'description', + 'displayParams'=>array('rows'=>6, 'cols'=>80), + 'label'=>'LBL_DESCRIPTION' + ), + ), + ), +) + + +); +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Contacts/metadata/searchdefs.php b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Contacts/metadata/searchdefs.php new file mode 100755 index 00000000..ec818d38 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Contacts/metadata/searchdefs.php @@ -0,0 +1,66 @@ + array('maxColumns' => '3', + 'widths' => array('label' => '10', 'field' => '30'), + ), + 'layout' => array( + 'basic_search' => array( + 'first_name', + 'last_name', + array('name'=>'current_user_only', 'label'=>'LBL_CURRENT_USER_FILTER', 'type'=>'bool'), + 'account_name', + ), + 'advanced_search' => array( + 'first_name', + array('name' => 'address_street', 'label' =>'LBL_ANY_ADDRESS', 'type' => 'name'), + array('name' => 'phone', 'label' =>'LBL_ANY_PHONE', 'type' => 'name'), + 'last_name', + array('name' => 'address_city', 'label' =>'LBL_CITY', 'type' => 'name'), + array('name' => 'email', 'label' =>'LBL_ANY_EMAIL', 'type' => 'name'), + 'account_name', + array('name' => 'address_state', 'label' =>'LBL_STATE', 'type' => 'name'), + 'do_not_call', + 'assistant', + array('name' => 'address_postalcode', 'label' =>'LBL_POSTAL_CODE', 'type' => 'name'), + array('name' => 'primary_address_country', 'label' =>'LBL_COUNTRY', 'type' => 'name', 'options' => 'countries_dom', ), + 'lead_source', + array('name' => 'assigned_user_id', 'type' => 'enum', 'label' => 'LBL_ASSIGNED_TO', 'function' => array('name' => 'get_user_array', 'params' => array(false))), + ), + ), + ); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Leads/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Leads/metadata/detailviewdefs.php new file mode 100755 index 00000000..ddefb65a --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Leads/metadata/detailviewdefs.php @@ -0,0 +1,220 @@ + array ( + 'form' => array ( + 'buttons' => array ( + 'EDIT', + 'DUPLICATE', + 'DELETE', + array ( + 'customCode' => '' + ), + array ( + 'customCode' => '' + ), + array ( + 'customCode' => '' + ), + + ), + 'headerTpl'=>'modules/Leads/tpls/DetailViewHeader.tpl', + ), + 'maxColumns' => '2', + 'widths' => array ( + array ( + 'label' => '10', + 'field' => '30' + ), + array ( + 'label' => '10', + 'field' => '30' + ) + ), + 'includes'=> array( + array('file'=>'modules/Leads/Lead.js'), + ), + ), + 'panels' => array ( + + array ( + 'lead_source', + 'status', + + ), + + array ( + 'lead_source_description', + 'status_description', + + ), + + array ( + array ( + 'name' => 'campaign_name', + 'label' => 'LBL_CAMPAIGN', + + ), + 'opportunity_amount', + + + + ), + + array ( + 'refered_by', + array ( + 'name' => 'phone_work', + 'label' => 'LBL_OFFICE_PHONE', + + ), + + ), + + array ( + + array ( + 'name' => 'full_name', + 'label' => 'LBL_NAME', + + ), + + array ( + 'name' => 'phone_mobile', + 'label' => 'LBL_MOBILE_PHONE', + + ), + + ), + + array ( + 'birthdate', + array ( + 'name' => 'phone_home', + 'label' => 'LBL_HOME_PHONE', + + ), + + ), + + array ( + // removing acc_name_from_accounts field from 510 + 'account_name', + array ( + 'name' => 'phone_other', + 'label' => 'LBL_OTHER_PHONE', + + ), + + ), + + array ( + 'title', + + array ( + 'name' => 'phone_fax', + 'label' => 'LBL_FAX_PHONE', + + ), + + ), + + array ( + 'department', + 'do_not_call' + ), + array ( + array ( + 'name' => 'date_modified', + 'label' => 'LBL_DATE_MODIFIED', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}' + ) + ), + array(), + array ( + + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO' + ), + + array ( + 'name' => 'created_by', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value} ', + 'label' => 'LBL_DATE_ENTERED', + + ), + + ), + + array ( + array ( + 'name' => 'primary_address_street', + 'label' => 'LBL_PRIMARY_ADDRESS', + 'type' => 'address', + 'displayParams' => array ( + 'key' => 'primary' + ), + + ), + + array ( + 'name' => 'alt_address_street', + 'label' => 'LBL_ALTERNATE_ADDRESS', + 'type' => 'address', + 'displayParams' => array ( + 'key' => 'alt' + ), + + ), + + ), + + array ( + 'description', + '', + + ), + + array ( + 'email1', + + ), + + ) +); +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Leads/metadata/editviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Leads/metadata/editviewdefs.php new file mode 100755 index 00000000..8f126951 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Leads/metadata/editviewdefs.php @@ -0,0 +1,155 @@ + array('form' => array('hidden'=>array('', + '', + '', + ''), + 'buttons' => array( + 'SAVE', + 'CANCEL', + ) + ), + 'maxColumns' => '2', + 'widths' => array( + array('label' => '10', 'field' => '30'), + array('label' => '10', 'field' => '30') + ), + 'javascript' => '', +), + 'panels' => array ( + 'lbl_contact_information' => array ( + array( + 'lead_source', + 'status' + ), + + array ( + array('name'=>'lead_source_description', 'displayParams'=>(array('rows'=>4,'cols'=>40))), + array('name'=>'status_description', 'displayParams'=>(array('rows'=>4,'cols'=>40))), + ), + + array('campaign_name','opportunity_amount'), + + array ( + 'refered_by', + ), + + array ( + array ( + 'name' => 'first_name', + 'customCode' => '{html_options id="salutation" name="salutation" options=$fields.salutation.options selected=$fields.salutation.value} ', + ), + 'phone_work', + ), + + array ( + array('name'=>'last_name', + 'displayParams'=>array('required'=>true), + ), + 'phone_mobile', + ), + + array ( + 'birthdate', + 'phone_home', + ), + + array ( + array('name'=>'account_name', 'type'=>'varchar', 'validateDependency'=>false,'customCode' => ''), + 'phone_other', + ), + + array ( + NULL, + 'phone_fax', + ), + + array ( + 'title','do_not_call', + ), + + array ( + 'department', + ), + + + array ( + 'assigned_user_name', + '' + ), + ), + + 'lbl_email_addresses' => array( + array('email1') + ), + + 'lbl_address_information' => array ( + array ( + array ( + 'name' => 'primary_address_street', + 'hideLabel' => true, + 'type' => 'address', + 'displayParams'=>array('key'=>'primary', 'rows'=>2, 'cols'=>30, 'maxlength'=>150), + ), + + array ( + 'name' => 'alt_address_street', + 'hideLabel'=>true, + 'type' => 'address', + 'displayParams'=>array('key'=>'alt', 'copy'=>'primary', 'rows'=>2, 'cols'=>30, 'maxlength'=>150), + ), + ), + ), + + 'lbl_description_information' => + array ( + array ( + array('name'=>'description', + 'displayParams'=>array('rows'=>6, 'cols'=>80), + 'label'=>'LBL_DESCRIPTION' + ), + ), + array ( + 'test_c' + ) + ), +) + + +); +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Notes/metadata/searchdefs.php b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Notes/metadata/searchdefs.php new file mode 100755 index 00000000..f308f8b5 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/551/modules/Notes/metadata/searchdefs.php @@ -0,0 +1,59 @@ + array( + 'maxColumns' => '3', + 'widths' => array('label' => '10', 'field' => '30'), + ), + 'layout' => array( + 'basic_search' => array( + 'name', + array('name'=>'contact_name', 'label'=>'LBL_CONTACT_NAME', 'type'=>'name'), + ), + 'advanced_search' => array( + 'name', + 'filename', + ), + ), + ); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/Contacts/metadata/editviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/Contacts/metadata/editviewdefs.php new file mode 100755 index 00000000..505b42b2 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/Contacts/metadata/editviewdefs.php @@ -0,0 +1,286 @@ + + array ( + 'templateMeta' => + array ( + 'form' => + array ( + 'hidden' => + array ( + 0 => '', + 1 => '', + 2 => '', + 3 => '', + 4 => '', + ), + ), + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + ), + 'panels' => + array ( + 'lbl_contact_information' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'first_name', + 'customCode' => '{html_options name="salutation" options=$fields.salutation.options selected=$fields.salutation.value} ', + ), + 1 => + array ( + 'name' => 'phone_work', + 'comment' => 'Work phone number of the contact', + 'label' => 'LBL_OFFICE_PHONE', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'last_name', + 'displayParams' => + array ( + 'required' => true, + ), + ), + 1 => + array ( + 'name' => 'phone_mobile', + 'comment' => 'Mobile phone number of the contact', + 'label' => 'LBL_MOBILE_PHONE', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'test_c', + 'label' => 'LBL_TEST', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'account_name', + 'displayParams' => + array ( + 'key' => 'billing', + 'copy' => 'primary', + 'billingKey' => 'primary', + 'additionalFields' => + array ( + 'phone_office' => 'phone_work', + ), + ), + ), + 1 => + array ( + 'name' => 'phone_home', + 'comment' => 'Home phone number of the contact', + 'label' => 'LBL_HOME_PHONE', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'lead_source', + 'comment' => 'How did the contact come about', + 'label' => 'LBL_LEAD_SOURCE', + ), + 1 => + array ( + 'name' => 'phone_other', + 'comment' => 'Other phone number for the contact', + 'label' => 'LBL_OTHER_PHONE', + ), + ), + 5 => + array ( + 0 => + array ( + 'name' => 'campaign_name', + 'comment' => 'The first campaign name for Contact (Meta-data only)', + 'label' => 'LBL_CAMPAIGN', + ), + 1 => + array ( + 'name' => 'phone_fax', + 'comment' => 'Contact fax number', + 'label' => 'LBL_FAX_PHONE', + ), + ), + 6 => + array ( + 0 => + array ( + 'name' => 'title', + 'comment' => 'The title of the contact', + 'label' => 'LBL_TITLE', + ), + 1 => + array ( + 'name' => 'birthdate', + 'comment' => 'The birthdate of the contact', + 'label' => 'LBL_BIRTHDATE', + ), + ), + 7 => + array ( + 0 => + array ( + 'name' => 'department', + 'comment' => 'The department of the contact', + 'label' => 'LBL_DEPARTMENT', + ), + ), + 8 => + array ( + 0 => + array ( + 'name' => 'report_to_name', + 'label' => 'LBL_REPORTS_TO', + ), + 1 => + array ( + 'name' => 'assistant', + 'comment' => 'Name of the assistant of the contact', + 'label' => 'LBL_ASSISTANT', + ), + ), + 9 => + array ( + 0 => + array ( + 'name' => 'sync_contact', + 'comment' => 'Synch to outlook? (Meta-Data only)', + 'label' => 'LBL_SYNC_CONTACT', + ), + 1 => + array ( + 'name' => 'assistant_phone', + 'comment' => 'Phone number of the assistant of the contact', + 'label' => 'LBL_ASSISTANT_PHONE', + ), + ), + 10 => + array ( + 0 => + array ( + 'name' => 'do_not_call', + 'comment' => 'An indicator of whether contact can be called', + 'label' => 'LBL_DO_NOT_CALL', + ), + ), + 11 => + array ( + 0 => + array ( + 'name' => 'team_name', + 'displayParams' => + array ( + 'display' => true, + ), + ), + ), + 12 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO_NAME', + ), + ), + ), + 'lbl_email_addresses' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'email1', + 'studio' => 'false', + 'label' => 'LBL_EMAIL_ADDRESS', + ), + ), + ), + 'lbl_address_information' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'primary_address_street', + 'hideLabel' => true, + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'primary', + 'rows' => 2, + 'cols' => 30, + 'maxlength' => 150, + ), + ), + 1 => + array ( + 'name' => 'alt_address_street', + 'hideLabel' => true, + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'alt', + 'copy' => 'primary', + 'rows' => 2, + 'cols' => 30, + 'maxlength' => 150, + ), + ), + ), + ), + 'lbl_description_information' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'description', + 'displayParams' => + array ( + 'rows' => 6, + 'cols' => 80, + ), + 'label' => 'LBL_DESCRIPTION', + ), + + array ( + 'name' => 'custom_description_c', + 'displayParams' => + array ( + 'rows' => 10, + 'cols' => 100, + ), + 'label' => 'LBL_DESCRIPTION', + ), + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/Leads/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/Leads/metadata/detailviewdefs.php new file mode 100755 index 00000000..58cff45f --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/Leads/metadata/detailviewdefs.php @@ -0,0 +1,175 @@ + + array ( + 'form' => + array ( + 'buttons' => + array ( + 0 => 'EDIT', + 1 => 'DUPLICATE', + 2 => 'DELETE', + 3 => + array ( + 'customCode' => '', + ), + 4 => + array ( + 'customCode' => '', + ), + 5 => + array ( + 'customCode' => '', + ), + ), + 'headerTpl' => 'modules/Leads/tpls/DetailViewHeader.tpl', + ), + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + 'includes' => + array ( + 0 => + array ( + 'file' => 'modules/Leads/Lead.js', + ), + ), + ), + 'panels' => + array ( + 'default' => + array ( + 0 => + array ( + 0 => 'lead_source', + 1 => 'status', + ), + 1 => + array ( + 0 => 'lead_source_description', + 1 => 'status_description', + ), + 2 => + array ( + 0 => + array ( + 'name' => 'campaign_name', + 'label' => 'LBL_CAMPAIGN', + ), + ), + 3 => + array ( + 0 => 'refered_by', + 1 => 'phone_work', + ), + 4 => + array ( + 0 => + array ( + 'name' => 'full_name', + 'label' => 'LBL_NAME', + ), + 1 => 'phone_mobile', + ), + 6 => + array ( + 0 => + array ( + 'name' => 'account_name', + 'displayParams' => + array ( + ), + ), + ), + 7 => + array ( + 0 => 'title', + 1 => 'phone_fax', + ), + 8 => + array ( + 0 => 'department', + 1 => 'do_not_call', + ), + 9 => + array ( + 0 => 'team_name', + 1 => + array ( + 'name' => 'date_modified', + 'label' => 'LBL_DATE_MODIFIED', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', + ), + ), + 11 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO', + ), + ), + 12 => + array ( + 0 => + array ( + 'name' => 'primary_address_street', + 'label' => 'LBL_PRIMARY_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'primary', + ), + ), + 1 => + array ( + 'name' => 'alt_address_street', + 'label' => 'LBL_ALTERNATE_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'alt', + ), + ), + ), + 13 => + array ( + 0 => 'description', + 1 => '', + ), + 14 => + array ( + 0 => 'email1', + ), + 15 => + array ( + 0 => 'field1_c', + 1 => 'field2_c', + ) + ), + 'lbl_panel_assignment' => + array ( + 1 => + array ( + 1 => + array ( + 'name' => 'date_entered', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}', + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/Leads/metadata/editviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/Leads/metadata/editviewdefs.php new file mode 100755 index 00000000..0424f9da --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/Leads/metadata/editviewdefs.php @@ -0,0 +1,155 @@ + array('form' => array('hidden'=>array('', + '', + '', + ''), + 'buttons' => array( + 'SAVE', + 'CANCEL', + ) + ), + 'maxColumns' => '2', + 'widths' => array( + array('label' => '10', 'field' => '30'), + array('label' => '10', 'field' => '30') + ), + 'javascript' => '', +), + 'panels' =>array ( + 'lbl_contact_information' => + array ( + + array( + 'lead_source', + 'status' + ), + + array ( + array('name'=>'lead_source_description', 'displayParams'=>(array('rows'=>4,'cols'=>40))), + array('name'=>'status_description', 'displayParams'=>(array('rows'=>4,'cols'=>40))), + ), + + array('campaign_name','opportunity_amount'), + + array ( + 'refered_by', + + ), + + array ( + + array ( + 'name' => 'first_name', + 'customCode' => '{html_options id="salutation" name="salutation" options=$fields.salutation.options selected=$fields.salutation.value} ', + ), + 'phone_work', + ), + + array ( + array('name'=>'last_name', + 'displayParams'=>array('required'=>true), + ), + 'phone_mobile', + ), + + array ( + 'birthdate', + 'phone_home', + ), + + array ( + array('name'=>'account_name', 'type'=>'varchar', 'validateDependency'=>false,'customCode' => ''), + 'phone_other', + ), + + array ( + NULL, + 'phone_fax', + ), + + array ( + 'title','do_not_call', + ), + + array ( + 'department', + ), + + + array ( + 'assigned_user_name', + '' + ), + ), + + 'lbl_email_addresses'=>array( + array('email1') + ), + + 'lbl_address_information' => + array ( + array ( + array ( + 'name' => 'primary_address_street', + 'hideLabel' => true, + 'type' => 'address', + 'displayParams'=>array('key'=>'primary', 'rows'=>2, 'cols'=>30, 'maxlength'=>150), + ), + + array ( + 'name' => 'alt_address_street', + 'hideLabel'=>true, + 'type' => 'address', + 'displayParams'=>array('key'=>'alt', 'copy'=>'primary', 'rows'=>2, 'cols'=>30, 'maxlength'=>150), + ), + ), + ), + + 'lbl_description_information' => + array ( + array( + 'test_c', + 'description', + ) + ), +) + + +); +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/Quotes/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/Quotes/metadata/detailviewdefs.php new file mode 100755 index 00000000..4827d970 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/metadata_files/custom/modules/Quotes/metadata/detailviewdefs.php @@ -0,0 +1,208 @@ + + array ( + 'templateMeta' => + array ( + 'form' => + array ( + 'closeFormBeforeCustomButtons' => true, + 'links' => + array ( + 0 => '{$MOD.PDF_FORMAT}
', + ), + 'buttons' => + array ( + 0 => 'EDIT', + 1 => 'DUPLICATE', + 2 => 'DELETE', + 3 => + array ( + 'customCode' => '
', + ), + 4 => + array ( + 'customCode' => '
', + ), + ), + 'footerTpl' => 'modules/Quotes/tpls/DetailViewFooter.tpl', + ), + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + ), + 'panels' => + array ( + 'default' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'name', + 'label' => 'LBL_QUOTE_NAME', + ), + 1 => + array ( + 'name' => 'opportunity_name', + 'label' => 'LBL_OPPORTUNITY_NAME', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'quote_num', + 'label' => 'LBL_QUOTE_NUM', + ), + 1 => + array ( + 'name' => 'quote_stage', + 'label' => 'LBL_QUOTE_STAGE', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'purchase_order_num', + 'label' => 'LBL_PURCHASE_ORDER_NUM', + ), + 1 => + array ( + 'name' => 'date_quote_expected_closed', + 'label' => 'LBL_DATE_QUOTE_EXPECTED_CLOSED', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'payment_terms', + 'label' => 'LBL_PAYMENT_TERMS', + ), + 1 => + array ( + 'name' => 'original_po_date', + 'label' => 'LBL_ORIGINAL_PO_DATE', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'team_name', + 'label' => 'LBL_TEAM', + ), + 1 => + array ( + 'name' => 'date_entered', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}', + 'label' => 'LBL_DATE_ENTERED', + ), + ), + 5 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO_NAME', + ), + 1 => + array ( + 'name' => 'date_modified', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', + 'label' => 'LBL_DATE_MODIFIED', + ), + ), + 6 => + array ( + 0 => + array ( + 'name' => 'billing_account_name', + 'label' => 'LBL_BILLING_ACCOUNT_NAME', + ), + 1 => + array ( + 'name' => 'shipping_account_name', + 'label' => 'LBL_SHIPPING_ACCOUNT_NAME', + ), + ), + 7 => + array ( + 0 => + array ( + 'name' => 'billing_contact_name', + 'label' => 'LBL_BILLING_CONTACT_NAME', + ), + 1 => + array ( + 'name' => 'shipping_contact_name', + 'label' => 'LBL_SHIPPING_CONTACT_NAME', + ), + ), + 8 => + array ( + 0 => + array ( + 'name' => 'billing_address_street', + 'label' => 'LBL_BILL_TO', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'billing', + ), + ), + 1 => + array ( + 'name' => 'shipping_address_street', + 'label' => 'LBL_SHIP_TO', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'shipping', + ), + ), + ), + 9 => + array ( + 0 => + array ( + 'name' => 'description', + 'label' => 'LBL_DESCRIPTION', + ), + 1 => + array ( + 'name' => 'contacts_quotes_name', + 'label' => 'LBL_CONTACTS_QUOTES_FROM_CONTACTS_TITLE', + ), + ), + 10 => + array ( + 0 => + array ( + 'name' => 'contacts_quotes_1_name', + 'label' => 'LBL_CONTACTS_QUOTES_1_FROM_CONTACTS_TITLE', + ), + 1 => + array ( + 'name' => 'contacts_quotes_2_name', + ), + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/551/modules/Meetings/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/551/modules/Meetings/metadata/detailviewdefs.php new file mode 100755 index 00000000..43d80742 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/551/modules/Meetings/metadata/detailviewdefs.php @@ -0,0 +1,107 @@ + array('form'=>array('buttons'=>array('EDIT', 'DUPLICATE', 'DELETE', + array('customCode'=>'{if $fields.status.value != "Held"}' . + ' ' . + ' ' . + ' ' . + ' {/if}'), + array('customCode'=>'{if $fields.status.value != "Held"}' . + ' ' . + ' {/if}'),)), + 'maxColumns' => '2', + 'widths' => array( + array('label' => '10', 'field' => '30'), + array('label' => '10', 'field' => '30') + ), + ), + 'panels' =>array ( + array ( + array ( 'name' => 'name','label' => 'LBL_SUBJECT',), + 'status', + ), + array ( + 'location', + array ('name' => 'parent_name', + 'customLabel' => '{sugar_translate label=\'LBL_MODULE_NAME\' module=$fields.parent_type.value}',), + ), + array ( + array ('name' =>'date_start', 'label' => 'LBL_DATE_TIME'), + array ( + 'name' => 'duration_hours', + 'customCode' => '{$fields.duration_hours.value}{$MOD.LBL_HOURS_ABBREV} {$fields.duration_minutes.value}{$MOD.LBL_MINSS_ABBREV} ', + 'label' => 'LBL_DURATION', + ), + ), + array ( + array ( + 'name' => 'modified_by_name', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value} ', + 'label' => 'LBL_DATE_MODIFIED', + ), + ), + array ( + array ('name' => 'assigned_user_name','label' => 'LBL_ASSIGNED_TO',), + array ( + 'name' => 'created_by_name', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value} ', + 'label' => 'LBL_DATE_ENTERED', + ), + ), + array ( + array( + 'name'=>'reminder_checked', + 'fields'=>array('reminder_checked', 'reminder_time') + ), + 'description', + ), + ) +); +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/554/modules/Leads/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/554/modules/Leads/metadata/detailviewdefs.php new file mode 100755 index 00000000..b14e11f5 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/554/modules/Leads/metadata/detailviewdefs.php @@ -0,0 +1,194 @@ + + array ( + 'templateMeta' => + array ( + 'form' => + array ( + 'buttons' => + array ( + 0 => 'EDIT', + 1 => 'DUPLICATE', + 2 => 'DELETE', + 3 => + array ( + 'customCode' => '', + ), + 4 => + array ( + 'customCode' => '', + ), + 5 => + array ( + 'customCode' => '', + ), + ), + 'headerTpl' => 'modules/Leads/tpls/DetailViewHeader.tpl', + ), + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + 'includes' => + array ( + 0 => + array ( + 'file' => 'modules/Leads/Lead.js', + ), + ), + ), + 'panels' => + array ( + 0 => + array ( + 0 => 'lead_source', + 1 => 'status', + ), + 1 => + array ( + 0 => 'lead_source_description', + 1 => 'status_description', + ), + 2 => + array ( + 0 => + array ( + 'name' => 'campaign_name', + 'label' => 'LBL_CAMPAIGN', + ), + 1 => 'opportunity_amount', + ), + 3 => + array ( + 0 => 'refered_by', + 1 => + array ( + 'name' => 'phone_work', + 'label' => 'LBL_OFFICE_PHONE', + 'customCode' => '{fonality_phone value=$fields.phone_work.value this_module=Leads this_id=$fields.id.value}', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'full_name', + 'label' => 'LBL_NAME', + ), + 1 => + array ( + 'name' => 'phone_mobile', + 'label' => 'LBL_MOBILE_PHONE', + 'customCode' => '{fonality_phone value=$fields.phone_mobile.value this_module=Leads this_id=$fields.id.value}', + ), + ), + 5 => + array ( + 0 => 'birthdate', + 1 => + array ( + 'name' => 'phone_home', + 'label' => 'LBL_HOME_PHONE', + 'customCode' => '{fonality_phone value=$fields.phone_home.value this_module=Leads this_id=$fields.id.value}', + ), + ), + 6 => + array ( + 0 => 'account_name', + 1 => + array ( + 'name' => 'phone_other', + 'label' => 'LBL_OTHER_PHONE', + 'customCode' => '{fonality_phone value=$fields.phone_other.value this_module=Leads this_id=$fields.id.value}', + ), + ), + 7 => + array ( + 0 => 'title', + 1 => + array ( + 'name' => 'phone_fax', + 'label' => 'LBL_FAX_PHONE', + 'customCode' => '{fonality_phone value=$fields.phone_fax.value this_module=Leads this_id=$fields.id.value}', + ), + ), + 8 => + array ( + 0 => 'department', + 1 => 'do_not_call', + ), + 9 => + array ( + 0 => 'team_name', + 1 => + array ( + 'name' => 'date_modified', + 'label' => 'LBL_DATE_MODIFIED', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', + ), + ), + 10 => + array ( + ), + 11 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO', + ), + 1 => + array ( + 'name' => 'created_by', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value} ', + 'label' => 'LBL_DATE_ENTERED', + ), + ), + 12 => + array ( + 0 => + array ( + 'name' => 'primary_address_street', + 'label' => 'LBL_PRIMARY_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'primary', + ), + ), + 1 => + array ( + 'name' => 'alt_address_street', + 'label' => 'LBL_ALTERNATE_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'alt', + ), + ), + ), + 13 => + array ( + 0 => 'description', + 1 => '', + ), + 14 => + array ( + 0 => 'email1', + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/554/modules/Opportunities/metadata/listviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/554/modules/Opportunities/metadata/listviewdefs.php new file mode 100755 index 00000000..3ff342ab --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/554/modules/Opportunities/metadata/listviewdefs.php @@ -0,0 +1,76 @@ + array( + 'width' => '30', + 'label' => 'LBL_LIST_OPPORTUNITY_NAME', + 'link' => true, + 'default' => true), + 'ACCOUNT_NAME' => array( + 'width' => '20', + 'label' => 'LBL_LIST_ACCOUNT_NAME', + 'id' => 'ACCOUNT_ID', + 'module' => 'Accounts', + 'link' => true, + 'default' => true, + 'sortable'=> true, + 'ACLTag' => 'ACCOUNT', + 'contextMenu' => array('objectType' => 'sugarAccount', + 'metaData' => array('return_module' => 'Contacts', + 'return_action' => 'ListView', + 'module' => 'Accounts', + 'return_action' => 'ListView', + 'parent_id' => '{$ACCOUNT_ID}', + 'parent_name' => '{$ACCOUNT_NAME}', + 'account_id' => '{$ACCOUNT_ID}', + 'account_name' => '{$ACCOUNT_NAME}', + ), + ), + 'related_fields' => array('account_id')), + 'SALES_STAGE' => array( + 'width' => '10', + 'label' => 'LBL_LIST_SALES_STAGE', + 'default' => true), + 'AMOUNT_USDOLLAR' => array( + 'width' => '10', + 'label' => 'LBL_LIST_AMOUNT', + 'align' => 'right', + 'default' => true, + 'currency_format' => true, + ), + 'OPPORTUNITY_TYPE' => array( + 'width' => '15', + 'label' => 'LBL_TYPE'), + 'LEAD_SOURCE' => array( + 'width' => '15', + 'label' => 'LBL_LEAD_SOURCE'), + 'NEXT_STEP' => array( + 'width' => '10', + 'label' => 'LBL_NEXT_STEP'), + 'PROBABILITY' => array( + 'width' => '10', + 'label' => 'LBL_PROBABILITY'), + 'DATE_CLOSED' => array( + 'width' => '10', + 'label' => 'LBL_LIST_DATE_CLOSED', + 'default' => true), + 'DATE_ENTERED' => array( + 'width' => '10', + 'label' => 'LBL_DATE_ENTERED'), + 'CREATED_BY_NAME' => array( + 'width' => '10', + 'label' => 'LBL_CREATED'), + 'TEAM_NAME' => array( + 'width' => '5', + 'label' => 'LBL_LIST_TEAM', + 'default' => false), + 'ASSIGNED_USER_NAME' => array( + 'width' => '5', + 'label' => 'LBL_LIST_ASSIGNED_USER', + 'default' => true), + 'MODIFIED_BY_NAME' => array( + 'width' => '5', + 'label' => 'LBL_MODIFIED') +); + +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/610/custom/modules/Accounts/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/610/custom/modules/Accounts/metadata/detailviewdefs.php new file mode 100755 index 00000000..2e1ee329 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/610/custom/modules/Accounts/metadata/detailviewdefs.php @@ -0,0 +1,199 @@ + array('form' => array('buttons'=>array('EDIT', 'DUPLICATE', 'DELETE', 'FIND_DUPLICATES')), + 'maxColumns' => '2', + 'widths' => array( + array('label' => '10', 'field' => '30'), + array('label' => '10', 'field' => '30') + ), + 'includes'=> array( + array('file'=>'modules/Accounts/Account.js'), + ), + ), + 'panels' => + array ( + 'lbl_account_information' => + array ( + array ( + array ( + 'name' => 'name', + 'comment' => 'Name of the Company', + 'label' => 'LBL_NAME', + ), + array ( + 'name' => 'name', + 'comment' => 'Name of the Company', + 'label' => 'LBL_NAME', + ), + ), + + array ( + + array ( + 'name' => 'website', + 'type' => 'link', + 'label' => 'LBL_WEBSITE', + 'displayParams' => + array ( + 'link_target' => '_blank', + ), + ), + array ( + 'name' => 'phone_fax', + 'comment' => 'The fax phone number of this company', + 'label' => 'LBL_FAX', + ), + ), + + array ( + array ( + 'name' => 'billing_address_street', + 'label' => 'LBL_BILLING_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'billing', + ), + ), + + array ( + 'name' => 'shipping_address_street', + 'label' => 'LBL_SHIPPING_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'shipping', + ), + ), + ), + array ( + array ( + 'name' => 'description', + 'displayParams'=>array('rows'=>6, 'cols'=>80), + 'comment' => 'Full text of the note', + 'label' => 'LBL_DESCRIPTION', + ), + ), + ), + 'LBL_PANEL_ADVANCED' => + array ( + + array ( + array ( + 'name' => 'account_type', + 'comment' => 'The Company is of this type', + 'label' => 'LBL_TYPE', + ), + array ( + 'name' => 'industry', + 'comment' => 'The company belongs in this industry', + 'label' => 'LBL_INDUSTRY', + ), + ), + + array ( + array ( + 'name' => 'annual_revenue', + 'comment' => 'Annual revenue for this company', + 'label' => 'LBL_ANNUAL_REVENUE', + ), + array ( + 'name' => 'employees', + 'comment' => 'Number of employees, varchar to accomodate for both number (100) or range (50-100)', + 'label' => 'LBL_EMPLOYEES', + ), + ), + + array ( + array ( + 'name' => 'sic_code', + 'comment' => 'SIC code of the account', + 'label' => 'LBL_SIC_CODE', + ), + array ( + 'name' => 'ticker_symbol', + 'comment' => 'The stock trading (ticker) symbol for the company', + 'label' => 'LBL_TICKER_SYMBOL', + ), + ), + + array ( + array ( + 'name' => 'parent_name', + 'label' => 'LBL_MEMBER_OF', + ), + array ( + 'name' => 'ownership', + 'comment' => '', + 'label' => 'LBL_OWNERSHIP', + ), + ), + + array ( + 'campaign_name', + + array ( + 'name' => 'rating', + 'comment' => 'An arbitrary rating for this company for use in comparisons with others', + 'label' => 'LBL_RATING', + ), + ), + ), + 'LBL_PANEL_ASSIGNMENT' => + array ( + array ( + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO', + ), + array ( + 'name' => 'date_modified', + 'label' => 'LBL_DATE_MODIFIED', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', + ), + ), + array ( + array ( + 'name' => 'date_entered', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}', + ), + ), + ), + ) +); +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/610/oob/modules/Accounts/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/610/oob/modules/Accounts/metadata/detailviewdefs.php new file mode 100755 index 00000000..91cd3370 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/610/oob/modules/Accounts/metadata/detailviewdefs.php @@ -0,0 +1,206 @@ + array('form' => array('buttons'=>array('EDIT', 'DUPLICATE', 'DELETE', 'FIND_DUPLICATES')), + 'maxColumns' => '2', + 'widths' => array( + array('label' => '10', 'field' => '30'), + array('label' => '10', 'field' => '30') + ), + 'includes'=> array( + array('file'=>'modules/Accounts/Account.js'), + ), + ), + 'panels' => + array ( + 'lbl_account_information' => + array ( + array ( + array ( + 'name' => 'name', + 'comment' => 'Name of the Company', + 'label' => 'LBL_NAME', + ), + array ( + 'name' => 'phone_office', + 'comment' => 'The office phone number', + 'label' => 'LBL_PHONE_OFFICE', + ), + ), + + array ( + + array ( + 'name' => 'website', + 'type' => 'link', + 'label' => 'LBL_WEBSITE', + 'displayParams' => + array ( + 'link_target' => '_blank', + ), + ), + array ( + 'name' => 'phone_fax', + 'comment' => 'The fax phone number of this company', + 'label' => 'LBL_FAX', + ), + ), + + array ( + array ( + 'name' => 'billing_address_street', + 'label' => 'LBL_BILLING_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'billing', + ), + ), + + array ( + 'name' => 'shipping_address_street', + 'label' => 'LBL_SHIPPING_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'shipping', + ), + ), + ), + + array ( + array ( + 'name' => 'email1', + 'studio' => 'false', + 'label' => 'LBL_EMAIL', + ), + ), + array ( + array ( + 'name' => 'description', + 'comment' => 'Full text of the note', + 'label' => 'LBL_DESCRIPTION', + ), + ), + ), + 'LBL_PANEL_ADVANCED' => + array ( + + array ( + array ( + 'name' => 'account_type', + 'comment' => 'The Company is of this type', + 'label' => 'LBL_TYPE', + ), + array ( + 'name' => 'industry', + 'comment' => 'The company belongs in this industry', + 'label' => 'LBL_INDUSTRY', + ), + ), + + array ( + array ( + 'name' => 'annual_revenue', + 'comment' => 'Annual revenue for this company', + 'label' => 'LBL_ANNUAL_REVENUE', + ), + array ( + 'name' => 'employees', + 'comment' => 'Number of employees, varchar to accomodate for both number (100) or range (50-100)', + 'label' => 'LBL_EMPLOYEES', + ), + ), + + array ( + array ( + 'name' => 'sic_code', + 'comment' => 'SIC code of the account', + 'label' => 'LBL_SIC_CODE', + ), + array ( + 'name' => 'ticker_symbol', + 'comment' => 'The stock trading (ticker) symbol for the company', + 'label' => 'LBL_TICKER_SYMBOL', + ), + ), + + array ( + array ( + 'name' => 'parent_name', + 'label' => 'LBL_MEMBER_OF', + ), + array ( + 'name' => 'ownership', + 'comment' => '', + 'label' => 'LBL_OWNERSHIP', + ), + ), + + array ( + 'campaign_name', + + array ( + 'name' => 'rating', + 'comment' => 'An arbitrary rating for this company for use in comparisons with others', + 'label' => 'LBL_RATING', + ), + ), + ), + 'LBL_PANEL_ASSIGNMENT' => + array ( + array ( + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO', + ), + array ( + 'name' => 'date_modified', + 'label' => 'LBL_DATE_MODIFIED', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', + ), + ), + array ( + array ( + 'name' => 'date_entered', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}', + ), + ), + ), + ) +); +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Accounts/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Accounts/metadata/detailviewdefs.php new file mode 100755 index 00000000..67b29bfe --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Accounts/metadata/detailviewdefs.php @@ -0,0 +1,167 @@ + + array ( + 'form' => + array ( + 'buttons' => + array ( + 0 => 'EDIT', + 1 => 'DUPLICATE', + 2 => 'DELETE', + 3 => 'FIND_DUPLICATES', + ), + ), + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + 'includes' => + array ( + 0 => + array ( + 'file' => 'modules/Accounts/Account.js', + ), + ), + ), + 'panels' => + array ( + 'default' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'name', + 'label' => 'LBL_NAME', + ), + 1 => + array ( + 'name' => 'phone_office', + 'label' => 'LBL_PHONE_OFFICE', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'account_type', + 'label' => 'LBL_TYPE', + ), + 1 => + array ( + 'name' => 'phone_alternate', + 'label' => 'LBL_OTHER_PHONE', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'team_name', + 'label' => 'LBL_TEAM', + ), + 1 => + array ( + 'name' => 'phone_fax', + 'label' => 'LBL_FAX', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO', + ), + 1 => + array ( + 'name' => 'date_modified', + 'label' => 'LBL_DATE_MODIFIED', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', + ), + ), + 4 => + array ( + 0 => NULL, + 1 => + array ( + 'name' => 'date_entered', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}', + 'label' => 'LBL_DATE_ENTERED', + ), + ), + 5 => + array ( + 0 => + array ( + 'name' => 'billing_address_street', + 'label' => 'LBL_BILLING_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'billing', + ), + ), + 1 => + array ( + 'name' => 'shipping_address_street', + 'label' => 'LBL_SHIPPING_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'shipping', + ), + ), + ), + 6 => + array ( + 0 => + array ( + 'name' => 'description', + 'label' => 'LBL_DESCRIPTION', + ), + 1 => NULL, + ), + 7 => + array ( + 0 => + array ( + 'name' => 'email1', + 'label' => 'LBL_EMAIL', + ), + 1 => + array ( + 'name' => 'website', + 'type' => 'link', + 'label' => 'LBL_WEBSITE', + 'displayParams' => + array ( + 'link_target' => '_blank', + ), + ), + ), + 8 => + array ( + 0 => NULL, + 1 => NULL, + ), + 11 => + array ( + 0 => 'campaign_name', + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Accounts/metadata/listviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Accounts/metadata/listviewdefs.php new file mode 100755 index 00000000..8cf9a423 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Accounts/metadata/listviewdefs.php @@ -0,0 +1,150 @@ + + array ( + 'width' => '20', + 'label' => 'LBL_LIST_ACCOUNT_NAME', + 'link' => true, + 'default' => true, + ), + 'ACCOUNT_TYPE_C' => + array ( + 'width' => '10%', + 'label' => 'LBL_ACCOUNT_TYPE', + 'default' => true, + ), + 'OWNERSHIP' => + array ( + 'width' => '10%', + 'label' => 'LBL_OWNERSHIP', + 'default' => true, + ), + 'DCI_OR_DBS_C' => + array ( + 'width' => '10%', + 'label' => 'LBL_DCI_OR_DBS', + 'default' => true, + ), + 'PHONE_OFFICE' => + array ( + 'width' => '10%', + 'label' => 'LBL_LIST_PHONE', + 'default' => true, + ), + 'PHONE_FAX' => + array ( + 'width' => '10%', + 'label' => 'LBL_PHONE_FAX', + 'default' => true, + ), + 'ASSIGNED_USER_NAME' => + array ( + 'width' => '10', + 'label' => 'LBL_LIST_ASSIGNED_USER', + 'default' => true, + ), + 'ANNUAL_REVENUE' => + array ( + 'width' => '10%', + 'label' => 'LBL_ANNUAL_REVENUE', + 'default' => false, + ), + 'INDUSTRY' => + array ( + 'width' => '10%', + 'label' => 'LBL_INDUSTRY', + 'default' => false, + ), + 'TEAM_NAME' => + array ( + 'width' => '10', + 'label' => 'LBL_LIST_TEAM', + 'default' => true, + ), + 'PHONE_ALTERNATE' => + array ( + 'width' => '10%', + 'label' => 'LBL_OTHER_PHONE', + 'default' => false, + ), + 'WEBSITE' => + array ( + 'width' => '10%', + 'label' => 'LBL_WEBSITE', + 'default' => false, + ), + 'BILLING_ADDRESS_STREET' => + array ( + 'width' => '15%', + 'label' => 'LBL_BILLING_ADDRESS_STREET', + 'default' => false, + ), + 'BILLING_ADDRESS_COUNTRY' => + array ( + 'width' => '10%', + 'label' => 'LBL_BILLING_ADDRESS_COUNTRY', + 'default' => false, + ), + 'BILLING_ADDRESS_CITY' => + array ( + 'width' => '10%', + 'label' => 'LBL_LIST_CITY', + 'default' => false, + ), + 'BILLING_ADDRESS_POSTALCODE' => + array ( + 'width' => '10%', + 'label' => 'LBL_BILLING_ADDRESS_POSTALCODE', + 'default' => false, + ), + 'BILLING_ADDRESS_STATE' => + array ( + 'width' => '7%', + 'label' => 'LBL_BILLING_ADDRESS_STATE', + 'default' => false, + ), + 'EMPLOYEES' => + array ( + 'width' => '10%', + 'label' => 'LBL_EMPLOYEES', + 'default' => false, + ), + 'SIC_CODE' => + array ( + 'width' => '10%', + 'label' => 'LBL_SIC_CODE', + 'default' => false, + ), + 'TICKER_SYMBOL' => + array ( + 'width' => '10%', + 'label' => 'LBL_TICKER_SYMBOL', + 'default' => false, + ), + 'DATE_MODIFIED' => + array ( + 'width' => '10%', + 'label' => 'LBL_DATE_MODIFIED', + 'default' => false, + ), + 'DATE_ENTERED' => + array ( + 'width' => '5%', + 'label' => 'LBL_DATE_ENTERED', + 'default' => false, + ), + 'CREATED_BY_NAME' => + array ( + 'width' => '10%', + 'label' => 'LBL_CREATED', + 'default' => false, + ), + 'MODIFIED_BY_NAME' => + array ( + 'width' => '10', + 'label' => 'LBL_MODIFIED', + 'default' => false, + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Contacts/metadata/editviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Contacts/metadata/editviewdefs.php new file mode 100755 index 00000000..c5af948a --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Contacts/metadata/editviewdefs.php @@ -0,0 +1,270 @@ + + array ( + 'form' => + array ( + 'hidden' => + array ( + 0 => '', + 1 => '', + 2 => '', + 3 => '', + 4 => '', + ), + ), + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + ), + 'panels' => + array ( + 'lbl_contact_information' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'first_name', + 'customCode' => '{html_options name="salutation" options=$fields.salutation.options selected=$fields.salutation.value} ', + 'label' => 'LBL_FIRST_NAME', + ), + 1 => + array ( + 'name' => 'last_name', + 'displayParams' => + array ( + 'required' => true, + ), + 'label' => 'LBL_LAST_NAME', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'personeels_id_c', + 'label' => 'LBL_PERSONEELS_ID', + ), + 1 => + array ( + 'name' => 'account_name', + 'displayParams' => + array ( + 'key' => 'billing', + 'copy' => 'primary', + 'billingKey' => 'primary', + 'additionalFields' => + array ( + 'phone_office' => 'phone_work', + ), + ), + 'label' => 'LBL_ACCOUNT_NAME', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'phone_work', + 'label' => 'LBL_OFFICE_PHONE', + ), + 1 => + array ( + 'name' => 'phone_mobile', + 'label' => 'LBL_MOBILE_PHONE', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'phone_other', + 'label' => 'LBL_OTHER_PHONE', + ), + 1 => + array ( + 'name' => 'lead_source', + 'label' => 'LBL_LEAD_SOURCE', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'phone_home', + 'label' => 'LBL_HOME_PHONE', + ), + 1 => + array ( + 'name' => 'phone_fax', + 'label' => 'LBL_FAX_PHONE', + ), + ), + 5 => + array ( + 0 => + array ( + 'name' => 'department', + 'label' => 'LBL_DEPARTMENT', + ), + 1 => + array ( + 'name' => 'title', + 'label' => 'LBL_TITLE', + ), + ), + 6 => + array ( + 0 => + array ( + 'name' => 'report_to_name', + 'label' => 'LBL_REPORTS_TO', + ), + 1 => + array ( + 'name' => 'contactpersoon_c', + 'label' => 'LBL_CONTACTPERSOON', + ), + ), + 7 => + array ( + 0 => + array ( + 'name' => 'birthdate', + 'label' => 'LBL_BIRTHDATE', + ), + 1 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO_NAME', + ), + ), + 8 => + array ( + 0 => + array ( + 'name' => 'sync_contact', + 'label' => 'LBL_SYNC_CONTACT', + ), + 1 => + array ( + 'name' => 'team_name', + 'displayParams' => + array ( + 'display' => true, + ), + 'label' => 'LBL_TEAM', + ), + ), + ), + 'lbl_address_information' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'nulmeting_sturen_c', + 'studio' => 'visible', + 'label' => 'LBL_NULMETING_STUREN', + ), + 1 => + array ( + 'name' => 'datum_nulmeeting_verzonden_c', + 'label' => 'LBL_DATUM_NULMEETING_VERZONDEN', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'deelnemende_bedrijven_c', + 'studio' => 'visible', + 'label' => 'LBL_DEELNEMENDE_BEDRIJVEN', + ), + ), + ), + 'lbl_panel1' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'primary_address_street', + 'label' => 'LBL_PRIMARY_ADDRESS_STREET', + ), + 1 => + array ( + 'name' => 'alt_address_street', + 'label' => 'LBL_ALT_ADDRESS_STREET', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'primary_address_postalcode', + 'label' => 'LBL_PRIMARY_ADDRESS_POSTALCODE', + ), + 1 => + array ( + 'name' => 'alt_address_postalcode', + 'label' => 'LBL_ALT_ADDRESS_POSTALCODE', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'primary_address_city', + 'label' => 'LBL_PRIMARY_ADDRESS_CITY', + ), + 1 => + array ( + 'name' => 'alt_address_city', + 'label' => 'LBL_ALT_ADDRESS_CITY', + ), + ), + ), + 'lbl_email_addresses' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'email1', + 'label' => 'LBL_EMAIL_ADDRESS', + ), + ), + ), + 'lbl_description_information' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'description', + 'displayParams' => + array ( + 'rows' => 6, + 'cols' => 80, + ), + 'label' => 'LBL_DESCRIPTION', + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Contacts/metadata/searchdefs.php b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Contacts/metadata/searchdefs.php new file mode 100755 index 00000000..3377f528 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Contacts/metadata/searchdefs.php @@ -0,0 +1,170 @@ + + array ( + 'maxColumns' => '3', + 'widths' => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + 'layout' => + array ( + 'basic_search' => + array ( + 0 => + array ( + 'name' => 'first_name', + 'label' => 'LBL_FIRST_NAME', + 'default' => true, + ), + 1 => + array ( + 'name' => 'last_name', + 'label' => 'LBL_LAST_NAME', + 'default' => true, + ), + 2 => + array ( + 'name' => 'account_name', + 'label' => 'LBL_ACCOUNT_NAME', + 'default' => true, + ), + 3 => + array ( + 'name' => 'current_user_only', + 'label' => 'LBL_CURRENT_USER_FILTER', + 'type' => 'bool', + 'default' => true, + ), + 4 => + array ( + 'width' => '10%', + 'label' => 'LBL_ASSIGNED_TO_NAME', + 'default' => true, + 'name' => 'assigned_user_name', + ), + ), + 'advanced_search' => + array ( + 0 => + array ( + 'name' => 'first_name', + 'label' => 'LBL_FIRST_NAME', + 'default' => true, + ), + 1 => + array ( + 'name' => 'address_street', + 'label' => 'LBL_ANY_ADDRESS', + 'type' => 'name', + 'default' => true, + ), + 2 => + array ( + 'name' => 'phone', + 'label' => 'LBL_ANY_PHONE', + 'type' => 'name', + 'default' => true, + ), + 3 => + array ( + 'name' => 'last_name', + 'label' => 'LBL_LAST_NAME', + 'default' => true, + ), + 4 => + array ( + 'name' => 'address_city', + 'label' => 'LBL_CITY', + 'type' => 'name', + 'default' => true, + ), + 5 => + array ( + 'name' => 'email', + 'label' => 'LBL_ANY_EMAIL', + 'type' => 'name', + 'default' => true, + ), + 6 => + array ( + 'name' => 'account_name', + 'label' => 'LBL_ACCOUNT_NAME', + 'default' => true, + ), + 7 => + array ( + 'name' => 'address_state', + 'label' => 'LBL_STATE', + 'type' => 'name', + 'default' => true, + ), + 8 => + array ( + 'width' => '10%', + 'label' => 'LBL_ASSIGNED_TO_NAME', + 'default' => true, + 'name' => 'assigned_user_name', + ), + 9 => + array ( + 'width' => '10%', + 'label' => 'LBL_DATE_ENTERED', + 'default' => true, + 'name' => 'date_entered', + ), + 10 => + array ( + 'name' => 'do_not_call', + 'label' => 'LBL_DO_NOT_CALL', + 'default' => true, + ), + 11 => + array ( + 'name' => 'assistant', + 'label' => 'LBL_ASSISTANT', + 'default' => true, + ), + 12 => + array ( + 'name' => 'address_postalcode', + 'label' => 'LBL_POSTAL_CODE', + 'type' => 'name', + 'default' => true, + ), + 13 => + array ( + 'name' => 'primary_address_country', + 'label' => 'LBL_COUNTRY', + 'type' => 'name', + 'options' => 'countries_dom', + 'default' => true, + ), + 14 => + array ( + 'name' => 'lead_source', + 'label' => 'LBL_LEAD_SOURCE', + 'default' => true, + ), + 15 => + array ( + 'name' => 'assigned_user_id', + 'type' => 'enum', + 'label' => 'LBL_ASSIGNED_TO', + 'function' => + array ( + 'name' => 'get_user_array', + 'params' => + array ( + 0 => false, + ), + ), + 'default' => true, + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Leads/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Leads/metadata/detailviewdefs.php new file mode 100755 index 00000000..cfc25e35 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Leads/metadata/detailviewdefs.php @@ -0,0 +1,223 @@ + + array ( + 'form' => + array ( + 'buttons' => + array ( + 0 => 'EDIT', + 1 => 'DUPLICATE', + 2 => 'DELETE', + 3 => + array ( + 'customCode' => '', + ), + 4 => + array ( + 'customCode' => '', + ), + 5 => + array ( + 'customCode' => '', + ), + ), + 'headerTpl' => 'modules/Leads/tpls/DetailViewHeader.tpl', + ), + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + 'includes' => + array ( + 0 => + array ( + 'file' => 'modules/Leads/Lead.js', + ), + ), + ), + 'panels' => + array ( + 'default' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'full_name', + 'label' => 'LBL_NAME', + ), + 1 => + array ( + 'name' => 'account_name', + 'label' => 'LBL_ACCOUNT_NAME', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'title', + 'label' => 'LBL_TITLE', + ), + 1 => + array ( + 'name' => 'phone_work', + 'label' => 'LBL_OFFICE_PHONE', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'phone_other', + 'label' => 'LBL_OTHER_PHONE', + ), + 1 => + array ( + 'name' => 'phone_fax', + 'label' => 'LBL_FAX_PHONE', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'lead_source', + 'label' => 'LBL_LEAD_SOURCE', + ), + 1 => + array ( + 'name' => 'lead_source_description', + 'label' => 'LBL_LEAD_SOURCE_DESCRIPTION', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'status', + 'label' => 'LBL_STATUS', + ), + 1 => + array ( + 'name' => 'manufacturers_c', + 'label' => 'LBL_MANUFACTURERS', + ), + ), + 5 => + array ( + 0 => + array ( + 'name' => 'email1', + 'label' => 'LBL_EMAIL_ADDRESS', + ), + 1 => + array ( + 'name' => 'oe_dealer_code_c', + 'label' => 'LBL_OE_DEALER_CODE', + ), + ), + 6 => + array ( + 0 => + array ( + 'name' => 'refered_by', + 'label' => 'LBL_REFERED_BY', + ), + 1 => + array ( + 'name' => 'regions_c', + 'label' => 'LBL_REGIONS', + ), + ), + 7 => + array ( + 0 => + array ( + 'name' => 'campaign_name', + 'label' => 'LBL_CAMPAIGN', + ), + 1 => + array ( + 'name' => 'department', + 'label' => 'LBL_DEPARTMENT', + ), + ), + 8 => + array ( + 0 => + array ( + 'name' => 'do_not_call', + 'label' => 'LBL_DO_NOT_CALL', + ), + 1 => + array ( + 'name' => 'team_name', + 'label' => 'LBL_TEAM', + ), + ), + 9 => + array ( + 0 => + array ( + 'name' => 'date_modified', + 'label' => 'LBL_DATE_MODIFIED', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', + ), + 1 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO', + ), + ), + 10 => + array ( + 0 => + array ( + 'name' => 'created_by', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value} ', + 'label' => 'LBL_DATE_ENTERED', + ), + 1 => 'opportunity_amount', + ), + 11 => + array ( + 0 => 'birthdate', + ), + 12 => + array ( + 0 => + array ( + 'name' => 'primary_address_street', + 'label' => 'LBL_PRIMARY_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'primary', + ), + ), + ), + 13 => + array ( + 0 => + array ( + 'name' => 'description', + 'label' => 'LBL_DESCRIPTION', + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Meetings/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Meetings/metadata/detailviewdefs.php new file mode 100755 index 00000000..c69e7966 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Meetings/metadata/detailviewdefs.php @@ -0,0 +1,128 @@ + + array ( + 'templateMeta' => + array ( + 'form' => + array ( + 'buttons' => + array ( + 0 => 'EDIT', + 1 => 'DUPLICATE', + 2 => 'DELETE', + 3 => + array ( + 'customCode' => '{if $fields.status.value != "Held"} {/if}', + ), + 4 => + array ( + 'customCode' => '{if $fields.status.value != "Held"} {/if}', + ), + ), + ), + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + ), + 'panels' => + array ( + 'default' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'name', + 'label' => 'LBL_SUBJECT', + ), + 1 => + array ( + 'name' => 'status', + 'label' => 'LBL_STATUS', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'location', + 'label' => 'LBL_LOCATION', + ), + 1 => + array ( + 'name' => 'parent_name', + 'customLabel' => '{sugar_translate label=\'LBL_MODULE_NAME\' module=$fields.parent_type.value}', + 'label' => 'LBL_LIST_RELATED_TO', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'date_start', + 'label' => 'LBL_DATE_TIME', + ), + 1 => + array ( + 'name' => 'duration_hours', + 'customCode' => '{$fields.duration_hours.value}{$MOD.LBL_HOURS_ABBREV} {$fields.duration_minutes.value}{$MOD.LBL_MINSS_ABBREV} ', + 'label' => 'LBL_DURATION', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO', + ), + 1 => + array ( + 'name' => 'created_by_name', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value} ', + 'label' => 'LBL_DATE_ENTERED', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'reminder_checked', + 'fields' => + array ( + 0 => 'reminder_checked', + 1 => 'reminder_time', + ), + 'label' => 'LBL_REMINDER', + ), + 1 => + array ( + 'name' => 'description', + 'label' => 'LBL_DESCRIPTION', + ), + ), + 5 => + array ( + 0 => + array ( + 'name' => 'meetings_opportunities_name', + ), + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Notes/metadata/searchdefs.php b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Notes/metadata/searchdefs.php new file mode 100755 index 00000000..e6cc5ee1 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Notes/metadata/searchdefs.php @@ -0,0 +1,77 @@ + + array ( + 'basic_search' => + array ( + 0 => 'name', + 1 => + array ( + 'name' => 'contact_name', + 'label' => 'LBL_CONTACT_NAME', + 'type' => 'name', + ), + ), + 'advanced_search' => + array ( + 'name' => + array ( + 'name' => 'name', + 'label' => 'LBL_NOTE_SUBJECT', + 'default' => true, + ), + 'filename' => + array ( + 'name' => 'filename', + 'label' => 'LBL_FILENAME', + 'default' => true, + ), + 'date_entered' => + array ( + 'width' => '10%', + 'label' => 'LBL_DATE_ENTERED', + 'default' => true, + 'name' => 'date_entered', + ), + 'date_modified' => + array ( + 'width' => '10%', + 'label' => 'LBL_DATE_MODIFIED', + 'default' => true, + 'name' => 'date_modified', + ), + 'portal_flag' => + array ( + 'width' => '10%', + 'label' => 'LBL_PORTAL_FLAG', + 'default' => true, + 'name' => 'portal_flag', + ), + 'embed_flag' => + array ( + 'width' => '10%', + 'label' => 'LBL_EMBED_FLAG', + 'default' => true, + 'name' => 'embed_flag', + ), + 'parent_name' => + array ( + 'width' => '10%', + 'label' => 'LBL_RELATED_TO', + 'default' => true, + 'name' => 'parent_name', + ), + ), + ), + 'templateMeta' => + array ( + 'maxColumns' => '3', + 'widths' => + array ( + 'label' => '10', + 'field' => '30', + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Opportunities/metadata/listviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Opportunities/metadata/listviewdefs.php new file mode 100755 index 00000000..ed757b90 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Opportunities/metadata/listviewdefs.php @@ -0,0 +1,165 @@ + + array ( + 'width' => '30%', + 'label' => 'LBL_LIST_OPPORTUNITY_NAME', + 'link' => true, + 'default' => true, + ), + 'SALES_STAGE' => + array ( + 'width' => '10%', + 'label' => 'LBL_LIST_SALES_STAGE', + 'default' => true, + ), + 'LEAD_SOURCE' => + array ( + 'width' => '15%', + 'label' => 'LBL_LEAD_SOURCE', + 'default' => true, + ), + 'REQREVBAND_C' => + array ( + 'width' => '10%', + 'label' => 'LBL_REQREVBAND', + 'default' => true, + ), + 'AMOUNT_USDOLLAR' => + array ( + 'width' => '50%', + 'label' => 'LBL_LIST_AMOUNT + {$MY CUSTOMIZATION}', + 'align' => 'right', + 'default' => true, + 'currency_format' => true, + ), + 'AIRVOLUMEDAY_C' => + array ( + 'width' => '10%', + 'label' => 'LBL_AIRVOLUMEDAY', + 'default' => true, + ), + 'TERRITORY_C' => + array ( + 'width' => '10%', + 'label' => 'LBL_TERRITORY', + 'default' => true, + ), + 'HOTACCOUNT_C' => + array ( + 'width' => '10%', + 'label' => 'LBL_HOTACCOUNT', + 'default' => true, + ), + 'DATE_CLOSED' => + array ( + 'width' => '10%', + 'label' => 'LBL_LIST_DATE_CLOSED', + 'default' => true, + ), + 'ROE_DENIED_C' => + array ( + 'width' => '10%', + 'label' => 'LBL_ROE_DENIED', + 'default' => true, + ), + 'SSRLEAD_C' => + array ( + 'type' => 'bool', + 'default' => true, + 'label' => 'LBL_SSRLEAD', + 'width' => '10%', + ), + 'ASSIGNED_USER_NAME' => + array ( + 'width' => '5%', + 'label' => 'LBL_LIST_ASSIGNED_USER', + 'default' => true, + ), + 'ACCOUNT_NAME' => + array ( + 'width' => '20%', + 'label' => 'LBL_LIST_ACCOUNT_NAME', + 'id' => 'ACCOUNT_ID', + 'module' => 'Accounts', + 'link' => true, + 'default' => false, + 'sortable' => true, + 'ACLTag' => 'ACCOUNT', + 'contextMenu' => + array ( + 'objectType' => 'sugarAccount', + 'metaData' => + array ( + 'return_module' => 'Contacts', + 'return_action' => 'ListView', + 'module' => 'Accounts', + 'parent_id' => '{$ACCOUNT_ID}', + 'parent_name' => '{$ACCOUNT_NAME}', + 'account_id' => '{$ACCOUNT_ID}', + 'account_name' => '{$ACCOUNT_NAME}', + ), + ), + 'related_fields' => + array ( + 0 => 'account_id', + ), + ), + 'NEXT_STEP' => + array ( + 'width' => '10%', + 'label' => 'LBL_NEXT_STEP', + 'default' => false, + ), + 'OPPORTUNITY_TYPE' => + array ( + 'width' => '10%', + 'label' => 'LBL_TYPE', + 'default' => false, + ), + 'TEAM_NAME' => + array ( + 'width' => '5%', + 'label' => 'LBL_LIST_TEAM', + 'default' => false, + ), + 'PROBABILITY' => + array ( + 'width' => '10%', + 'label' => 'LBL_PROBABILITY', + 'default' => false, + ), + 'DATEREQUESTED_C' => + array ( + 'width' => '10%', + 'label' => 'LBL_DATEREQUESTED', + 'default' => false, + ), + 'AMOUNT' => + array ( + 'width' => '10%', + 'label' => 'LBL_AMOUNT', + 'currency_format' => true, + 'default' => false, + ), + 'DATE_ENTERED' => + array ( + 'width' => '10%', + 'label' => 'LBL_DATE_ENTERED', + 'default' => false, + ), + 'CREATED_BY_NAME' => + array ( + 'width' => '10%', + 'label' => 'LBL_CREATED', + 'default' => false, + ), + 'MODIFIED_BY_NAME' => + array ( + 'width' => '5%', + 'label' => 'LBL_MODIFIED', + 'default' => false, + ), +); +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Project/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Project/metadata/detailviewdefs.php new file mode 100755 index 00000000..56b4f59f --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Project/metadata/detailviewdefs.php @@ -0,0 +1,123 @@ + + array ( + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + 'includes' => + array ( + 0 => + array ( + 'file' => 'modules/Project/Project.js', + ), + ), + 'form' => + array ( + 'buttons' => + array ( + 0 => + array ( + 'customCode' => '', + ), + 1 => + array ( + 'customCode' => '', + ), + 2 => + array ( + 'customCode' => '{if $EDIT_RIGHTS_ONLY}{/if}', + ), + 3 => + array ( + 'customCode' => '', + ), + 4 => + array ( + 'customCode' => '', + ), + ), + ), + ), + 'panels' => + array ( + 'lbl_panel_1' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'name', + 'label' => 'LBL_NAME', + ), + 1 => + array ( + 'name' => 'status', + 'label' => 'LBL_STATUS', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'estimated_start_date', + 'label' => 'LBL_DATE_START', + ), + 1 => + array ( + 'name' => 'estimated_end_date', + 'label' => 'LBL_DATE_END', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_USER_ID', + ), + 1 => + array ( + 'name' => 'team_name', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'priority', + 'label' => 'LBL_PRIORITY', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'description', + 'label' => 'LBL_DESCRIPTION', + ), + 1 => NULL, + ), + 5 => + array ( + 0 => + array ( + 'name' => 'kiosk_kiosk_project_name', + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Project/metadata/editviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Project/metadata/editviewdefs.php new file mode 100755 index 00000000..2fee901f --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/od_metadata_files/custom/modules/Project/metadata/editviewdefs.php @@ -0,0 +1,108 @@ + + array ( + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + 'form' => + array ( + 'hidden' => '', + 'buttons' => + array ( + 0 => 'SAVE', + 1 => + array ( + 'customCode' => '{if !empty($smarty.request.return_action) && $smarty.request.return_action == "ProjectTemplatesDetailView" && (!empty($fields.id.value) || !empty($smarty.request.return_id)) } {elseif !empty($smarty.request.return_action) && $smarty.request.return_action == "DetailView" && (!empty($fields.id.value) || !empty($smarty.request.return_id)) } {elseif $is_template} {else} {/if}', + ), + ), + ), + ), + 'panels' => + array ( + 'default' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'name', + 'label' => 'LBL_NAME', + ), + 1 => + array ( + 'name' => 'status', + 'label' => 'LBL_STATUS', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'estimated_start_date', + 'label' => 'LBL_DATE_START', + ), + 1 => + array ( + 'name' => 'estimated_end_date', + 'label' => 'LBL_DATE_END', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_USER_NAME', + ), + 1 => + array ( + 'name' => 'team_name', + 'label' => 'LBL_TEAM', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'priority', + 'label' => 'LBL_PRIORITY', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'description', + 'displayParams' => + array ( + 'rows' => '8', + 'cols' => '60', + ), + 'label' => 'LBL_DESCRIPTION', + ), + 1 => NULL, + ), + 5 => + array ( + 0 => + array ( + 'name' => 'kiosk_kiosk_project_name', + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/detailviewdefs.php new file mode 100755 index 00000000..5caaa64d --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/detailviewdefs.php @@ -0,0 +1,84 @@ + array('form' => array('buttons'=>array('EDIT', 'DUPLICATE', 'DELETE', 'FIND_DUPLICATES')), + 'maxColumns' => '2', + 'widths' => array( + array('label' => '10', 'field' => '30'), + array('label' => '10', 'field' => '30') + ), + 'includes'=> array( + array('file'=>'modules/Accounts/Account.js'), + ), + ), + 'panels' => array( + 'default'=> array( + array('name', 'phone_office'), + array(array('name'=>'website', 'type'=>'link','label'=>'LBL_WEBSITE', 'displayParams'=>array('link_target'=>'_blank')), 'phone_fax'), + array('ticker_symbol', array('name'=>'phone_alternate', 'label'=>'LBL_OTHER_PHONE')), + array('parent_name', 'employees'), + array('ownership', 'rating'), + array('industry', 'sic_code'), + array('account_type', 'annual_revenue'), + array( + array('name'=>'date_modified', 'label'=>'LBL_DATE_MODIFIED', 'customCode'=>'{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}')), + array(array('name'=>'assigned_user_name', 'label'=>'LBL_ASSIGNED_TO'), + array('name'=>'date_entered', 'customCode'=>'{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}')), + array ( + array ( + 'name' => 'billing_address_street', + 'label'=> 'LBL_BILLING_ADDRESS', + 'type' => 'address', + 'displayParams'=>array('key'=>'billing'), + ), + array ( + 'name' => 'shipping_address_street', + 'label'=> 'LBL_SHIPPING_ADDRESS', + 'type' => 'address', + 'displayParams'=>array('key'=>'shipping'), + ), + ), + + array('description'), + array('campaign_name'), + array('email1'), + ), + ), + + +); +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/editviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/editviewdefs.php new file mode 100755 index 00000000..5f7fba7c --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/editviewdefs.php @@ -0,0 +1,135 @@ + array( + 'form' => array('buttons'=>array('SAVE', 'CANCEL')), + 'maxColumns' => '2', + 'widths' => array( + array('label' => '10', 'field' => '30'), + array('label' => '10', 'field' => '30'), + ), + 'includes'=> array( + array('file'=>'modules/Accounts/Account.js'), + ), + ), + + 'panels' => array( + 'lbl_account_information'=>array( + array( + array( + 'name'=>'name', + 'label'=>'LBL_NAME', + 'displayParams'=>array('required'=>true) + ), + array( + 'name'=>'phone_office', + 'label'=>'LBL_PHONE_OFFICE' + ) + + ), + array( + array( + 'name'=>'website', + 'type'=>'link', + 'label'=>'LBL_WEBSITE' + ), + array( + 'name'=>'phone_fax', + 'label'=>'LBL_PHONE_FAX' + ) + ), + array( + array( + 'name'=>'ticker_symbol', + 'label'=>'LBL_TICKER_SYMBOL' + ), + array( + 'name'=>'phone_alternate', + 'label'=>'LBL_OTHER_PHONE' + ) + ), + array( + array('name'=>'parent_name','label' => 'LBL_MEMBER_OF'), + array('name'=>'employees','label' => 'LBL_EMPLOYEES' ) + ), + array( + array('name'=>'ownership','label' => 'LBL_OWNERSHIP'), + array('name'=>'rating','label' => 'LBL_RATING' ) + ), + array( + array('name'=>'industry','label' => 'LBL_INDUSTRY'), + array('name'=>'sic_code','label' => 'LBL_SIC_CODE' ) + ), + array( + array('name'=>'account_type'), + array('name'=>'annual_revenue','label' => 'LBL_ANNUAL_REVENUE' ) + ), + array( + array('name'=>'campaign_name') + ), + array( + array('name'=>'assigned_user_name','label' =>'LBL_ASSIGNED_TO') + ) + ), + 'lbl_address_information'=>array( + array ( + array ( + 'name' => 'billing_address_street', + 'hideLabel'=> true, + 'type' => 'address', + 'displayParams'=>array('key'=>'billing', 'rows'=>2, 'cols'=>30, 'maxlength'=>150), + ), + array ( + 'name' => 'shipping_address_street', + 'hideLabel' => true, + 'type' => 'address', + 'displayParams'=>array('key'=>'shipping', 'copy'=>'billing', 'rows'=>2, 'cols'=>30, 'maxlength'=>150), + ), + ), + ), + + 'lbl_email_addresses'=>array( + array('email1') + ), + + 'lbl_description_information' =>array( + array(array('name'=>'description', 'displayParams'=>array('cols'=>80, 'rows'=>6),'label' => 'LBL_DESCRIPTION')), + ), + + ) +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/listviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/listviewdefs.php new file mode 100755 index 00000000..0c46156f --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/listviewdefs.php @@ -0,0 +1,133 @@ + array( + 'width' => '20', + 'label' => 'LBL_LIST_ACCOUNT_NAME', + 'link' => true, + 'default' => true), + 'BILLING_ADDRESS_CITY' => array( + 'width' => '10', + 'label' => 'LBL_LIST_CITY', + 'default' => true + ), + 'PHONE_OFFICE' => array( + 'width' => '10', + 'label' => 'LBL_LIST_PHONE', + 'default' => true), + 'ACCOUNT_TYPE' => array( + 'width' => '10', + 'label' => 'LBL_TYPE'), + 'INDUSTRY' => array( + 'width' => '10', + 'label' => 'LBL_INDUSTRY'), + 'ANNUAL_REVENUE' => array( + 'width' => '10', + 'label' => 'LBL_ANNUAL_REVENUE'), + 'PHONE_FAX' => array( + 'width' => '10', + 'label' => 'LBL_PHONE_FAX'), + 'BILLING_ADDRESS_STREET' => array( + 'width' => '15', + 'label' => 'LBL_BILLING_ADDRESS_STREET'), + 'BILLING_ADDRESS_STATE' => array( + 'width' => '7', + 'label' => 'LBL_BILLING_ADDRESS_STATE'), + 'BILLING_ADDRESS_POSTALCODE' => array( + 'width' => '10', + 'label' => 'LBL_BILLING_ADDRESS_POSTALCODE'), + 'BILLING_ADDRESS_COUNTRY' => array( + 'width' => '10', + 'label' => 'LBL_BILLING_ADDRESS_COUNTRY'), + 'SHIPPING_ADDRESS_STREET' => array( + 'width' => '15', + 'label' => 'LBL_SHIPPING_ADDRESS_STREET'), + 'SHIPPING_ADDRESS_CITY' => array( + 'width' => '10', + 'label' => 'LBL_SHIPPING_ADDRESS_CITY'), + 'SHIPPING_ADDRESS_STATE' => array( + 'width' => '7', + 'label' => 'LBL_SHIPPING_ADDRESS_STATE'), + 'SHIPPING_ADDRESS_POSTALCODE' => array( + 'width' => '10', + 'label' => 'LBL_SHIPPING_ADDRESS_POSTALCODE'), + 'SHIPPING_ADDRESS_COUNTRY' => array( + 'width' => '10', + 'label' => 'LBL_SHIPPING_ADDRESS_COUNTRY'), + 'RATING' => array( + 'width' => '10', + 'label' => 'LBL_RATING'), + 'PHONE_ALTERNATE' => array( + 'width' => '10', + 'label' => 'LBL_OTHER_PHONE'), + 'WEBSITE' => array( + 'width' => '10', + 'label' => 'LBL_WEBSITE'), + 'OWNERSHIP' => array( + 'width' => '10', + 'label' => 'LBL_OWNERSHIP'), + 'EMPLOYEES' => array( + 'width' => '10', + 'label' => 'LBL_EMPLOYEES'), + 'SIC_CODE' => array( + 'width' => '10', + 'label' => 'LBL_SIC_CODE'), + 'TICKER_SYMBOL' => array( + 'width' => '10', + 'label' => 'LBL_TICKER_SYMBOL'), + 'DATE_MODIFIED' => array( + 'width' => '5', + 'label' => 'LBL_DATE_MODIFIED'), + 'DATE_ENTERED' => array( + 'width' => '5', + 'label' => 'LBL_DATE_ENTERED'), + 'CREATED_BY_NAME' => array( + 'width' => '10', + 'label' => 'LBL_CREATED'), + 'ASSIGNED_USER_NAME' => array( + 'width' => '10', + 'label' => 'LBL_LIST_ASSIGNED_USER', + 'default' => true), + 'MODIFIED_BY_NAME' => array( + 'width' => '10', + 'label' => 'LBL_MODIFIED') +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/searchdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/searchdefs.php new file mode 100755 index 00000000..1271ad17 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Accounts/metadata/searchdefs.php @@ -0,0 +1,78 @@ + array( + 'maxColumns' => '3', + 'widths' => array('label' => '10', 'field' => '30'), + ), + 'layout' => array( + 'basic_search' => array( + 'name', + 'billing_address_city', + 'phone_office', + array('name' => 'address_street', 'label' =>'LBL_BILLING_ADDRESS', 'type' => 'name' , 'group'=>'billing_address_street'), + array('name'=>'current_user_only', 'label'=>'LBL_CURRENT_USER_FILTER', 'type'=>'bool'), + ), + 'advanced_search' => array( + 'name', + array('name' => 'address_street', 'label' =>'LBL_ANY_ADDRESS', 'type' => 'name'), + array('name' => 'phone', 'label' =>'LBL_ANY_PHONE', 'type' => 'name'), + 'website', + array('name' => 'address_city', 'label' =>'LBL_CITY', 'type' => 'name'), + array('name' => 'email', 'label' =>'LBL_ANY_EMAIL', 'type' => 'name'), + 'annual_revenue', + array('name' => 'address_state', 'label' =>'LBL_STATE', 'type' => 'name'), + 'employees', + array('name' => 'address_postalcode', 'label' =>'LBL_POSTAL_CODE', 'type' => 'name'), + array('name' => 'billing_address_country', 'label' =>'LBL_COUNTRY', 'type' => 'name', 'options' => 'countries_dom', ), + 'ticker_symbol', + 'sic_code', + 'rating', + 'ownership', + array('name' => 'assigned_user_id', 'type' => 'enum', 'label' => 'LBL_ASSIGNED_TO', 'function' => array('name' => 'get_user_array', 'params' => array(false))), + 'account_type', + 'industry', + ), + ), + ); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Contacts/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Contacts/metadata/detailviewdefs.php new file mode 100755 index 00000000..76c07a39 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Contacts/metadata/detailviewdefs.php @@ -0,0 +1,171 @@ + array('form' => array('buttons'=>array('EDIT', 'DUPLICATE', 'DELETE', 'FIND_DUPLICATES', + array('customCode'=>''), + ), + ), + 'maxColumns' => '2', + 'widths' => array( + array('label' => '10', 'field' => '30'), + array('label' => '10', 'field' => '30') + ), + 'includes'=> array( + array('file'=>'modules/Leads/Lead.js'), + ), + ), +'panels' =>array ( + 'default'=>array( + array ( + array ( + 'name' => 'full_name', + 'label' => 'LBL_NAME', + ), + + array ( + 'name' => 'phone_work', + 'label' => 'LBL_OFFICE_PHONE', + ), + ), + + array ( + 'account_name', + + array ( + 'name' => 'phone_mobile', + 'label' => 'LBL_MOBILE_PHONE', + ), + ), + + array ( + 'lead_source', + + array ( + 'name' => 'phone_home', + 'label' => 'LBL_HOME_PHONE', + ), + ), + + array ( + + array ( + 'name' => 'campaign_name', + 'label' => 'LBL_CAMPAIGN', + ), + + array ( + 'name' => 'phone_other', + 'label' => 'LBL_OTHER_PHONE', + ), + ), + + array ( + 'title', + array ( + 'name' => 'phone_fax', + 'label' => 'LBL_FAX_PHONE', + ), + ), + + array ( + 'department', + 'birthdate', + ), + + array ( + 'report_to_name', + 'assistant', + ), + + array ( + 'sync_contact', + 'assistant_phone', + ), + + array ( + 'do_not_call', + '', + ), + + array ( + + array ( + 'name' => 'date_modified', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', + 'label' => 'LBL_DATE_MODIFIED', + ), + ), + + array ( + 'assigned_user_name', + + array ( + 'name' => 'date_entered', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}', + 'label' => 'LBL_DATE_ENTERED', + ), + ), + + array ( + array ( + 'name' => 'primary_address_street', + 'label'=> 'LBL_PRIMARY_ADDRESS', + 'type' => 'address', + 'displayParams'=>array('key'=>'primary'), + ), + + array ( + 'name' => 'alt_address_street', + 'label'=> 'LBL_ALTERNATE_ADDRESS', + 'type' => 'address', + 'displayParams'=>array('key'=>'alt'), + ), + ), + array ( + 'description', + ), + + array ( + 'email1', + ), + ), +) + + + +); +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Contacts/metadata/editviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Contacts/metadata/editviewdefs.php new file mode 100755 index 00000000..10adc069 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Contacts/metadata/editviewdefs.php @@ -0,0 +1,145 @@ + array('form'=>array('hidden'=>array('', + '', + '', + '', + '')), + 'maxColumns' => '2', + 'widths' => array( + array('label' => '10', 'field' => '30'), + array('label' => '10', 'field' => '30'), + ), +), + 'panels' =>array ( + 'lbl_contact_information' => + array ( + + array ( + array ( + 'name' => 'first_name', + 'customCode' => '{html_options name="salutation" options=$fields.salutation.options selected=$fields.salutation.value} ', + ), + 'phone_work', + ), + + array ( + array('name'=>'last_name', + 'displayParams'=>array('required'=>true), + ), + 'phone_mobile', + ), + + array ( + array('name'=>'account_name', 'displayParams'=>array('key'=>'billing', 'copy'=>'primary', 'billingKey'=>'primary', 'additionalFields'=>array('phone_office'=>'phone_work'))), + 'phone_home', + ), + + array ( + 'lead_source', + 'phone_other', + ), + + array ( + 'campaign_name', + 'phone_fax', + ), + + array ( + 'title', + 'birthdate', + ), + + array ( + 'department', + ), + + array ( + 'report_to_name', + 'assistant', + ), + + array ( + 'sync_contact', + 'assistant_phone', + ), + + array ( + 'do_not_call', + ), + + + array ( + 'assigned_user_name', + ), + ), + 'lbl_email_addresses'=>array( + array('email1') + ), + 'lbl_address_information' => + array ( + array ( + array ( + 'name' => 'primary_address_street', + 'hideLabel' => true, + 'type' => 'address', + 'displayParams'=>array('key'=>'primary', 'rows'=>2, 'cols'=>30, 'maxlength'=>150), + ), + + array ( + 'name' => 'alt_address_street', + 'hideLabel'=>true, + 'type' => 'address', + 'displayParams'=>array('key'=>'alt', 'copy'=>'primary', 'rows'=>2, 'cols'=>30, 'maxlength'=>150), + ), + ), + ), + + 'lbl_description_information' => + array ( + array ( + array('name'=>'description', + 'displayParams'=>array('rows'=>6, 'cols'=>80), + 'label'=>'LBL_DESCRIPTION'), + ), + ), +) + + +); +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Opportunities/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Opportunities/metadata/detailviewdefs.php new file mode 100755 index 00000000..4937bee5 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Opportunities/metadata/detailviewdefs.php @@ -0,0 +1,65 @@ + array('form' => array('buttons'=>array('EDIT', 'DUPLICATE', 'DELETE', + array('customCode'=>''),)), + 'maxColumns' => '2', + 'widths' => array( + array('label' => '10', 'field' => '30'), + array('label' => '10', 'field' => '30') + ), + ), + 'panels' => array( + array('name', array('name'=>'amount','label' => '{$MOD.LBL_AMOUNT} ({$CURRENCY})'),), + array('account_name','date_closed'), + array('opportunity_type', 'next_step'), + array('lead_source', 'sales_stage'), + array('campaign_name'), + array( + 'probability'), + array('assigned_user_name', array('name'=>'date_modified', 'label'=>'LBL_DATE_MODIFIED', 'customCode'=>'{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}')), + array('', array('name'=>'date_entered', 'customCode'=>'{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}')), + array(array('name' => 'description', 'nl2br' => true)), + ) +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Opportunities/metadata/editviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Opportunities/metadata/editviewdefs.php new file mode 100755 index 00000000..bc7e5fa4 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Opportunities/metadata/editviewdefs.php @@ -0,0 +1,90 @@ + array('maxColumns' => '2', + 'widths' => array( + array('label' => '10', 'field' => '30'), + array('label' => '10', 'field' => '30') + ), + 'javascript' => '{$PROBABILITY_SCRIPT}', +), + 'panels' =>array ( + 'default' => + array ( + + array ( + array('name'=>'name', 'displayParams'=>array('required'=>true)), + array('name'=>'currency_id','label'=>'LBL_CURRENCY'), + ), + + array ( + 'account_name', + array( 'name'=>'amount','displayParams'=>array('required'=>true)), + ), + + array ( + 'opportunity_type', + array('name'=>'date_closed', 'displayParams'=>array('required'=>true)), + ), + + array ( + 'lead_source', + 'next_step', + ), + + array ( + 'campaign_name', + ), + + array ( + array('name'=>'sales_stage', 'displayParams'=>array('required'=>true)), + ), + + array ( + 'assigned_user_name', + 'probability', + ), + + array ( + 'description', + ), + ), +) + + +); +?> \ No newline at end of file diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Opportunities/metadata/searchdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Opportunities/metadata/searchdefs.php new file mode 100755 index 00000000..112371a6 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/551/modules/Opportunities/metadata/searchdefs.php @@ -0,0 +1,63 @@ + array( + 'maxColumns' => '3', + 'widths' => array('label' => '10', 'field' => '30'), + ), + 'layout' => array( + 'basic_search' => array( + 'name', + 'account_name', + array('name'=>'current_user_only', 'label'=>'LBL_CURRENT_USER_FILTER', 'type'=>'bool'), + 'opportunity_type', + + ), + 'advanced_search' => array( + 'name', + 'amount', + 'date_closed', + 'account_name', + 'next_step', + 'probability', + 'lead_source', + 'sales_stage', + array('name' => 'assigned_user_id', 'type' => 'enum', 'label' => 'LBL_ASSIGNED_TO', 'function' => array('name' => 'get_user_array', 'params' => array(false))), + ), + ), + ); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Accounts/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Accounts/metadata/detailviewdefs.php new file mode 100755 index 00000000..3ce79ce8 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Accounts/metadata/detailviewdefs.php @@ -0,0 +1,428 @@ + + array ( + 'DetailView' => + array ( + 'templateMeta' => + array ( + 'form' => + array ( + 'buttons' => + array ( + 0 => 'EDIT', + 1 => 'DUPLICATE', + 2 => 'DELETE', + 3 => 'FIND_DUPLICATES', + ), + ), + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + 'includes' => + array ( + 0 => + array ( + 'file' => 'modules/Accounts/Account.js', + ), + ), + ), + 'panels' => + array ( + 'DEFAULT' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'name', + 'label' => 'LBL_NAME', + 'displayParams' => + array ( + ), + ), + 1 => + array ( + 'name' => 'subscription_expiration_c', + 'label' => 'Subscription_Expiration__c', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'high_prio_c', + 'label' => 'High_Priority_Account_c', + ), + 1 => + array ( + 'name' => 'phone_office', + 'label' => 'LBL_PHONE_OFFICE', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'website', + 'type' => 'link', + 'label' => 'LBL_WEBSITE', + 'customCode' => '{$fields.website.value}', + ), + 1 => + array ( + 'name' => 'phone_fax', + 'label' => 'LBL_PHONE_FAX', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'ticker_symbol', + 'label' => 'LBL_TICKER_SYMBOL', + ), + 1 => + array ( + 'name' => 'phone_alternate', + 'label' => 'LBL_OTHER_PHONE', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'parent_name', + 'label' => 'LBL_MEMBER_OF', + ), + 1 => + array ( + 'name' => 'email1', + 'label' => 'LBL_EMAIL', + ), + ), + 5 => + array ( + 0 => + array ( + 'name' => 'employees', + 'label' => 'LBL_EMPLOYEES', + ), + 1 => + array ( + 'name' => 'LBL_FILLER', + 'label' => 'LBL_FILLER', + ), + ), + 6 => + array ( + 0 => + array ( + 'name' => 'ownership', + 'label' => 'LBL_OWNERSHIP', + ), + 1 => + array ( + 'name' => 'rating', + 'label' => 'LBL_RATING', + ), + ), + 7 => + array ( + 0 => + array ( + 'name' => 'industry', + 'label' => 'LBL_INDUSTRY', + ), + 1 => + array ( + 'name' => 'sic_code', + 'label' => 'LBL_SIC_CODE', + ), + ), + 8 => + array ( + 0 => + array ( + 'name' => 'account_type', + 'label' => 'LBL_TYPE', + ), + 1 => + array ( + 'name' => 'annual_revenue', + 'label' => 'LBL_ANNUAL_REVENUE', + ), + ), + 9 => + array ( + 0 => + array ( + 'name' => 'reference_code_c', + 'label' => 'LBL_REFERENCE_CODE', + ), + 1 => + array ( + 'name' => 'ref_code_expiration_c', + 'label' => 'LBL_REF_CODE_EXPIRATION', + ), + ), + 10 => + array ( + 0 => + array ( + 'name' => 'contract_version', + 'label' => 'LBL_CONTRACT_VERSION', + ), + 1 => + array ( + 'name' => 'code_customized_by_c', + 'label' => 'LBL_CODE_CUSTOMIZED_BY', + ), + ), + 11 => + array ( + 0 => + array ( + 'name' => 'resell_discount', + 'label' => 'LBL_RESELL_DISCOUNT', + ), + 1 => + array ( + 'name' => 'Support_Service_Level_c', + 'label' => 'Support Service Level_0', + ), + ), + 12 => + array ( + 0 => NULL, + 1 => + array ( + 'name' => 'deployment_type_c', + 'label' => 'Deployment_Type__c', + ), + ), + 13 => + array ( + 0 => + array ( + 'name' => 'Partner_Type_c', + 'label' => 'partner_Type__c', + ), + 1 => + array ( + 'default' => 'false', + 'customCode' => '{ if $fields.deployment_type_c.value == "ondemand" || $fields.deployment_type_c.value == "ondemand_ded" || $fields.deployment_type_c.value == ""}On-Demand Account URL{/if}', + ), + ), + 14 => + array ( + 0 => + array ( + 'name' => 'auto_send_renewal_emails_c', + 'label' => 'LBL_AUTO_SEND_RENEWAL_EMAILS', + ), + 1 => + array ( + 'name' => 'renewal_contact_c', + 'label' => 'LBL_RENEWAL_CONTACT_C', + ), + ), + 15 => + array ( + 0 => + array ( + 'name' => 'team_name', + 'label' => 'LBL_LIST_TEAM', + ), + 1 => + array ( + 'name' => 'date_modified', + 'label' => 'LBL_DATE_MODIFIED', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', + ), + ), + 16 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO', + ), + 1 => + array ( + 'name' => 'date_entered', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}', + 'label' => 'LBL_DATE_ENTERED', + ), + ), + 17 => + array ( + 0 => + array ( + 'name' => 'billing_address_street', + 'label' => 'LBL_BILLING_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'billing', + ), + ), + 1 => + array ( + 'name' => 'shipping_address_street', + 'label' => 'LBL_SHIPPING_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'shipping', + ), + ), + ), + 18 => + array ( + 0 => + array ( + 'name' => 'description', + 'label' => 'LBL_DESCRIPTION', + ), + ), + 19 => + array ( + 0 => + array ( + 'name' => 'id', + 'type' => 'link', + 'label' => 'LBL_USAGE_GRAPH', + 'customCode' => 'Usage Graph', + ), + ), + ), + 'lbl_panel7' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'customer_reference_c', + 'label' => 'LBL_CUSTOMER_REFERENCE', + ), + 1 => + array ( + 'name' => 'type_of_reference_c', + 'label' => 'LBL_TYPE_OF_REFERENCE', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'reference_contact_c', + 'label' => 'LBL_REFERENCE_CONTACT', + ), + 1 => + array ( + 'name' => 'last_used_as_reference_c', + 'label' => 'LBL_LAST_USED_AS_REFERENCE', + ), + ), + 2 => + array ( + 0 => NULL, + 1 => + array ( + 'name' => 'reference_status_c', + 'label' => 'LBL_REFERENCE_STATUS', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'reference_notes_c', + 'label' => 'LBL_REFERENCE_NOTES', + ), + 1 => + array ( + 'name' => 'last_used_reference_notes_c', + 'label' => 'LBL_LAST_USED_REFERENCE_NOTES', + ), + ), + ), + 'LBL_PANEL1' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'training_credits_purchased_c', + 'label' => 'Learning_Credits_Purchased__c', + ), + 1 => + array ( + 'name' => 'remaining_training_credits_c', + 'label' => 'Remaining_Learning_Credits__c', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'training_credits_pur_date_c', + 'label' => 'Most_Recent_Credits_Purchase_Date_c', + ), + 1 => + array ( + 'name' => 'training_credits_exp_date_c', + 'label' => 'Upcoming_Credits_Expiration_Date__c', + ), + ), + ), + 'LBL_PANEL6' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'support_cases_purchased_c', + 'label' => 'Support_Cases_Purchased__c', + ), + 1 => + array ( + 'name' => 'remaining_support_cases_c', + 'label' => 'Remaining_Support_Cases__c', + ), + ), + ), + 'LBL_PANEL4' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'dce_auth_user_c', + 'label' => 'LBL_DCE_AUTH_USER', + ), + 1 => + array ( + 'name' => 'dce_app_id_c', + 'label' => 'LBL_DCE_APP_ID', + ), + ), + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Accounts/metadata/editviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Accounts/metadata/editviewdefs.php new file mode 100755 index 00000000..63cb9f94 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Accounts/metadata/editviewdefs.php @@ -0,0 +1,426 @@ + + array ( + 'templateMeta' => + array ( + 'form' => + array ( + 'buttons' => + array ( + 0 => 'SAVE', + 1 => 'CANCEL', + ), + ), + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + 'includes' => + array ( + 0 => + array ( + 'file' => 'modules/Accounts/Account.js', + ), + ), + ), + 'panels' => + array ( + 'lbl_account_information' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'name', + 'label' => 'LBL_NAME', + 'displayParams' => + array ( + 'required' => true, + ), + ), + 1 => + array ( + 'name' => 'phone_office', + 'label' => 'LBL_PHONE_OFFICE', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'high_prio_c', + 'label' => 'High_Priority_Account_c', + ), + 1 => NULL, + ), + 2 => + array ( + 0 => + array ( + 'name' => 'website', + 'type' => 'link', + 'label' => 'LBL_WEBSITE', + ), + 1 => + array ( + 'name' => 'phone_fax', + 'label' => 'LBL_PHONE_FAX', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'ticker_symbol', + 'label' => 'LBL_TICKER_SYMBOL', + ), + 1 => + array ( + 'name' => 'phone_alternate', + 'label' => 'LBL_OTHER_PHONE', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'parent_name', + 'label' => 'LBL_MEMBER_OF', + ), + ), + 5 => + array ( + 0 => + array ( + 'name' => 'employees', + 'label' => 'LBL_EMPLOYEES', + ), + 1 => NULL, + ), + 6 => + array ( + 0 => + array ( + 'name' => 'ownership', + 'label' => 'LBL_OWNERSHIP', + ), + 1 => + array ( + 'name' => 'rating', + 'label' => 'LBL_RATING', + ), + ), + 7 => + array ( + 0 => + array ( + 'name' => 'industry', + 'label' => 'LBL_INDUSTRY', + ), + 1 => + array ( + 'name' => 'sic_code', + 'label' => 'LBL_SIC_CODE', + ), + ), + 8 => + array ( + 0 => + array ( + 'name' => 'account_type', + 'label' => 'LBL_TYPE', + 'customCode' => ' + + +', + ), + 1 => + array ( + 'name' => 'annual_revenue', + 'label' => 'LBL_ANNUAL_REVENUE', + ), + ), + 9 => + array ( + 0 => + array ( + 'name' => 'reference_code_c', + 'label' => 'LBL_REFERENCE_CODE_C', + ), + 1 => + array ( + 'name' => 'ref_code_expiration_c', + 'label' => 'LBL_REF_CODE_EXPIRATION', + ), + ), + 10 => + array ( + NULL, + 1 => + array ( + 'name' => 'code_customized_by_c', + 'label' => 'LBL_CODE_CUSTOMIZED_BY', + ), + ), + 11 => + array ( + 0 => + array ( + 'name' => 'resell_discount', + 'label' => 'LBL_RESELL_DISCOUNT', + ), + 1 => + array ( + 'name' => 'Support_Service_Level_c', + 'label' => 'Support Service Level_0', + ), + ), + 12 => + array ( + 0 => + array ( + 'name' => 'Partner_Type_c', + 'label' => 'partner_Type__c', + ), + 1 => + array ( + 'name' => 'deployment_type_c', + 'label' => 'Deployment_Type__c', + ), + ), + 13 => + array ( + 0 => + array ( + 'name' => 'team_name', + 'label' => 'LBL_LIST_TEAM', + 'displayParams' => + array ( + 'display' => true, + ), + ), + 1 => array( + 'name' => 'renewal_contact_c', + 'label' => 'LBL_RENEWAL_CONTACT_C', +'displayParams' => array('initial_filter' => '&account_name_advanced={$fields.name.value}'), + ), + ), + 14 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO', + ), + 1 => + array ( + 'name' => 'auto_send_renewal_emails_c', + 'label' => 'LBL_AUTO_SEND_RENEWAL_EMAILS', + ), + ), + ), + 'lbl_panel5' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'customer_reference_c', + 'label' => 'LBL_CUSTOMER_REFERENCE', + ), + 1 => + array ( + 'name' => 'type_of_reference_c', + 'label' => 'LBL_TYPE_OF_REFERENCE', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'reference_contact_c', + 'label' => 'LBL_REFERENCE_CONTACT', + ), + 1 => + array ( + 'name' => 'last_used_as_reference_c', + 'label' => 'LBL_LAST_USED_AS_REFERENCE', + ), + ), + 2 => + array ( + 0 => NULL, + 1 => + array ( + 'name' => 'reference_status_c', + 'label' => 'LBL_REFERENCE_STATUS', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'reference_notes_c', + 'label' => 'LBL_REFERENCE_NOTES', + ), + 1 => + array ( + 'name' => 'last_used_reference_notes_c', + 'label' => 'LBL_LAST_USED_REFERENCE_NOTES', + ), + ), + ), + 'lbl_panel1' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'training_credits_purchased_c', + 'label' => 'Learning_Credits_Purchased__c', + ), + 1 => + array ( + 'name' => 'remaining_training_credits_c', + 'label' => 'Remaining_Learning_Credits__c', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'training_credits_pur_date_c', + 'label' => 'Most_Recent_Credits_Purchase_Date_c', + ), + 1 => + array ( + 'name' => 'training_credits_exp_date_c', + 'label' => 'Upcoming_Credits_Expiration_Date__c', + ), + ), + ), + 'LBL_PANEL6' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'support_cases_purchased_c', + 'label' => 'Support_Cases_Purchased__c', + ), + 1 => + array ( + 'name' => 'remaining_support_cases_c', + 'label' => 'Remaining_Support_Cases__c', + ), + ), + ), + 'lbl_panel4' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'dce_auth_user_c', + 'label' => 'LBL_DCE_AUTH_USER', + ), + 1 => + array ( + 'name' => 'dce_app_id_c', + 'label' => 'LBL_DCE_APP_ID', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'dce_auth_pass_c', + 'label' => 'LBL_DCE_AUTH_PASSWORD', + ), + 1 => NULL, + ), + ), + 'lbl_address_information' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'billing_address_street', + 'hideLabel' => true, + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'billing', + 'rows' => 2, + 'cols' => 30, + 'maxlength' => 150, + ), + 'label' => 'LBL_BILLING_ADDRESS_STREET', + ), + 1 => + array ( + 'name' => 'shipping_address_street', + 'hideLabel' => true, + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'shipping', + 'copy' => 'billing', + 'rows' => 2, + 'cols' => 30, + 'maxlength' => 150, + ), + 'label' => 'LBL_SHIPPING_ADDRESS_STREET', + ), + ), + ), + 'lbl_email_addresses' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'email1', + 'label' => 'LBL_EMAIL', + ), + ), + ), + 'lbl_description_information' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'description', + 'displayParams' => + array ( + 'cols' => 80, + 'rows' => 6, + ), + 'label' => 'LBL_DESCRIPTION', + ), + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Accounts/metadata/listviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Accounts/metadata/listviewdefs.php new file mode 100755 index 00000000..2b170762 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Accounts/metadata/listviewdefs.php @@ -0,0 +1,180 @@ + + array ( + 'width' => '40%', + 'label' => 'LBL_LIST_ACCOUNT_NAME', + 'link' => true, + 'default' => true, + ), + 'BILLING_ADDRESS_CITY' => + array ( + 'width' => '10%', + 'label' => 'LBL_LIST_CITY', + 'default' => true, + ), + 'BILLING_ADDRESS_STATE' => + array ( + 'width' => '7%', + 'label' => 'LBL_BILLING_ADDRESS_STATE', + 'default' => true, + ), + 'PHONE_OFFICE' => + array ( + 'width' => '10%', + 'label' => 'LBL_LIST_PHONE', + 'default' => true, + ), + 'TEAM_NAME' => + array ( + 'width' => '2%', + 'label' => 'LBL_LIST_TEAM', + 'default' => true, + ), + 'ASSIGNED_USER_NAME' => + array ( + 'width' => '2%', + 'label' => 'LBL_LIST_ASSIGNED_USER', + 'default' => true, + ), + 'ACCOUNT_TYPE' => + array ( + 'width' => '10%', + 'label' => 'LBL_TYPE', + 'default' => false, + ), + 'INDUSTRY' => + array ( + 'width' => '10%', + 'label' => 'LBL_INDUSTRY', + 'default' => false, + ), + 'ANNUAL_REVENUE' => + array ( + 'width' => '10%', + 'label' => 'LBL_ANNUAL_REVENUE', + 'default' => false, + ), + 'PHONE_FAX' => + array ( + 'width' => '10%', + 'label' => 'LBL_PHONE_FAX', + 'default' => false, + ), + 'BILLING_ADDRESS_STREET' => + array ( + 'width' => '15%', + 'label' => 'LBL_BILLING_ADDRESS_STREET', + 'default' => false, + ), + 'BILLING_ADDRESS_POSTALCODE' => + array ( + 'width' => '10%', + 'label' => 'LBL_BILLING_ADDRESS_POSTALCODE', + 'default' => false, + ), + 'BILLING_ADDRESS_COUNTRY' => + array ( + 'width' => '10%', + 'label' => 'LBL_BILLING_ADDRESS_COUNTRY', + 'default' => false, + ), + 'SHIPPING_ADDRESS_STREET' => + array ( + 'width' => '15%', + 'label' => 'LBL_SHIPPING_ADDRESS_STREET', + 'default' => false, + ), + 'SHIPPING_ADDRESS_CITY' => + array ( + 'width' => '10%', + 'label' => 'LBL_SHIPPING_ADDRESS_CITY', + 'default' => false, + ), + 'SHIPPING_ADDRESS_STATE' => + array ( + 'width' => '7%', + 'label' => 'LBL_SHIPPING_ADDRESS_STATE', + 'default' => false, + ), + 'SHIPPING_ADDRESS_POSTALCODE' => + array ( + 'width' => '10%', + 'label' => 'LBL_SHIPPING_ADDRESS_POSTALCODE', + 'default' => false, + ), + 'SHIPPING_ADDRESS_COUNTRY' => + array ( + 'width' => '10%', + 'label' => 'LBL_SHIPPING_ADDRESS_COUNTRY', + 'default' => false, + ), + 'RATING' => + array ( + 'width' => '10%', + 'label' => 'LBL_RATING', + 'default' => false, + ), + 'PHONE_ALTERNATE' => + array ( + 'width' => '10%', + 'label' => 'LBL_OTHER_PHONE', + 'default' => false, + ), + 'WEBSITE' => + array ( + 'width' => '10%', + 'label' => 'LBL_WEBSITE', + 'default' => false, + ), + 'OWNERSHIP' => + array ( + 'width' => '10%', + 'label' => 'LBL_OWNERSHIP', + 'default' => false, + ), + 'EMPLOYEES' => + array ( + 'width' => '10%', + 'label' => 'LBL_EMPLOYEES', + 'default' => false, + ), + 'SIC_CODE' => + array ( + 'width' => '10%', + 'label' => 'LBL_SIC_CODE', + 'default' => false, + ), + 'TICKER_SYMBOL' => + array ( + 'width' => '10%', + 'label' => 'LBL_TICKER_SYMBOL', + 'default' => false, + ), + 'DATE_MODIFIED' => + array ( + 'width' => '5%', + 'label' => 'LBL_DATE_MODIFIED', + 'default' => false, + ), + 'DATE_ENTERED' => + array ( + 'width' => '5%', + 'label' => 'LBL_DATE_ENTERED', + 'default' => false, + ), + 'CREATED_BY_NAME' => + array ( + 'width' => '10%', + 'label' => 'LBL_CREATED', + 'default' => false, + ), + 'MODIFIED_BY_NAME' => + array ( + 'width' => '2%', + 'label' => 'LBL_MODIFIED', + 'default' => false, + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Accounts/metadata/searchdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Accounts/metadata/searchdefs.php new file mode 100755 index 00000000..84df7acb --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Accounts/metadata/searchdefs.php @@ -0,0 +1,209 @@ + + array ( + 'basic_search' => + array ( + 'name' => + array ( + 'name' => 'name', + 'label' => 'LBL_NAME', + 'default' => true, + ), + 'billing_address_city' => + array ( + 'name' => 'billing_address_city', + 'label' => 'LBL_BILLING_ADDRESS_CITY', + 'default' => true, + ), + 'phone_office' => + array ( + 'name' => 'phone_office', + 'label' => 'LBL_PHONE_OFFICE', + 'default' => true, + ), + 'address_street' => + array ( + 'name' => 'address_street', + 'label' => 'LBL_BILLING_ADDRESS', + 'type' => 'name', + 'group' => 'billing_address_street', + 'default' => true, + ), + 'website' => + array ( + 'width' => '10%', + 'label' => 'LBL_WEBSITE', + 'default' => true, + 'name' => 'website', + ), + 'current_user_only' => + array ( + 'name' => 'current_user_only', + 'label' => 'LBL_CURRENT_USER_FILTER', + 'type' => 'bool', + 'default' => true, + ), + ), + 'advanced_search' => + array ( + 'name' => + array ( + 'name' => 'name', + 'label' => 'LBL_NAME', + 'default' => true, + 'width' => '10%', + ), + 'address_street' => + array ( + 'name' => 'address_street', + 'label' => 'LBL_ANY_ADDRESS', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'phone' => + array ( + 'name' => 'phone', + 'label' => 'LBL_ANY_PHONE', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'website' => + array ( + 'name' => 'website', + 'label' => 'LBL_WEBSITE', + 'default' => true, + 'width' => '10%', + ), + 'address_city' => + array ( + 'name' => 'address_city', + 'label' => 'LBL_CITY', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'email' => + array ( + 'name' => 'email', + 'label' => 'LBL_ANY_EMAIL', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'annual_revenue' => + array ( + 'name' => 'annual_revenue', + 'label' => 'LBL_ANNUAL_REVENUE', + 'default' => true, + 'width' => '10%', + ), + 'address_state' => + array ( + 'name' => 'address_state', + 'label' => 'LBL_STATE', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'employees' => + array ( + 'name' => 'employees', + 'label' => 'LBL_EMPLOYEES', + 'default' => true, + 'width' => '10%', + ), + 'address_postalcode' => + array ( + 'name' => 'address_postalcode', + 'label' => 'LBL_POSTAL_CODE', + 'type' => 'name', + 'default' => true, + 'width' => '10%', + ), + 'billing_address_country' => + array ( + 'name' => 'billing_address_country', + 'label' => 'LBL_COUNTRY', + 'type' => 'enum', + 'options' => 'countries_dom', + 'default' => true, + 'width' => '10%', + ), + 'ticker_symbol' => + array ( + 'name' => 'ticker_symbol', + 'label' => 'LBL_TICKER_SYMBOL', + 'default' => true, + 'width' => '10%', + ), + 'sic_code' => + array ( + 'name' => 'sic_code', + 'label' => 'LBL_SIC_CODE', + 'default' => true, + 'width' => '10%', + ), + 'rating' => + array ( + 'name' => 'rating', + 'label' => 'LBL_RATING', + 'default' => true, + 'width' => '10%', + ), + 'ownership' => + array ( + 'name' => 'ownership', + 'label' => 'LBL_OWNERSHIP', + 'default' => true, + 'width' => '10%', + ), + 'assigned_user_id' => + array ( + 'name' => 'assigned_user_id', + 'type' => 'enum', + 'label' => 'LBL_ASSIGNED_TO', + 'function' => + array ( + 'name' => 'get_user_array', + 'params' => + array ( + 0 => false, + ), + ), + 'default' => true, + 'sortable' => false, + 'width' => '10%', + ), + 'account_type' => + array ( + 'name' => 'account_type', + 'label' => 'LBL_TYPE', + 'default' => true, + 'sortable' => false, + 'width' => '10%', + ), + 'industry' => + array ( + 'name' => 'industry', + 'label' => 'LBL_INDUSTRY', + 'default' => true, + 'sortable' => false, + 'width' => '10%', + ), + ), + ), + 'templateMeta' => + array ( + 'maxColumns' => '3', + 'widths' => + array ( + 'label' => '10', + 'field' => '30', + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Contacts/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Contacts/metadata/detailviewdefs.php new file mode 100755 index 00000000..af765641 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Contacts/metadata/detailviewdefs.php @@ -0,0 +1,331 @@ + + array ( + 'DetailView' => + array ( + 'templateMeta' => + array ( + 'preForm' => '
', + 'form' => + array ( + 'buttons' => + array ( + 0 => 'EDIT', + 1 => 'DUPLICATE', + 2 => 'DELETE', + 3 => 'FIND_DUPLICATES', + 4 => + array ( + 'customCode' => '', + ), + ), + ), + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + 'includes' => + array ( + 0 => + array ( + 'file' => 'modules/Leads/Lead.js', + ), + ), + ), + 'panels' => + array ( + 'default' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'full_name', + 'customCode' => '{$fields.full_name.value}  ', + 'label' => 'LBL_NAME', + 'displayParams' => + array ( + ), + ), + 1 => + array ( + 'name' => 'phone_work', + 'label' => 'LBL_OFFICE_PHONE', + ), + ), + 1 => + array ( + 0 => 'score_c', + 1 => + array ( + 'name' => 'phone_mobile', + 'label' => 'LBL_MOBILE_PHONE', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'account_name', + 'label' => 'LBL_ACCOUNT_NAME', + ), + 1 => + array ( + 'name' => 'phone_home', + 'label' => 'LBL_HOME_PHONE', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'lead_source', + 'label' => 'LBL_LEAD_SOURCE', + ), + 1 => + array ( + 'name' => 'phone_other', + 'label' => 'LBL_OTHER_PHONE', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'title', + 'label' => 'LBL_TITLE', + ), + 1 => + array ( + 'name' => 'phone_fax', + 'label' => 'LBL_FAX_PHONE', + ), + ), + 5 => + array ( + 0 => + array ( + 'name' => 'department', + 'label' => 'LBL_DEPARTMENT', + ), + 1 => + array ( + 'name' => 'email1', + 'label' => 'LBL_EMAIL_ADDRESS', + ), + ), + 6 => + array ( + 0 => + array ( + 'name' => 'birthdate', + 'label' => 'LBL_BIRTHDATE', + ), + 1 => NULL, + ), + 7 => + array ( + 0 => + array ( + 'name' => 'report_to_name', + 'label' => 'LBL_REPORTS_TO', + ), + 1 => + array ( + 'name' => 'assistant', + 'label' => 'LBL_ASSISTANT', + ), + ), + 8 => + array ( + 0 => + array ( + 'name' => 'technical_proficiency_', + 'label' => 'LBL_TECHNICAL_PROFICIENCY_', + ), + 1 => + array ( + 'name' => 'assistant_phone', + 'label' => 'LBL_ASSISTANT_PHONE', + ), + ), + 9 => + array ( + 0 => + array ( + 'name' => 'do_not_call', + 'label' => 'LBL_DO_NOT_CALL', + ), + 1 => NULL, + ), + 10 => + array ( + 0 => + array ( + 'name' => 'sync_contact', + 'label' => 'LBL_SYNC_CONTACT', + ), + 1 => NULL, + ), + 11 => + array ( + 0 => NULL, + 1 => + array ( + 'name' => 'primary_business_c', + 'label' => 'Primary_Business_Contact__c', + ), + ), + 12 => + array ( + 0 => NULL, + 1 => + array ( + 'name' => 'support_authorized_c', + 'label' => 'Support_Authorized_Contact__c', + ), + ), + 13 => + array ( + 0 => NULL, + 1 => + array ( + 'name' => 'university_enabled_c', + 'label' => 'LBL_UNIVERSITY_ENABLED', + ), + ), + 14 => + array ( + 0 => NULL, + 1 => + array ( + 'name' => 'billing_contact_c', + 'label' => 'Billing_Contact__c', + ), + ), + 15 => + array ( + 0 => NULL, + 1 => + array ( + 'name' => 'oppq_active_c', + 'label' => 'LBL_OPPQ_ACTIVE_C', + ), + ), + 16 => + array ( + 0 => + array ( + 'name' => 'team_name', + 'label' => 'LBL_TEAM', + ), + 1 => + array ( + 'name' => 'date_modified', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', + 'label' => 'LBL_DATE_MODIFIED', + ), + ), + 17 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO_NAME', + ), + 1 => + array ( + 'name' => 'date_entered', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}', + 'label' => 'LBL_DATE_ENTERED', + ), + ), + 18 => + array ( + 0 => + array ( + 'name' => 'primary_address_street', + 'label' => 'LBL_PRIMARY_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'primary', + ), + ), + 1 => + array ( + 'name' => 'alt_address_street', + 'label' => 'LBL_ALTERNATE_ADDRESS', + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'alt', + ), + ), + ), + 19 => + array ( + 0 => + array ( + 'name' => 'portal_name', + 'customCode' => '{if $PORTAL_ENABLED}{$fields.portal_name.value}{/if}', + 'customLabel' => '{if $PORTAL_ENABLED}{sugar_translate label="LBL_PORTAL_NAME" module="Contacts"}{/if}', + 'label' => 'LBL_PORTAL_NAME', + ), + 1 => + array ( + 'name' => 'portal_active', + 'customCode' => '{if $PORTAL_ENABLED} + {if strval($fields.portal_active.value) == "1" || strval($fields.portal_active.value) == "yes" || strval($fields.portal_active.value) == "on"} + {assign var="checked" value="CHECKED"} + {else} + {assign var="checked" value=""} + {/if} + + {/if}', + 'customLabel' => '{if $PORTAL_ENABLED}{sugar_translate label="LBL_PORTAL_ACTIVE" module="Contacts"}{/if}', + 'label' => 'LBL_PORTAL_ACTIVE', + ), + ), + 20 => + array ( + 0 => + array ( + 'name' => 'description', + 'label' => 'LBL_DESCRIPTION', + ), + ), + ), + 'lbl_panel1' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'dce_user_name_c', + 'label' => 'LBL_DCE_USER_NAME', + ), + 1 => + array ( + 'name' => 'licensing_rights_c', + 'label' => 'LBL_LICENSING_RIGHTS', + ), + ), + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Contacts/metadata/editviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Contacts/metadata/editviewdefs.php new file mode 100755 index 00000000..32c14794 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Contacts/metadata/editviewdefs.php @@ -0,0 +1,370 @@ + + array ( + 'templateMeta' => + array ( + 'form' => + array ( + 'hidden' => + array ( + 0 => '', + 1 => '', + 2 => '', + 3 => '', + 4 => '', + ), + ), + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + ), + 'panels' => + array ( + 'lbl_contact_information' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'first_name', + 'customCode' => '{html_options name="salutation" options=$fields.salutation.options selected=$fields.salutation.value} ', + 'label' => 'LBL_FIRST_NAME', + ), + 1 => + array ( + 'name' => 'phone_work', + 'label' => 'LBL_OFFICE_PHONE', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'last_name', + 'displayParams' => + array ( + 'required' => true, + ), + 'label' => 'LBL_LAST_NAME', + ), + 1 => + array ( + 'name' => 'phone_mobile', + 'label' => 'LBL_MOBILE_PHONE', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'account_name', + 'displayParams' => + array ( + 'key' => 'billing', + 'copy' => 'primary', + 'billingKey' => 'primary', + 'additionalFields' => + array ( + 'phone_office' => 'phone_work', + ), + ), + 'label' => 'LBL_ACCOUNT_NAME', + ), + 1 => + array ( + 'name' => 'phone_home', + 'label' => 'LBL_HOME_PHONE', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'lead_source', + 'label' => 'LBL_LEAD_SOURCE', + ), + 1 => + array ( + 'name' => 'phone_other', + 'label' => 'LBL_OTHER_PHONE', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'title', + 'label' => 'LBL_TITLE', + ), + 1 => + array ( + 'name' => 'phone_fax', + 'label' => 'LBL_FAX_PHONE', + ), + ), + 5 => + array ( + 0 => + array ( + 'name' => 'department', + 'label' => 'LBL_DEPARTMENT', + ), + 1 => NULL, + ), + 6 => + array ( + 0 => + array ( + 'name' => 'birthdate', + 'label' => 'LBL_BIRTHDATE', + ), + 1 => NULL, + ), + 7 => + array ( + 0 => + array ( + 'name' => 'report_to_name', + 'label' => 'LBL_REPORTS_TO', + ), + 1 => + array ( + 'name' => 'assistant', + 'label' => 'LBL_ASSISTANT', + ), + ), + 8 => + array ( + 0 => + array ( + 'name' => 'technical_proficiency_', + 'label' => 'LBL_TECHNICAL_PROFICIENCY_', + ), + 1 => + array ( + 'name' => 'assistant_phone', + 'label' => 'LBL_ASSISTANT_PHONE', + ), + ), + 9 => + array ( + 0 => + array ( + 'name' => 'do_not_call', + 'label' => 'LBL_DO_NOT_CALL', + ), + 1 => NULL, + ), + 10 => + array ( + 0 => + array ( + 'name' => 'team_name', + 'displayParams' => + array ( + 'display' => true, + ), + 'label' => 'LBL_TEAM', + ), + 1 => + array ( + 'name' => 'sync_contact', + 'label' => 'LBL_SYNC_CONTACT', + ), + ), + 11 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO_NAME', + ), + 1 => NULL, + ), + 12 => + array ( + 0 => NULL, + 1 => + array ( + 'name' => 'primary_business_c', + 'label' => 'Primary_Business_Contact__c', + ), + ), + 13 => + array ( + 0 => NULL, + 1 => + array ( + 'name' => 'support_authorized_c', + 'label' => 'Support_Authorized_Contact__c', + ), + ), + 14 => + array ( + 0 => NULL, + 1 => + array ( + 'name' => 'university_enabled_c', + 'label' => 'LBL_UNIVERSITY_ENABLED', + ), + ), + 15 => + array ( + 0 => NULL, + 1 => + array ( + 'name' => 'billing_contact_c', + 'label' => 'Billing_Contact__c', + ), + ), + 16 => + array ( + 0 => NULL, + 1 => + array ( + 'name' => 'oppq_active_c', + 'label' => 'LBL_OPPQ_ACTIVE_C', + ), + ), + ), + 'lbl_email_addresses' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'email1', + 'label' => 'LBL_EMAIL_ADDRESS', + ), + ), + ), + 'lbl_address_information' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'primary_address_street', + 'hideLabel' => true, + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'primary', + 'rows' => 2, + 'cols' => 30, + 'maxlength' => 150, + ), + 'label' => 'LBL_PRIMARY_ADDRESS_STREET', + ), + 1 => + array ( + 'name' => 'alt_address_street', + 'hideLabel' => true, + 'type' => 'address', + 'displayParams' => + array ( + 'key' => 'alt', + 'copy' => 'primary', + 'rows' => 2, + 'cols' => 30, + 'maxlength' => 150, + ), + 'label' => 'LBL_ALT_ADDRESS_STREET', + ), + ), + ), + 'lbl_description_information' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'description', + 'displayParams' => + array ( + 'rows' => 6, + 'cols' => 80, + ), + 'label' => 'LBL_DESCRIPTION', + ), + ), + ), + 'lbl_portal_information' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'portal_name', + + 'customCode' => '
+ + + + + + + +
', + + 'label' => 'LBL_PORTAL_NAME', + ), + 1 => + array ( + 'name' => 'portal_active', + 'label' => 'LBL_PORTAL_ACTIVE', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'portal_password1', + 'type' => 'password', + 'customCode' => '', + 'label' => 'LBL_PORTAL_PASSWORD', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'portal_password', + 'customCode' => '', + 'label' => 'LBL_CONFIRM_PORTAL_PASSWORD', + ), + ), + ), + 'lbl_panel1' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'dce_user_name_c', + 'label' => 'LBL_DCE_USER_NAME', + ), + 1 => + array ( + 'name' => 'licensing_rights_c', + 'label' => 'LBL_LICENSING_RIGHTS', + ), + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Opportunities/metadata/detailviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Opportunities/metadata/detailviewdefs.php new file mode 100755 index 00000000..1b8e1269 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Opportunities/metadata/detailviewdefs.php @@ -0,0 +1,391 @@ + + array ( + 'DetailView' => + array ( + 'templateMeta' => + array ( + 'form' => + array ( + 'buttons' => + array ( + 0 => 'EDIT', + 1 => 'DUPLICATE', + 2 => 'DELETE', + 3 => + array ( + 'customCode' => '', + ), + 4 => + array ( + 'customCode' => '', + ), + ), + ), + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + ), + 'panels' => + array ( + 'default' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'name', + 'label' => 'LBL_OPPORTUNITY_NAME', + ), + 1 => + array ( + 'name' => 'amount', + 'label' => '{$MOD.LBL_AMOUNT} ({$CURRENCY})', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'account_name', + 'label' => 'LBL_ACCOUNT_NAME', + ), + 1 => + array ( + 'name' => 'date_closed', + 'label' => 'LBL_DATE_CLOSED', + ), + ), + '1.5' => + array ( + 0 => + array ( + 'name' => NULL, + 'displayParams' => + array ( + ), + ), + 1 => + array ( + 'name' => 'discount_code_c', + 'label' => 'LBL_DISCOUNT_CODE', + ), + ), + 2 => + array ( + 0 => + array ( + 'name' => 'opportunity_type', + 'label' => 'LBL_TYPE', + ), + 1 => + array ( + 'name' => 'users', + 'label' => 'LBL_USERS_1', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'email_client', + 'label' => 'LBL_EMAIL_CLIENT', + ), + 1 => + array ( + 'name' => 'additional_support_cases_c', + 'label' => 'Additional_Support_Cases__c', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'processed_by_moofcart_c', + 'label' => 'LBL_PROCESSED_BY_MOOFCART', + ), + 1 => + array ( + 'name' => 'additional_training_credits_c', + 'label' => 'Learning_Credits__c', + ), + ), + 5 => + array ( + 0 => + array ( + 'name' => 'trial_name_c', + 'label' => 'Trial URL', + ), + 1 => + array ( + 'name' => 'sales_stage', + 'label' => 'LBL_SALES_STAGE', + ), + ), + 6 => + array ( + 0 => + array ( + 'name' => 'trial_expiration_c', + 'label' => 'Trial Expiration', + 'customCode' => '{php} $myTimeDate = new TimeDate(); $this->assign("jmo_trialExpirationDB", $myTimeDate->to_db($this->_tpl_vars["fields"]["trial_expiration_c"]["value"])); unset($myTimeDate); {/php} {$fields.trial_expiration_c.value}{if $fields.trial_extended_c.value eq 0 && !empty($fields.trial_name_c.value) && strtotime("now") < $jmo_trialExpirationDB|date_format:"%s"}   {/if}', + ), + 1 => + array ( + 'name' => 'probability', + 'label' => 'LBL_PROBABILITY', + ), + ), + 7 => + array ( + 0 => + array ( + 'name' => 'campaign_name', + 'label' => 'LBL_CAMPAIGN', + ), + 1 => 'score_c', + ), + 8 => + array ( + 0 => + array ( + 'name' => 'lead_source', + 'label' => 'LBL_LEAD_SOURCE', + ), + 1 => NULL, + ), + 9 => + array ( + 0 => + array ( + 'name' => 'current_solution', + 'label' => 'LBL_CURRENT_SOLUTION', + ), + 1 => + array ( + 'name' => 'Term_c', + 'label' => 'Term__c', + ), + ), + 10 => + array ( + 0 => + array ( + 'name' => 'competitor_1', + 'label' => 'LBL_COMPETITOR_1', + ), + 1 => + array ( + 'name' => 'Revenue_Type_c', + 'label' => 'Revenue_Type__c', + ), + ), + 11 => + array ( + 0 => + array ( + 'name' => 'competitor_2', + 'label' => 'LBL_COMPETITOR_2', + ), + 1 => + array ( + 'name' => 'renewal_date_c', + 'label' => 'Renewal_Date_c', + ), + ), + 12 => + array ( + 0 => + array ( + 'name' => 'competitor_3', + 'label' => 'LBL_COMPETITOR_3', + ), + 1 => + array ( + 'name' => 'order_number', + 'label' => 'LBL_ORDER_NUMBER', + 'customCode' => '{$fields.order_number.value}', + ), + ), + 13 => + array ( + 0 => + array ( + 'name' => 'competitor_expiration_c', + 'label' => 'LBL_COMPETITOR_EXPIRATION', + ), + 1 => + array ( + 'name' => 'order_type_c', + 'label' => 'LBL_ORDER_TYPE_C', + ), + ), + 14 => + array ( + 0 => NULL, + 1 => + array ( + 'name' => 'next_step', + 'label' => 'LBL_NEXT_STEP', + ), + ), + 15 => + array ( + 0 => + array ( + 'name' => 'demo_c', + 'label' => 'Demo_1', + ), + 1 => + array ( + 'name' => 'next_step_due_date', + 'label' => 'LBL_NEXT_STEP_DUE_DATE', + ), + ), + 16 => + array ( + 0 => + array ( + 'name' => 'demo_date_c', + 'label' => 'Demo Date', + ), + 1 => + array ( + 'name' => 'top20deal_c', + 'label' => 'LBL_TOP20DEAL', + ), + ), + 17 => + array ( + 0 => + array ( + 'name' => 'evaluation', + 'label' => 'LBL_EVALUATION', + ), + 1 => + array ( + 'name' => 'closed_lost_reason_c', + 'label' => 'LBL_CLOSED_LOST_REASON_C', + ), + ), + 18 => + array ( + 0 => + array ( + 'name' => 'evaluation_start_date', + 'label' => 'LBL_EVALUATION_START_DATE', + ), + 1 => + array ( + 'name' => 'closed_lost_reason_detail_c', + 'label' => 'LBL_CLOSED_LOST_REASON_DETAIL', + ), + ), + 19 => + array ( + 0 => + array ( + 'name' => 'Evaluation_Close_Date_c', + 'label' => 'Evaluation_Close_Date__c', + ), + 1 => + array ( + 'name' => 'primary_reason_competitor_c', + 'label' => 'LBL_PRIMARY_REASON_COMPETITOR', + ), + ), + 20 => + array ( + 0 => + array ( + ), + 1 => + array ( + 'name' => 'closed_lost_description', + 'label' => 'LBL_CLOSED_LOST_DESCRIPTION', + ), + ), + 21 => + array ( + 0 => + array ( + 'name' => 'partner_assigned_to_c', + 'label' => 'Partner_Assigned_To_c', + 'customCode' => '{assign var=partner_assigned_to_key value=$fields.partner_assigned_to_c.value}{$APP_LIST_STRINGS.partner_assigned_to.$partner_assigned_to_key}', + ), + 1 => + array ( + 'name' => 'accepted_by_partner_c', + 'label' => 'LBL_ACCEPTED_BY_PARTNER', + ), + ), + 22 => + array ( + 0 => + array ( + 'name' => 'team_name', + 'label' => 'LBL_TEAM', + ), + 1 => + array ( + 'name' => 'partner_contact_c', + 'label' => 'LBL_PARTNER_CONTACT', + ), + ), + 23 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO_NAME', + ), + 1 => + array ( + 'name' => 'date_modified', + 'label' => 'LBL_DATE_MODIFIED', + 'customCode' => '{$fields.date_modified.value} {$APP.LBL_BY} {$fields.modified_by_name.value}', + ), + ), + 24 => + array ( + 0 => + array ( + 'name' => 'associated_rep_c', + 'label' => 'Associated_Rep_c', + ), + 1 => + array ( + 'name' => 'date_entered', + 'customCode' => '{$fields.date_entered.value} {$APP.LBL_BY} {$fields.created_by_name.value}', + 'label' => 'LBL_DATE_ENTERED', + ), + ), + 25 => + array ( + 0 => + array ( + 'name' => 'description', + 'nl2br' => true, + 'label' => 'LBL_DESCRIPTION', + ), + ), + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Opportunities/metadata/editviewdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Opportunities/metadata/editviewdefs.php new file mode 100755 index 00000000..167961d8 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Opportunities/metadata/editviewdefs.php @@ -0,0 +1,402 @@ + + array ( + 'templateMeta' => + array ( + 'maxColumns' => '2', + 'widths' => + array ( + 0 => + array ( + 'label' => '10', + 'field' => '30', + ), + 1 => + array ( + 'label' => '10', + 'field' => '30', + ), + ), + 'javascript' => '{$PROBABILITY_SCRIPT}', + ), + 'panels' => + array ( + 'default' => + array ( + 0 => + array ( + 0 => + array ( + 'name' => 'name', + 'displayParams' => + array ( + 'required' => true, + ), + 'label' => 'LBL_OPPORTUNITY_NAME', + ), + 1 => + array ( + 'name' => 'currency_id', + 'label' => 'LBL_CURRENCY', + ), + ), + 1 => + array ( + 0 => + array ( + 'name' => 'account_name', + 'label' => 'LBL_ACCOUNT_NAME', + ), + 1 => + array ( + 'name' => 'amount', + 'displayParams' => + array ( + 'required' => true, + ), + 'label' => 'LBL_AMOUNT', + ), + ), + // BEGIN jostrow MoofCart customization + // See ITRequest #9622 + + '1.5' => array( + NULL, + array( + 'name' => 'discount_code_c', + 'label' => 'LBL_DISCOUNT_CODE', + ), + ), + + // END jostrow MoofCart customization + + 2 => + array ( + 0 => + array ( + 'name' => 'opportunity_type', + 'label' => 'LBL_TYPE', + ), + 1 => + array ( + 'name' => 'date_closed', + 'displayParams' => + array ( + 'required' => true, + ), + 'label' => 'LBL_DATE_CLOSED', + ), + ), + 3 => + array ( + 0 => + array ( + 'name' => 'operating_system', + 'label' => 'LBL_OPERATING_SYSTEM', + ), + 1 => + array ( + 'name' => 'users', + 'label' => 'LBL_USERS_1', + ), + ), + 4 => + array ( + 0 => + array ( + 'name' => 'campaign_name', + 'label' => 'LBL_CAMPAIGN', + ), + 1 => + array ( + 'name' => 'additional_support_cases_c', + 'label' => 'Additional_Support_Cases__c', + ), + ), + 5 => + array ( + 1 => + array ( + 'name' => 'additional_training_credits_c', + 'label' => 'Learning_Credits__c', + ), + ), + 6 => + array ( + 0 => + array ( + 'name' => 'email_client', + 'label' => 'LBL_EMAIL_CLIENT', + ), + 1 => + array ( + 'name' => 'sales_stage', + 'displayParams' => + array ( + 'required' => true, + ), + 'label' => 'LBL_SALES_STAGE', + 'customCode' => ' + + {html_options id="sales_stage" name="sales_stage" options=$fields.sales_stage.options selected=$fields.sales_stage.value onChange=\'checkOpportunitySalesStage()\'} + ', + ), + ), + 7 => + array ( + 1 => + array ( + 'name' => 'probability', + 'label' => 'LBL_PROBABILITY', + ), + ), + 8 => + array ( + ), + 9 => + array ( + 1 => + array ( + 'name' => 'Term_c', + 'label' => 'Term__c', + ), + ), + 10 => + array ( + 0 => + array ( + 'name' => 'lead_source', + 'label' => 'LBL_LEAD_SOURCE', + ), + 1 => + array ( + 'name' => 'Revenue_Type_c', + 'label' => 'Revenue_Type__c', + ), + ), + 11 => + array ( + 0 => + array ( + 'name' => 'partner_name', + 'label' => 'LBL_PARTNER_NAME', + ), + 1 => + array ( + 'name' => 'renewal_date_c', + 'label' => 'Renewal_Date_c', + ), + ), + 12 => + array ( + 0 => + array ( + 'name' => 'current_solution', + 'label' => 'LBL_CURRENT_SOLUTION', + ), + 1 => + array ( + 'name' => 'order_number', + 'label' => 'LBL_ORDER_NUMBER', + ), + ), + 13 => + array ( + 1 => + array ( + 'name' => 'order_type_c', + 'label' => 'LBL_ORDER_TYPE_C', + ), + ), + 14 => + array ( + 0 => + array ( + 'name' => 'competitor_1', + 'label' => 'LBL_COMPETITOR_1', + ), + 1 => + array ( + 'name' => 'true_up_c', + 'label' => 'LBL_TRUE_UP', + ), + ), + 15 => + array ( + 0 => + array ( + 'name' => 'competitor_2', + 'label' => 'LBL_COMPETITOR_2', + ), + 1 => + array ( + 'name' => 'next_step', + 'label' => 'LBL_NEXT_STEP', + 'customCode' => '', + ), + ), + 16 => + array ( + 0 => + array ( + 'name' => 'competitor_3', + 'label' => 'LBL_COMPETITOR_3', + ), + 1 => + array ( + 'name' => 'next_step_due_date', + 'label' => 'LBL_NEXT_STEP_DUE_DATE', + ), + ), + 17 => + array ( + 0 => + array ( + 'name' => 'competitor_expiration_c', + 'label' => 'LBL_COMPETITOR_EXPIRATION', + ), + ), + 18 => + array ( + 0 => + array ( + 'name' => 'demo_c', + 'label' => 'Demo_1', + ), + 1 => + array ( + 'name' => 'top20deal_c', + 'label' => 'LBL_TOP20DEAL', + ), + ), + 19 => + array ( + 0 => + array ( + 'name' => 'demo_date_c', + 'label' => 'Demo Date', + ), + ), + 20 => + array ( + 0 => + array ( + 'name' => 'evaluation', + 'label' => 'LBL_EVALUATION', + ), + 1 => + array ( + 'name' => 'closed_lost_reason_c', + 'label' => 'LBL_CLOSED_LOST_REASON_C', +//** BEGIN CUSTOMIZATION EDDY :: ITTix 13077 + 'customCode' => ' + + {html_options id="closed_lost_reason_c" name="closed_lost_reason_c" options=$fields.closed_lost_reason_c.options selected=$fields.closed_lost_reason_c.value onChange=\'checkOppClosedReasonDependentDropdown("closed_lost_reason_detail_c", true)\' } +', +//** END CUSTOMIZATION EDDY :: ITTix 13077 + ), + ), + 21 => + array ( + 0 => + array ( + 'name' => 'evaluation_start_date', + 'label' => 'LBL_EVALUATION_START_DATE', + ), + 1 => + array ( + 'name' => 'closed_lost_reason_detail_c', + 'label' => 'LBL_CLOSED_LOST_REASON_DETAIL', + + ), + ), + 22 => + array ( + 0 => + array ( + 'name' => 'Evaluation_Close_Date_c', + 'label' => 'Evaluation_Close_Date__c', + ), + 1 => + array ( + 'name' => 'primary_reason_competitor_c', + 'label' => 'LBL_PRIMARY_REASON_COMPETITOR', + ), + ), + 23 => + array ( + 0 => array(), + 1 => + array ( + 'name' => 'closed_lost_description', + 'label' => 'LBL_CLOSED_LOST_DESCRIPTION', +//** BEGIN CUSTOMIZATION EDDY :: ITTix 13077 + 'customCode' => ' + + + ', +//** END CUSTOMIZATION EDDY :: ITTix 13077 + + ), + ), + 24 => + array ( + 0 => + array( + 'name' => 'partner_assigned_to_c', + 'label' => 'Partner_Assigned_To_c', + ), + 1 => + array ( + 'name' => 'accepted_by_partner_c', + 'label' => 'LBL_ACCEPTED_BY_PARTNER', + ), + ), + 25 => + array ( + 0 => + array ( + 'name' => 'team_name', + 'displayParams' => + array ( + 'required' => true, + ), + 'label' => 'LBL_TEAM', + ), + 1 => + array ( + 'name' => 'partner_contact_c', + 'label' => 'LBL_PARTNER_CONTACT', + ), + ), + 26 => + array ( + 0 => + array ( + 'name' => 'assigned_user_name', + 'label' => 'LBL_ASSIGNED_TO_NAME', + ), + 1 => + array ( + 'name' => 'associated_rep_c', + 'label' => 'Associated_Rep_c', + ), + ), + 27 => + array ( + 0 => + array ( + 'name' => 'description', + 'label' => 'LBL_DESCRIPTION', + ), + ), + ), + ), + ), +); +?> diff --git a/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Opportunities/metadata/searchdefs.php b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Opportunities/metadata/searchdefs.php new file mode 100755 index 00000000..71c323f2 --- /dev/null +++ b/tests/modules/UpgradeWizard/SugarMerge/siupgrade_metadata_files/custom/modules/Opportunities/metadata/searchdefs.php @@ -0,0 +1,130 @@ + + array ( + 'basic_search' => + array ( + 0 => 'name', + 1 => 'opportunity_type', + 2 => 'account_name', + 3 => + array ( + 'name' => 'current_user_only', + 'label' => 'LBL_CURRENT_USER_FILTER', + 'type' => 'bool', + ), + ), + 'advanced_search' => + array ( + 'name' => + array ( + 'name' => 'name', + 'label' => 'LBL_OPPORTUNITY_NAME', + 'default' => true, + 'width' => '10%', + ), + 'amount' => + array ( + 'name' => 'amount', + 'label' => 'LBL_AMOUNT', + 'default' => true, + 'currency_format' => true, + 'width' => '10%', + ), + 'account_name' => + array ( + 'name' => 'account_name', + 'label' => 'LBL_ACCOUNT_NAME', + 'default' => true, + 'width' => '10%', + ), + 'date_closed' => + array ( + 'name' => 'date_closed', + 'label' => 'LBL_DATE_CLOSED', + 'default' => true, + 'width' => '10%', + ), + 'opportunity_type' => + array ( + 'width' => '10%', + 'label' => 'LBL_TYPE', + 'sortable' => false, + 'default' => true, + 'name' => 'opportunity_type', + ), + 'lead_source' => + array ( + 'name' => 'lead_source', + 'label' => 'LBL_LEAD_SOURCE', + 'default' => true, + 'sortable' => false, + 'width' => '10%', + ), + 'next_step' => + array ( + 'name' => 'next_step', + 'label' => 'LBL_NEXT_STEP', + 'default' => true, + 'width' => '10%', + ), + 'sales_stage' => + array ( + 'name' => 'sales_stage', + 'label' => 'LBL_SALES_STAGE', + 'default' => true, + 'sortable' => false, + 'width' => '10%', + ), + 'probability' => + array ( + 'name' => 'probability', + 'label' => 'LBL_PROBABILITY', + 'default' => true, + 'width' => '10%', + ), + 'assigned_user_id' => + array ( + 'name' => 'assigned_user_id', + 'type' => 'enum', + 'label' => 'LBL_ASSIGNED_TO', + 'function' => + array ( + 'name' => 'get_user_array', + 'params' => + array ( + 0 => false, + ), + ), + 'default' => true, + 'sortable' => false, + 'width' => '10%', + ), + 'partner_assigned_to_c' => + array ( + 'width' => '10%', + 'label' => 'Partner_Assigned_To_c', + 'default' => true, + 'name' => 'partner_assigned_to_c', + ), + 'order_number' => + array ( + 'width' => '10%', + 'label' => 'LBL_ORDER_NUMBER', + 'default' => true, + 'name' => 'order_number', + ), + ), + ), + 'templateMeta' => + array ( + 'maxColumns' => '3', + 'widths' => + array ( + 'label' => '10', + 'field' => '30', + ), + ), +); +?> diff --git a/tests/modules/Users/UserTest.php b/tests/modules/Users/UserTest.php new file mode 100755 index 00000000..2a9ca57d --- /dev/null +++ b/tests/modules/Users/UserTest.php @@ -0,0 +1,107 @@ +_user = SugarTestUserUtilities::createAnonymousUser(); + $GLOBALS['current_user'] = SugarTestUserUtilities::createAnonymousUser(); + } + + public function tearDown() + { + unset($GLOBALS['current_user']); + } + + public function testSettingAUserPreference() + { + $this->_user->setPreference('test_pref','dog'); + + $this->assertEquals('dog',$this->_user->getPreference('test_pref')); + } + + public function testGettingSystemPreferenceWhenNoUserPreferenceExists() + { + $GLOBALS['sugar_config']['somewhackypreference'] = 'somewhackyvalue'; + + $result = $this->_user->getPreference('somewhackypreference'); + + unset($GLOBALS['sugar_config']['somewhackypreference']); + + $this->assertEquals('somewhackyvalue',$result); + } + + /** + * @ticket 42667 + */ + public function testGettingSystemPreferenceWhenNoUserPreferenceExistsForEmailDefaultClient() + { + if ( isset($GLOBALS['sugar_config']['email_default_client']) ) { + $oldvalue = $GLOBALS['sugar_config']['email_default_client']; + } + $GLOBALS['sugar_config']['email_default_client'] = 'somewhackyvalue'; + + $result = $this->_user->getPreference('email_link_type'); + + if ( isset($oldvalue) ) { + $GLOBALS['sugar_config']['email_default_client'] = $oldvalue; + } + else { + unset($GLOBALS['sugar_config']['email_default_client']); + } + + $this->assertEquals('somewhackyvalue',$result); + } + + public function testResetingUserPreferences() + { + $this->_user->setPreference('test_pref','dog'); + + $this->_user->resetPreferences(); + + $this->assertNull($this->_user->getPreference('test_pref')); + } + + /** + * @group bug36657 + */ + public function testCertainPrefsAreNotResetWhenResetingUserPreferences() + { + $this->_user->setPreference('ut','1'); + $this->_user->setPreference('timezone','GMT'); + + $this->_user->resetPreferences(); + + $this->assertEquals('1',$this->_user->getPreference('ut')); + $this->assertEquals('GMT',$this->_user->getPreference('timezone')); + } + + public function testDeprecatedUserPreferenceInterface() + { + User::setPreference('deprecated_pref','dog',0,'global',$this->_user); + + $this->assertEquals('dog',User::getPreference('deprecated_pref','global',$this->_user)); + } + + public function testSavingToMultipleUserPreferenceCategories() + { + $this->_user->setPreference('test_pref1','dog',0,'cat1'); + $this->_user->setPreference('test_pref2','dog',0,'cat2'); + + $this->_user->savePreferencesToDB(); + + $this->assertEquals( + 'cat1', + $GLOBALS['db']->getOne("SELECT category FROM user_preferences WHERE assigned_user_id = '{$this->_user->id}' AND category = 'cat1'") + ); + + $this->assertEquals( + 'cat2', + $GLOBALS['db']->getOne("SELECT category FROM user_preferences WHERE assigned_user_id = '{$this->_user->id}' AND category = 'cat2'") + ); + } +} + diff --git a/tests/phpuc.xml b/tests/phpuc.xml new file mode 100755 index 00000000..1c86243f --- /dev/null +++ b/tests/phpuc.xml @@ -0,0 +1,27 @@ + + + ./tests/data + ./tests/include + ./tests/modules + ./tests/ModuleInstall + ./tests/service + ./tests/tests + + + + ./cache + ./custom + ./examples + ./jscalendar + ./jssource + ./log4php + ./metadata + ./tests + ./themes + ./XTemplate + ./config.php + + + diff --git a/tests/phpunit.bat b/tests/phpunit.bat new file mode 100755 index 00000000..8683f78b --- /dev/null +++ b/tests/phpunit.bat @@ -0,0 +1,40 @@ +@echo off +REM PHPUnit +REM +REM Copyright (c) 2002-2009, Sebastian Bergmann . +REM All rights reserved. +REM +REM Redistribution and use in source and binary forms, with or without +REM modification, are permitted provided that the following conditions +REM are met: +REM +REM * Redistributions of source code must retain the above copyright +REM notice, this list of conditions and the following disclaimer. +REM +REM * Redistributions in binary form must reproduce the above copyright +REM notice, this list of conditions and the following disclaimer in +REM the documentation and/or other materials provided with the +REM distribution. +REM +REM * Neither the name of Sebastian Bergmann nor the names of his +REM contributors may be used to endorse or promote products derived +REM from this software without specific prior written permission. +REM +REM THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +REM "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +REM LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +REM FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +REM COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +REM INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +REM BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +REM LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +REM CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC +REM LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +REM ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +REM POSSIBILITY OF SUCH DAMAGE. +REM + +REM + +set PHPBIN="php.exe" +"php.exe" "phpunit.php" %* diff --git a/tests/phpunit.php b/tests/phpunit.php new file mode 100755 index 00000000..e3edd301 --- /dev/null +++ b/tests/phpunit.php @@ -0,0 +1,56 @@ +#!/usr/bin/env php +. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of Sebastian Bergmann nor the names of his + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRIC + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + + */ +// no memory limit needed, since we are running this from the command line +ini_set('memory_limit', '-1'); + +set_include_path(dirname(__FILE__) . PATH_SEPARATOR . get_include_path()); + +if ( isset($_SERVER['_']) ) + $_SERVER['_'] = realpath($_SERVER['_']); + +require_once 'PHPUnit/Util/Filter.php'; + +PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT'); + +require 'PHPUnit/TextUI/Command.php'; + +define('PHPUnit_MAIN_METHOD', 'PHPUnit_TextUI_Command::main'); + +PHPUnit_TextUI_Command::main(); +?> diff --git a/tests/phpunit.xml b/tests/phpunit.xml new file mode 100755 index 00000000..857d6415 --- /dev/null +++ b/tests/phpunit.xml @@ -0,0 +1,11 @@ + + + ./tests/include + ./tests/modules + ./tests/ModuleInstall + ./tests/service + ./tests/tests + + diff --git a/tests/service/APIv3Helper.php b/tests/service/APIv3Helper.php new file mode 100755 index 00000000..d5f15198 --- /dev/null +++ b/tests/service/APIv3Helper.php @@ -0,0 +1,131 @@ +id = $a1_id; + $a1->new_with_id = TRUE; + $a1->name = "UNIT TEST $a1_id"; + $a1->assigned_user_id = $user_id; + $a1->save(); + $results[] = array('id' => $a1_id, 'fieldName' => 'name', 'fieldValue' => "UNIT TEST $a1_id"); + + $a2_id = uniqid(); + $a2 = new Account(); + $a2->new_with_id = TRUE; + $a2->id = $a2_id; + $a2->name = "UNIT TEST $a2_id"; + $a2->assigned_user_id = 'unittest'; + $a2->save(); + $results[] = array('id' => $a2_id, 'fieldName' => 'name', 'fieldValue' => "UNIT TEST $a2_id"); + + $c1_id = uniqid(); + $c1 = new Contact(); + $c1->id = $c1_id; + $c1->new_with_id = TRUE; + $c1->first_name = "UNIT TEST"; + $c1->last_name = "UNIT_TEST"; + $c1->assigned_user_id = $user_id; + $c1->save(); + $results[] = array('id' => $c1_id, 'fieldName' => 'name', 'fieldValue' => $c1->first_name .' ' . $c1->last_name); + + $op1_id = uniqid(); + $op1 = new Opportunity(); + $op1->new_with_id = TRUE; + $op1->id = $op1_id; + $op1->name = "UNIT TEST $op1_id"; + $op1->assigned_user_id = $user_id; + $op1->save(); + $results[] = array('id' => $op1_id, 'fieldName' => 'name', 'fieldValue' => "UNIT TEST $op1_id"); + + $op2_id = uniqid(); + $op2 = new Opportunity(); + $op2->new_with_id = TRUE; + $op2->id = $op2_id; + $op2->name = "UNIT TEST $op2_id"; + $op2->assigned_user_id = 'unittest'; + $op2->save(); + $results[] = array('id' => $op2_id, 'fieldName' => 'name', 'fieldValue' => "UNIT TEST $op2_id"); + + return $results; + } + + /** + * Linear search function used to find a bean id in an entry list array. + * + * @param array $list + * @param string $bean_id + */ + function findBeanIdFromEntryList($list,$bean_id,$module) + { + $found = FALSE; + foreach ($list as $moduleEntry) + { + if($moduleEntry['name'] == $module) + { + foreach ($moduleEntry['records'] as $entry) + { + foreach ($entry as $fieldEntry) + { + if($fieldEntry['name'] == 'id' && $fieldEntry['value'] == $bean_id ) + return TRUE; + } + } + } + } + + return $found; + } + + /** + * Linear search function used to find a particular field in an entry list array. + * + * @param array $list + * @param string $bean_id + */ + function findFieldByNameFromEntryList($list,$bean_id,$module,$fieldName) + { + $found = FALSE; + + foreach ($list as $moduleEntry) + { + if($moduleEntry['name'] == $module) + { + foreach ($moduleEntry['records'] as $entry) + { + $value = $this->_retrieveFieldValueByFieldName($entry, $fieldName,$bean_id); + if($value !== FALSE) + return $value; + } + } + } + + return $found; + } + + function _retrieveFieldValueByFieldName($entry, $fieldName, $beanId) + { + $found = FALSE; + $fieldValue = FALSE; + foreach ($entry as $fieldEntry) + { + if($fieldEntry['name'] == 'id' && $fieldEntry['value'] == $beanId ) + $found = TRUE; + + if($fieldEntry['name'] == $fieldName ) + $fieldValue = $fieldEntry['value']; + } + + if($found) + return $fieldValue; + else + return FALSE; + } +} \ No newline at end of file diff --git a/tests/service/Bug39234Test.php b/tests/service/Bug39234Test.php new file mode 100755 index 00000000..5e8fc017 --- /dev/null +++ b/tests/service/Bug39234Test.php @@ -0,0 +1,152 @@ +_soapClient = new nusoapclient($GLOBALS['sugar_config']['site_url'].'/soap.php',false,false,false,false,false,600,600); + $this->_setupTestUser(); + + $beanList = array(); + $beanFiles = array(); + require('include/modules.php'); + $GLOBALS['beanList'] = $beanList; + $GLOBALS['beanFiles'] = $beanFiles; + + $unid = uniqid(); + $time = date('Y-m-d H:i:s'); + + $contact = new Contact(); + $contact->id = 'c_'.$unid; + $contact->first_name = 'testfirst'; + $contact->last_name = 'testlast'; + $contact->email1 = 'fred@rogers.com'; + $contact->new_with_id = true; + $contact->disable_custom_fields = true; + $contact->save(); + $this->c1 = $contact; + + $account = new Account(); + $account->id = 'a_'.$unid; + $account->name = 'acctfirst'; + $account->assigned_user_id = 'SugarUser'; + $account->new_with_id = true; + $account->disable_custom_fields = true; + $account->save(); + $this->a1 = $account; + + $this->c1->load_relationship('accounts'); + $this->c1->accounts->add($this->a1->id); + + $contact2 = new Contact(); + $contact2->id = 'c2_'.$unid; + $contact2->first_name = 'testfirst'; + $contact2->last_name = 'testlast'; + $contact2->email1 = 'fred@rogers.com'; + $contact2->new_with_id = true; + $contact2->disable_custom_fields = true; + $contact2->save(); + $this->c2 = $contact2; + } + + /** + * Remove anything that was used during this test + * + */ + public function tearDown() { + global $soap_version_test_accountId, $soap_version_test_opportunityId, $soap_version_test_contactId; + $this->_tearDownTestUser(); + $this->_user = null; + $this->_sessionId = ''; + $GLOBALS['db']->query("DELETE FROM contacts WHERE id= '{$this->c1->id}'"); + $GLOBALS['db']->query("DELETE FROM contacts WHERE id= '{$this->c2->id}'"); + $GLOBALS['db']->query("DELETE FROM accounts_contacts WHERE contact_id= '{$this->c1->id}'"); + $GLOBALS['db']->query("DELETE FROM accounts_contacts WHERE contact_id= '{$this->c2->id}'"); + $GLOBALS['db']->query("DELETE FROM accounts WHERE id= '{$this->a1->id}'"); + + unset($this->c1); + unset($this->c2); + unset($this->a1); + unset($soap_version_test_accountId); + unset($soap_version_test_opportunityId); + unset($soap_version_test_contactId); + unset($GLOBALS['beanList']); + unset($GLOBALS['beanFiles']); + } + + public function testSetEntries() { + $this->_login(); + $result = $this->_soapClient->call('set_entries',array('session'=>$this->_sessionId,'module_name' => 'Contacts','name_value_lists' => array(array(array('name'=>'last_name' , 'value'=>$this->c1->last_name), array('name'=>'email1' , 'value'=>$this->c1->email1), array('name'=>'first_name' , 'value'=>$this->c1->first_name), array('name'=>'account_name' , 'value'=>$this->a1->name))))); + $this->assertTrue(isset($result['ids']) && $result['ids'][0] == $this->c1->id); + } // fn + + public function testSetEntries2() { + $this->_login(); + $result = $this->_soapClient->call('set_entries',array('session'=>$this->_sessionId,'module_name' => 'Contacts','name_value_lists' => array(array(array('name'=>'last_name' , 'value'=>$this->c2->last_name), array('name'=>'email1' , 'value'=>$this->c2->email1), array('name'=>'first_name' , 'value'=>$this->c2->first_name), array('name'=>'account_name' , 'value'=>'joe pizza'))))); + $this->assertTrue(isset($result['ids']) && $result['ids'][0] != $this->c1->id); + } // fn + + /********************************** + * HELPER PUBLIC FUNCTIONS + **********************************/ + + /** + * Attempt to login to the soap server + * + * @return $set_entry_result - this should contain an id and error. The id corresponds + * to the session_id. + */ + public function _login(){ + global $current_user; + $result = $this->_soapClient->call('login', + array('user_auth' => + array('user_name' => $current_user->user_name, + 'password' => $current_user->user_hash, + 'version' => '.01'), + 'application_name' => 'SoapTest') + ); + $this->_sessionId = $result['id']; + return $result; + } + + /** + * Create a test user + * + */ + public function _setupTestUser() { + $this->_user = SugarTestUserUtilities::createAnonymousUser(); + $this->_user->status = 'Active'; + $this->_user->is_admin = 1; + $this->_user->save(); + $GLOBALS['current_user'] = $this->_user; + } + + /** + * Remove user created for test + * + */ + public function _tearDownTestUser() { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + } + +} +?> \ No newline at end of file diff --git a/tests/service/Bug39855Test.php b/tests/service/Bug39855Test.php new file mode 100755 index 00000000..df4d5fe0 --- /dev/null +++ b/tests/service/Bug39855Test.php @@ -0,0 +1,139 @@ +markTestSkipped('Skipping for now while investigating'); + //setup test portal user + $this->_setupTestUser(); + $this->_soapClient = new nusoapclient($GLOBALS['sugar_config']['site_url'].'/soap.php',false,false,false,false,false,600,600); + $this->_login(); + + //setup test account + $account = new Account(); + $account->name = 'test account for bug 39855'; + $account->assigned_user_id = 'SugarUser'; + $account->save(); + $this->_acc = $account; + + //setup test cases + $case1 = new aCase(); + $case1->name = 'test case for bug 39855 ASDF'; + $case1->account_id = $this->_acc->id; + $case1->status = 'New'; + $case1->save(); + $this->_case1 = $case1; + + $case2 = new aCase(); + //$account->id = 'a_'.$unid; + $case2->name = 'test case for bug 39855 QWER'; + $case2->account_id = $this->_acc->id; + $case2->status = 'Rejected'; + $case2->save(); + $this->_case2 = $case2; + + + } + + /** + * Remove anything that was used during this test + * + */ + public function tearDown() { + global $soap_version_test_accountId, $soap_version_test_opportunityId, $soap_version_test_contactId; + $this->_tearDownTestUser(); + $this->_user = null; + $this->_sessionId = ''; + $GLOBALS['db']->query("DELETE FROM cases WHERE name like 'test case for bug 39855%'"); + $GLOBALS['db']->query("DELETE FROM accounts WHERE name like 'test account for bug 39855%'"); + + unset($this->_case1); + unset($this->_case2); + unset($this->_acc1); + + } + + public function testGetEntry() { + //test retrieving a case by id + $result = $this->_soapClient->call('portal_get_entry',array('session'=>$this->_sessionId,'module_name'=>'Cases','id'=>$this->_case1->id ,'select_field'=>array('case_number','status', 'name','description'))); + $this->assertTrue($result['entry_list'][0]['id'] == $this->_case1->id,'portal_get_entry was not able to retrieve a case record by id'); + + $result = $this->_soapClient->call('portal_logout',array('session' => $this->_sessionId)); + } + + public function testGetEntryList() { + $w = " name LIKE 'test case for bug 39855 %' "; + + $result = $this->_soapClient->call('portal_get_entry_list',array('session'=>$this->_sessionId,'module_name'=>'Cases','where'=>$w ,'', 'select_field'=>array('case_number','status', 'name','description'))); + $this->assertTrue($result['result_count'] > 1,'portal_get_entry_list was not able to retrieve both cases using the following where clause: '.$w); + + } + + /********************************** + * HELPER PUBLIC FUNCTIONS + **********************************/ + + /** + * Attempt to login to the soap server + * + * @return $set_entry_result - this should contain an id and error. The id corresponds + * to the session_id. + */ + public function _login(){ + global $current_user; + $result = $this->_soapClient->call('portal_login', + array('user_auth' => + array('user_name' => $this->_user->user_name, + 'password' => $this->_user->user_hash, + 'version' => '.01'), + 'user_name' =>'portal', + 'application_name' => 'SoapTestPortal') + ); + $this->_sessionId = $result['id']; + return $result; + + } + + /** + * Create a test portal user + * + */ + public function _setupTestUser() { + $this->_user = SugarTestUserUtilities::createAnonymousUser(); + $this->_user->status = 'Active'; + $this->_user->portal_only = 1; + $this->_user->save(); + } + + + + /** + * Remove user created for test + * + */ + public function _tearDownTestUser() { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + } + +} +?> \ No newline at end of file diff --git a/tests/service/Bug40250Test.php b/tests/service/Bug40250Test.php new file mode 100755 index 00000000..3904d955 --- /dev/null +++ b/tests/service/Bug40250Test.php @@ -0,0 +1,101 @@ +_setupTestUser(); + $this->_soapClient = new nusoapclient($GLOBALS['sugar_config']['site_url'].'/soap.php',false,false,false,false,false,60,60); + $this->_login(); + } + + /** + * Remove anything that was used during this test + * + */ + public function tearDown() { + global $soap_version_test_accountId, $soap_version_test_opportunityId, $soap_version_test_contactId; + $this->_tearDownTestUser(); + $this->_user = null; + $this->_sessionId = ''; + } + + public function testRetrieveUsersList() { + //First retrieve the users count (should be at least 1) + $countArr = $this->_soapClient->call('get_entries_count',array('session'=>$this->_sessionId,'module_name'=>'Users','query'=>" users.status = 'active' ",0)); + $count = $countArr['result_count']; + $this->assertTrue($count > 1, 'no users were retrieved so the test user was not set up correctly'); + + //now retrieve the list of users + $usersArr = $this->_soapClient->call('get_entry_list',array('session'=>$this->_sessionId,'module_name'=>'Users','query'=>" users.status = 'active' ", 'user_name','0' ,'select_field'=>array('user_name'),100,0)); + $usersCount = $usersArr['result_count']; + + //the count from both functions should be the same + $this->assertTrue($count == $usersCount ,'count is not the same which means that the 2 calls are generating different results.'); + + //logout + $result = $this->_soapClient->call('logout',array('session' => $this->_sessionId)); + } + + /********************************** + * HELPER PUBLIC FUNCTIONS + **********************************/ + + /** + * Attempt to login to the soap server + * + * @return $set_entry_result - this should contain an id and error. The id corresponds + * to the session_id. + */ + public function _login(){ + global $current_user; + $result = $this->_soapClient->call('login', + array('user_auth' => + array('user_name' => $this->_user->user_name, + 'password' => $this->_user->user_hash, + 'version' => '.01'), + 'application_name' => 'SoapTest') + ); + $this->_sessionId = $result['id']; + return $result; + + } + + /** + * Create a test user + * + */ + public function _setupTestUser() { + $this->_user = SugarTestUserUtilities::createAnonymousUser(); + $this->_user->status = 'Active'; + $this->_user->is_admin = 1; + $this->_user->save(); + } + + + + /** + * Remove user created for test + * + */ + public function _tearDownTestUser() { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + } + +} +?> \ No newline at end of file diff --git a/tests/service/Bug42683Test.php b/tests/service/Bug42683Test.php new file mode 100755 index 00000000..1471da42 --- /dev/null +++ b/tests/service/Bug42683Test.php @@ -0,0 +1,37 @@ +_soapURL = $GLOBALS['sugar_config']['site_url'].'/service/v2/soap.php'; + parent::setUp(); + } + + public function testBadQuery() + { + $lead = SugarTestLeadUtilities::createLead(); + + $this->_login(); + $result = $this->_soapClient->call( + 'get_entry_list', + array( + 'session' => $this->_sessionId, + "module_name" => 'Leads', + "query" => "leads.id = '{$lead->id}'", + '', + 0, + array(), + array(array('name' => 'email_addresses', 'value' => array('id', 'email_address', 'opt_out', 'primary_address'))), + ) + ); + + $this->assertEquals('primary_address', $result['relationship_list'][0][0]['records'][0][3]['name']); + + SugarTestLeadUtilities::removeAllCreatedLeads(); + } +} diff --git a/tests/service/RESTAPI3Test.php b/tests/service/RESTAPI3Test.php new file mode 100755 index 00000000..d4acbf8d --- /dev/null +++ b/tests/service/RESTAPI3Test.php @@ -0,0 +1,771 @@ +_user = SugarTestUserUtilities::createAnonymousUser(); + $this->_user->status = 'Active'; + $this->_user->is_admin = 1; + $this->_user->save(); + $GLOBALS['current_user'] = $this->_user; + + self::$helperObject = new APIv3Helper(); + } + + public function tearDown() + { + if(isset($GLOBALS['listViewDefs'])) unset($GLOBALS['listViewDefs']); + if(isset($GLOBALS['viewdefs'])) unset($GLOBALS['viewdefs']); + } + + protected function _makeRESTCall($method,$parameters) + { + // specify the REST web service to interact with + $url = $GLOBALS['sugar_config']['site_url'].'/service/v3/rest.php'; + // Open a curl session for making the call + $curl = curl_init($url); + // set URL and other appropriate options + curl_setopt($curl, CURLOPT_URL, $url); + curl_setopt($curl, CURLOPT_POST, 1); + curl_setopt($curl, CURLOPT_HEADER, 0); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0); + curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 ); + // build the request URL + $json = json_encode($parameters); + $postArgs = "method=$method&input_type=JSON&response_type=JSON&rest_data=$json"; + curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs); + // Make the REST call, returning the result + $response = curl_exec($curl); + // Close the connection + curl_close($curl); + + $this->_lastRawResponse = $response; + + // Convert the result from JSON format to a PHP array + return json_decode($response,true); + } + + protected function _returnLastRawResponse() + { + return "Error in web services call. Response was: {$this->_lastRawResponse}"; + } + + protected function _login() + { + return $this->_makeRESTCall('login', + array( + 'user_auth' => + array( + 'user_name' => $this->_user->user_name, + 'password' => $this->_user->user_hash, + 'version' => '.01', + ), + 'application_name' => 'SugarTestRunner', + 'name_value_list' => array(), + ) + ); + } + + public function testSearchByModule() + { + $result = $this->_login(); + $session = $result['id']; + + $seedData = self::$helperObject->populateSeedDataForSearchTest($this->_user->id); + + $searchModules = array('Accounts','Contacts','Opportunities'); + $searchString = "UNIT TEST"; + $offSet = 0; + $maxResults = 10; + + $results = $this->_makeRESTCall('search_by_module', + array( + 'session' => $session, + 'search' => $searchString, + 'modules' => $searchModules, + 'offset' => $offSet, + 'max' => $maxResults, + 'user' => $this->_user->id) + ); + + $this->assertTrue( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[0]['id'],'Accounts') ); + $this->assertFalse( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[1]['id'],'Accounts') ); + $this->assertTrue( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[2]['id'],'Contacts') ); + $this->assertTrue( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[3]['id'],'Opportunities') ); + $this->assertFalse( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[4]['id'],'Opportunities') ); + $GLOBALS['db']->query("DELETE FROM accounts WHERE name like 'UNIT TEST%' "); + $GLOBALS['db']->query("DELETE FROM opportunities WHERE name like 'UNIT TEST%' "); + $GLOBALS['db']->query("DELETE FROM contacts WHERE first_name like 'UNIT TEST%' "); + } + + public function testSearchByModuleWithReturnFields() + { + $result = $this->_login(); + $session = $result['id']; + + $seedData = self::$helperObject->populateSeedDataForSearchTest($this->_user->id); + + $returnFields = array('name','id','deleted'); + $searchModules = array('Accounts','Contacts','Opportunities'); + $searchString = "UNIT TEST"; + $offSet = 0; + $maxResults = 10; + + $results = $this->_makeRESTCall('search_by_module', + array( + 'session' => $session, + 'search' => $searchString, + 'modules' => $searchModules, + 'offset' => $offSet, + 'max' => $maxResults, + 'user' => $this->_user->id, + 'selectFields' => $returnFields) + ); + + + $this->assertEquals($seedData[0]['fieldValue'], self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[0]['id'],'Accounts', $seedData[0]['fieldName'])); + $this->assertFalse(self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[1]['id'],'Accounts', $seedData[1]['fieldName'])); + $this->assertEquals($seedData[2]['fieldValue'], self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[2]['id'],'Contacts', $seedData[2]['fieldName'])); + $this->assertEquals($seedData[3]['fieldValue'], self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[3]['id'],'Opportunities', $seedData[3]['fieldName'])); + $this->assertFalse(self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[4]['id'],'Opportunities', $seedData[4]['fieldName'])); + + $GLOBALS['db']->query("DELETE FROM accounts WHERE name like 'UNIT TEST%' "); + $GLOBALS['db']->query("DELETE FROM opportunities WHERE name like 'UNIT TEST%' "); + $GLOBALS['db']->query("DELETE FROM contacts WHERE first_name like 'UNIT TEST%' "); + } + + public function testGetServerInformation() + { + require('sugar_version.php'); + + $result = $this->_login(); + $session = $result['id']; + + $result = $this->_makeRESTCall('get_server_info',array()); + + $this->assertEquals($sugar_version, $result['version'],'Unable to get server information'); + $this->assertEquals($sugar_flavor, $result['flavor'],'Unable to get server information'); + } + + public function testGetModuleList() + { + $result = $this->_login(); + $session = $result['id']; + + $account = new Account(); + $account->id = uniqid(); + $account->new_with_id = TRUE; + $account->name = "Test " . $account->id; + $account->save(); + + $whereClause = "accounts.name='{$account->name}'"; + $module = 'Accounts'; + $orderBy = 'name'; + $offset = 0; + $returnFields = array('name'); + $result = $this->_makeRESTCall('get_entry_list', array($session, $module, $whereClause, $orderBy,$offset, $returnFields)); + + $this->assertEquals($account->id, $result['entry_list'][0]['id'],'Unable to retrieve account list during search.'); + + $GLOBALS['db']->query("DELETE FROM accounts WHERE id = '{$account->id}'"); + + } + + public function testLogin() + { + $result = $this->_login(); + $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse()); + } + + public static function _multipleModuleLayoutProvider() + { + return array( + array( + 'module' => array('Accounts','Contacts'), + 'type' => array('default'), + 'view' => array('list'), + 'expected_file' => array( + 'Accounts' => array( 'default' => array('list' => 'modules/Accounts/metadata/listviewdefs.php')), + 'Contacts' => array( 'default' => array('list' => 'modules/Contacts/metadata/listviewdefs.php'))) + ), + array( + 'module' => array('Accounts','Contacts'), + 'type' => array('default'), + 'view' => array('list','detail'), + 'expected_file' => array( + 'Accounts' => array( + 'default' => array( + 'list' => 'modules/Accounts/metadata/listviewdefs.php', + 'detail' => 'modules/Accounts/metadata/detailviewdefs.php')), + 'Contacts' => array( + 'default' => array( + 'list' => 'modules/Contacts/metadata/listviewdefs.php', + 'detail' => 'modules/Contacts/metadata/detailviewdefs.php')) + )) + ); + } + + /** + * @dataProvider _multipleModuleLayoutProvider + */ + public function testGetMultipleModuleLayout($a_module, $a_type, $a_view, $a_expected_file) + { + $result = $this->_login(); + $session = $result['id']; + + $results = $this->_makeRESTCall('get_module_layout', + array( + 'session' => $session, + 'module' => $a_module, + 'type' => $a_type, + 'view' => $a_view) + ); + + foreach ($results as $module => $moduleResults ) + { + foreach ($moduleResults as $type => $viewResults) + { + foreach ($viewResults as $view => $result) + { + $expected_file = $a_expected_file[$module][$type][$view]; + if ( is_file('custom' . DIRECTORY_SEPARATOR . $expected_file) ) + require('custom' . DIRECTORY_SEPARATOR . $expected_file); + else + require($expected_file); + + if($view == 'list') + $expectedResults = $listViewDefs[$module]; + else + $expectedResults = $viewdefs[$module][ucfirst($view) .'View' ]; + + $this->assertEquals(md5(serialize($expectedResults)), md5(serialize($result)), "Unable to retrieve module layout: module {$module}, type $type, view $view"); + } + } + } + } + + public static function _moduleLayoutProvider() + { + return array( + array('module' => 'Accounts','type' => 'default', 'view' => 'list','expected_file' => 'modules/Accounts/metadata/listviewdefs.php' ), + array('module' => 'Accounts','type' => 'default', 'view' => 'edit','expected_file' => 'modules/Accounts/metadata/editviewdefs.php' ), + array('module' => 'Accounts','type' => 'default', 'view' => 'detail','expected_file' => 'modules/Accounts/metadata/detailviewdefs.php' ), + ); + } + + /** + * @dataProvider _moduleLayoutProvider + */ + public function testGetModuleLayout($module, $type, $view, $expected_file) + { + $result = $this->_login(); + $session = $result['id']; + + $result = $this->_makeRESTCall('get_module_layout', + array( + 'session' => $session, + 'module' => array($module), + 'type' => array($type), + 'view' => array($view)) + ); + + if ( is_file('custom' . DIRECTORY_SEPARATOR . $expected_file) ) + require('custom' . DIRECTORY_SEPARATOR . $expected_file); + else + require($expected_file); + + if($view == 'list') + $expectedResults = $listViewDefs[$module]; + else + $expectedResults = $viewdefs[$module][ucfirst($view) .'View' ]; + + $a_expectedResults = array(); + $a_expectedResults[$module][$type][$view] = $expectedResults; + + $this->assertEquals(md5(serialize($a_expectedResults)), md5(serialize($result)), "Unable to retrieve module layout: module {$module}, type $type, view $view"); + } + + /** + * @dataProvider _moduleLayoutProvider + */ + public function testGetModuleLayoutMD5($module, $type, $view, $expected_file) + { + $result = $this->_login(); + $session = $result['id']; + + $fullResult = $this->_makeRESTCall('get_module_layout_md5', + array( + 'session' => $session, + 'module' => array($module), + 'type' => array($type), + 'view' => array($view) ) + ); + $result = $fullResult['md5']; + if ( is_file('custom' . DIRECTORY_SEPARATOR . $expected_file) ) + require('custom' . DIRECTORY_SEPARATOR . $expected_file); + else + require($expected_file); + + if($view == 'list') + $expectedResults = $listViewDefs[$module]; + else + $expectedResults = $viewdefs[$module][ucfirst($view) .'View' ]; + + $a_expectedResults = array(); + $a_expectedResults[$module][$type][$view] = $expectedResults; + + $this->assertEquals(md5(serialize($expectedResults)), $result[$module][$type][$view], "Unable to retrieve module layout md5: module {$module}, type $type, view $view"); + + } + + public function testGetAvailableModules() + { + $this->markTestSkipped('Will be updated week of June 21, 2010'); + + $result = $this->_login(); + $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse()); + $session = $result['id']; + + $fullResult = $this->_makeRESTCall('get_available_modules', array('session' => $session, 'filter' => 'all' )); + $this->assertTrue(in_array('ACLFields', $fullResult['modules']), "Unable to get all available modules"); + $this->assertTrue(in_array('Schedulers', $fullResult['modules']), "Unable to get all available modules"); + $this->assertTrue(in_array('Roles', $fullResult['modules']), "Unable to get all available modules"); + + $sh = new SugarWebServiceUtilv3(); + + $mobileResult = $this->_makeRESTCall('get_available_modules', array('session' => $session, 'filter' => 'mobile' )); + $mobileResultExpected = $sh->get_visible_mobile_modules($fullResult['modules']); + $mobileResultExpected = md5(serialize(array('modules' => $mobileResultExpected))); + $mobileResult = md5(serialize($mobileResult)); + $this->assertEquals($mobileResultExpected, $mobileResult, "Unable to get all visible mobile modules"); + + $defaultResult = $this->_makeRESTCall('get_available_modules', array('session' => $session, 'filter' => 'default' )); + $defaultResult = md5(serialize($defaultResult['modules'])); + $defaultResultExpected = $sh->get_visible_modules($fullResult['modules']); + $defaultResultExpected = md5(serialize($defaultResultExpected)); + $this->assertEquals($defaultResultExpected, $defaultResult, "Unable to get all visible default modules"); + + } + + public function testGetVardefsMD5() + { + $GLOBALS['reload_vardefs'] = TRUE; + $result = $this->_login(); + $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse()); + $session = $result['id']; + + //Test a regular module + $fullResult = $this->_makeRESTCall('get_module_fields_md5', array('session' => $session, 'module' => 'Accounts' )); + $result = $fullResult['Accounts']; + $a = new Account(); + $soapHelper = new SugarWebServiceUtilv3(); + $actualVardef = $soapHelper->get_return_module_fields($a,'Accounts',''); + $actualMD5 = md5(serialize($actualVardef)); + $this->assertEquals($actualMD5, $result, "Unable to retrieve vardef md5."); + + //Test a fake module + $result = $this->_makeRESTCall('get_module_fields_md5', array('session' => $session, 'module' => 'BadModule' )); + $this->assertTrue($result['name'] == 'Module Does Not Exist'); + unset($GLOBALS['reload_vardefs']); + } + + public function testAddNewAccountAndThenDeleteIt() + { + $result = $this->_login(); + $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse()); + $session = $result['id']; + + $result = $this->_makeRESTCall('set_entry', + array( + 'session' => $session, + 'module' => 'Accounts', + 'name_value_list' => array( + array('name' => 'name', 'value' => 'New Account'), + array('name' => 'description', 'value' => 'This is an account created from a REST web services call'), + ), + ) + ); + + $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse()); + + $accountId = $result['id']; + + // verify record was created + $result = $this->_makeRESTCall('get_entry', + array( + 'session' => $session, + 'module' => 'Accounts', + 'id' => $accountId, + ) + ); + + $this->assertEquals($result['entry_list'][0]['id'],$accountId,$this->_returnLastRawResponse()); + + // delete the record + $result = $this->_makeRESTCall('set_entry', + array( + 'session' => $session, + 'module' => 'Accounts', + 'name_value_list' => array( + array('name' => 'id', 'value' => $accountId), + array('name' => 'deleted', 'value' => '1'), + ), + ) + ); + + $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse()); + + // try to retrieve again to validate it is deleted + $result = $this->_makeRESTCall('get_entry', + array( + 'session' => $session, + 'module' => 'Accounts', + 'id' => $accountId, + ) + ); + + $this->assertTrue(!empty($result['entry_list'][0]['id']) && $result['entry_list'][0]['id'] != -1,$this->_returnLastRawResponse()); + $this->assertEquals($result['entry_list'][0]['name_value_list'][0]['name'],'warning',$this->_returnLastRawResponse()); + $this->assertEquals($result['entry_list'][0]['name_value_list'][0]['value'],"Access to this object is denied since it has been deleted or does not exist",$this->_returnLastRawResponse()); + $this->assertEquals($result['entry_list'][0]['name_value_list'][1]['name'],'deleted',$this->_returnLastRawResponse()); + $this->assertEquals($result['entry_list'][0]['name_value_list'][1]['value'],1,$this->_returnLastRawResponse()); + } + + public function testRelateAccountToTwoContacts() + { + $result = $this->_login(); + $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse()); + $session = $result['id']; + + $result = $this->_makeRESTCall('set_entry', + array( + 'session' => $session, + 'module' => 'Accounts', + 'name_value_list' => array( + array('name' => 'name', 'value' => 'New Account'), + array('name' => 'description', 'value' => 'This is an account created from a REST web services call'), + ), + ) + ); + + $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse()); + + $accountId = $result['id']; + + $result = $this->_makeRESTCall('set_entry', + array( + 'session' => $session, + 'module' => 'Contacts', + 'name_value_list' => array( + array('name' => 'last_name', 'value' => 'New Contact 1'), + array('name' => 'description', 'value' => 'This is a contact created from a REST web services call'), + ), + ) + ); + + $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse()); + + $contactId1 = $result['id']; + + $result = $this->_makeRESTCall('set_entry', + array( + 'session' => $session, + 'module' => 'Contacts', + 'name_value_list' => array( + array('name' => 'last_name', 'value' => 'New Contact 2'), + array('name' => 'description', 'value' => 'This is a contact created from a REST web services call'), + ), + ) + ); + + $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse()); + + $contactId2 = $result['id']; + + // now relate them together + $result = $this->_makeRESTCall('set_relationship', + array( + 'session' => $session, + 'module' => 'Accounts', + 'module_id' => $accountId, + 'link_field_name' => 'contacts', + 'related_ids' => array($contactId1,$contactId2), + ) + ); + + $this->assertEquals($result['created'],1,$this->_returnLastRawResponse()); + + // check the relationship + $result = $this->_makeRESTCall('get_relationships', + array( + 'session' => $session, + 'module' => 'Accounts', + 'module_id' => $accountId, + 'link_field_name' => 'contacts', + 'related_module_query' => '', + 'related_fields' => array('last_name','description'), + 'related_module_link_name_to_fields_array' => array(), + 'deleted' => false, + ) + ); + + $returnedValues = array(); + $returnedValues[] = $result['entry_list'][0]['name_value_list']['last_name']['value']; + $returnedValues[] = $result['entry_list'][1]['name_value_list']['last_name']['value']; + + + $this->assertContains('New Contact 1',$returnedValues,$this->_returnLastRawResponse()); + $this->assertContains('New Contact 2',$returnedValues,$this->_returnLastRawResponse()); + } + + /** + * @group bug36658 + */ + public function testOrderByClauseOfGetRelationship() + { + $result = $this->_login(); + $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse()); + $session = $result['id']; + + $result = $this->_makeRESTCall('set_entry', + array( + 'session' => $session, + 'module' => 'Accounts', + 'name_value_list' => array( + array('name' => 'name', 'value' => 'New Account'), + array('name' => 'description', 'value' => 'This is an account created from a REST web services call'), + ), + ) + ); + + $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse()); + + $accountId = $result['id']; + + $result = $this->_makeRESTCall('set_entry', + array( + 'session' => $session, + 'module' => 'Contacts', + 'name_value_list' => array( + array('name' => 'last_name', 'value' => 'New Contact 1'), + array('name' => 'description', 'value' => 'This is a contact created from a REST web services call'), + ), + ) + ); + + $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse()); + + $contactId1 = $result['id']; + + $result = $this->_makeRESTCall('set_entry', + array( + 'session' => $session, + 'module' => 'Contacts', + 'name_value_list' => array( + array('name' => 'last_name', 'value' => 'New Contact 2'), + array('name' => 'description', 'value' => 'This is a contact created from a REST web services call'), + ), + ) + ); + + $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse()); + + $contactId2 = $result['id']; + + // now relate them together + $result = $this->_makeRESTCall('set_relationship', + array( + 'session' => $session, + 'module' => 'Accounts', + 'module_id' => $accountId, + 'link_field_name' => 'contacts', + 'related_ids' => array($contactId1,$contactId2), + ) + ); + + $this->assertEquals($result['created'],1,$this->_returnLastRawResponse()); + + // check the relationship + $result = $this->_makeRESTCall('get_relationships', + array( + 'session' => $session, + 'module' => 'Accounts', + 'module_id' => $accountId, + 'link_field_name' => 'contacts', + 'related_module_query' => '', + 'related_fields' => array('last_name','description'), + 'related_module_link_name_to_fields_array' => array(), + 'deleted' => false, + 'order_by' => 'last_name', + ) + ); + + $this->assertEquals($result['entry_list'][0]['name_value_list']['last_name']['value'],'New Contact 1',$this->_returnLastRawResponse()); + $this->assertEquals($result['entry_list'][1]['name_value_list']['last_name']['value'],'New Contact 2',$this->_returnLastRawResponse()); + } + + public static function _subpanelLayoutProvider() + { + return array( + array( + 'module' => 'Contacts', + 'type' => 'default', + 'view' => 'subpanel', + ), + array( + 'module' => 'Leads', + 'type' => 'wireless', + 'view' => 'subpanel', + ) + ); + } + + /** + * @dataProvider _subpanelLayoutProvider + */ + public function testGetSubpanelLayout($module, $type, $view) + { + $result = $this->_login(); + $session = $result['id']; + + $results = $this->_makeRESTCall('get_module_layout', + array( + 'session' => $session, + 'module' => array($module), + 'type' => array($type), + 'view' => array($view)) + ); + + $this->assertTrue(isset($results[$module][$type][$view]), "Unable to get subpanel defs"); + } + + public function testGetLastViewed() + { + $result = $this->_login(); + $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse()); + $session = $result['id']; + + $testModule = 'Accounts'; + $testModuleID = uniqid(); + + $this->_createTrackerEntry($testModule,$testModuleID); + + $results = $this->_makeRESTCall('get_last_viewed', + array( + 'session' => $session, + 'modules' => array($testModule), + ) + ); + + $found = FALSE; + foreach ($results as $entry) + { + if($entry['item_id'] == $testModuleID) + { + $found = TRUE; + break; + } + } + + $this->assertTrue($found, "Unable to get last viewed modules"); + } + + private function _createTrackerEntry($module, $id,$summaryText = "UNIT TEST SUMMARY") + { + $trackerManager = TrackerManager::getInstance(); + $timeStamp = gmdate($GLOBALS['timedate']->get_db_date_time_format()); + $monitor = $trackerManager->getMonitor('tracker'); + + $monitor->setValue('action', 'detail'); + $monitor->setValue('user_id', $this->_user->id); + $monitor->setValue('module_name', $module); + $monitor->setValue('date_modified', $timeStamp); + $monitor->setValue('visible', true); + $monitor->setValue('item_id', $id); + $monitor->setValue('item_summary', $summaryText); + $trackerManager->saveMonitor($monitor, true, true); + } + + public function testGetUpcomingActivities() + { + $result = $this->_login(); + $this->assertTrue(!empty($result['id']) && $result['id'] != -1,$this->_returnLastRawResponse()); + $session = $result['id']; + $expected = $this->_createUpcomingActivities(); //Seed the data. + $results = $this->_makeRESTCall('get_upcoming_activities', + array( + 'session' => $session, + ) + ); + + $this->assertEquals($expected[0] ,$results[0]['id'] , "Unable to get upcoming activities"); + $this->assertEquals($expected[1] ,$results[1]['id'] , "Unable to get upcoming activities"); + + $this->_removeUpcomingActivities(); + } + + private function _removeUpcomingActivities() + { + $GLOBALS['db']->query("DELETE FROM calls where name = 'UNIT TEST'"); + $GLOBALS['db']->query("DELETE FROM tasks where name = 'UNIT TEST'"); + } + + private function _createUpcomingActivities() + { + $GLOBALS['current_user']->setPreference('datef','Y-m-d') ; + $GLOBALS['current_user']->setPreference('timef','H:i') ; + + $date1 = $GLOBALS['timedate']->to_display_date_time(gmdate("Y-m-d H:i:s", (gmmktime() + (3600 * 24 * 2) ) ),true,true, $GLOBALS['current_user']) ; //Two days from today + $date2 = $GLOBALS['timedate']->to_display_date_time(gmdate("Y-m-d H:i:s", (gmmktime() + (3600 * 24 * 4) ) ),true,true, $GLOBALS['current_user']) ; //Two days from today + + $callID = uniqid(); + $c = new Call(); + $c->id = $callID; + $c->new_with_id = TRUE; + $c->status = 'Not Planned'; + $c->date_start = $date1; + $c->name = "UNIT TEST"; + $c->assigned_user_id = $this->_user->id; + $c->save(FALSE); + + $callID = uniqid(); + $c = new Call(); + $c->id = $callID; + $c->new_with_id = TRUE; + $c->status = 'Planned'; + $c->date_start = $date1; + $c->name = "UNIT TEST"; + $c->assigned_user_id = $this->_user->id; + $c->save(FALSE); + + $taskID = uniqid(); + $t = new Task(); + $t->id = $taskID; + $t->new_with_id = TRUE; + $t->status = 'Not Started'; + $t->date_due = $date2; + $t->name = "UNIT TEST"; + $t->assigned_user_id = $this->_user->id; + $t->save(FALSE); + + return array($callID, $taskID); + } +} diff --git a/tests/service/SOAPAPI1Test.php b/tests/service/SOAPAPI1Test.php new file mode 100755 index 00000000..458b7c89 --- /dev/null +++ b/tests/service/SOAPAPI1Test.php @@ -0,0 +1,157 @@ +_soapClient = new nusoapclient($GLOBALS['sugar_config']['site_url'].'/soap.php',false,false,false,false,false,60,60); + $this->_setupTestUser(); + $this->_setupTestContact(); + $this->_meeting = SugarTestMeetingUtilities::createMeeting(); + } + + /** + * Remove anything that was used during this test + * + */ + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + $this->_user = null; + SugarTestContactUtilities::removeAllCreatedContacts(); + SugarTestContactUtilities::removeCreatedContactsUsersRelationships(); + $this->_contact = null; + SugarTestMeetingUtilities::removeAllCreatedMeetings(); + SugarTestMeetingUtilities::removeMeetingContacts(); + $this->_meeting = null; + } + + /** + * Ensure we can create a session on the server. + * + */ + public function testCanLogin() + { + $result = $this->_login(); + $this->assertTrue(!empty($result['id']) && $result['id'] != -1, + 'SOAP Session not created. Error ('.$result['error']['number'].'): '.$result['error']['name'].': '.$result['error']['description'].'. HTTP Response: '.$this->_soapClient->response); + } + + public function testSearchContactByEmail() + { + $result = $this->_soapClient->call('contact_by_email', array('user_name' => $this->_user->user_name, 'password' => $this->_user->user_hash, 'email_address' => $this->_contact->email1)); + $this->assertTrue(!empty($result) && count($result) > 0, 'Incorrect number of results returned. HTTP Response: '.$this->_soapClient->response); + $this->assertEquals($result[0]['name1'], $this->_contact->first_name, 'Incorrect result found'); + } + + public function testSearchByModule() + { + $modules = array('Contacts'); + $result = $this->_soapClient->call('search_by_module', array('user_name' => $this->_user->user_name, 'password' => $this->_user->user_hash, 'search_string' => $this->_contact->email1, 'modules' => $modules, 'offset' => 0, 'max_results' => 10)); + $this->assertTrue(!empty($result) && count($result['entry_list']) > 0, 'Incorrect number of results returned. HTTP Response: '.$this->_soapClient->response); + $this->assertEquals($result['entry_list'][0]['name_value_list'][1]['name'], 'first_name' && $result['entry_list'][0]['name_value_list'][1]['value'] == $this->_contact->first_name, 'Incorrect result returned'); + } + + public function testSearchBy() + { + $this->markTestSkipped('SOAP call "search" is deprecated'); + + $result = $this->_soapClient->call('search', array('user_name' => $this->_user->user_name, 'password' => $this->_user->user_hash, 'name' => $this->_contact->first_name)); + $this->assertTrue(!empty($result) && count($result) > 0, "Incorrect number of results returned - Returned $result results. HTTP Response: ".$this->_soapClient->response); + $this->assertEquals($result[0]['name1'], $this->_contact->first_name, "Contact First name does not match data returnd from SOAP_test"); + } + + public function testGetModifiedEntries() + { + $this->_login(); + $ids = array($this->_contact->id); + $result = $this->_soapClient->call('get_modified_entries', array('session' => $this->_sessionId, 'module_name' => 'Contacts', 'ids' => $ids, 'select_fields' => array())); + $decoded = base64_decode($result['result']); + } + + public function testGetAttendeeList() + { + $this->_login(); + $this->_meeting->load_relationship('contacts'); + $this->_meeting->contacts->add($this->_contact->id); + $result = $this->_soapClient->call('get_attendee_list', array('session' => $this->_sessionId, 'module_name' => 'Meetings', 'id' => $this->_meeting->id)); + $decoded = base64_decode($result['result']); + $decoded = simplexml_load_string($decoded); + $this->assertTrue(!empty($result['result']), 'Results not returned. HTTP Response: '.$this->_soapClient->response); + $this->assertEquals(urldecode($decoded->attendee->first_name), $this->_contact->first_name, 'Incorrect Result returned expected: '.$this->_contact->first_name.' Found: '.urldecode($decoded->attendee->first_name)); + } + + public function testSyncGetModifiedRelationships() + { + $this->_login(); + $ids = array($this->_contact->id); + $yesterday = date('Y-m-d', strtotime('last year')); + $tomorrow = date('Y-m-d', mktime(0, 0, 0, date("m") , date("d") + 1, date("Y"))); + $result = $this->_soapClient->call('sync_get_modified_relationships', array('session' => $this->_sessionId, 'module_name' => 'Users', 'related_module' => 'Contacts', 'from_date' => $yesterday, 'to_date' => $tomorrow, 'offset' => 0, 'max_results' => 10, 'deleted' => 0, 'module_id' => $this->_user->id, 'select_fields'=> array(), 'ids' => $ids, 'relationship_name' => 'contacts_users', 'deletion_date' => $yesterday, 'php_serialize' => 0)); + $this->assertTrue(!empty($result['entry_list']), 'Results not returned. HTTP Response: '.$this->_soapClient->response); + $decoded = base64_decode($result['entry_list']); + $decoded = simplexml_load_string($decoded); + if (isset($decoded->item[0]) ) { + $this->assertEquals(urlencode($decoded->item->name_value_list->name_value[1]->name), 'contact_id', "testSyncGetModifiedRelationships - could not retrieve contact_id column name"); + $this->assertEquals(urlencode($decoded->item->name_value_list->name_value[1]->value), $this->_contact->id, "vlue of contact id is not same as returned via SOAP"); + } + } + + /********************************** + * HELPER PUBLIC FUNCTIONS + **********************************/ + + /** + * Attempt to login to the soap server + * + * @return $set_entry_result - this should contain an id and error. The id corresponds + * to the session_id. + */ + private function _login(){ + $result = $this->_soapClient->call('login', + array('user_auth' => + array('user_name' => $this->_user->user_name, + 'password' => $this->_user->user_hash, + 'version' => '.01'), + 'application_name' => 'SoapTest') + ); + $this->_sessionId = $result['id']; + return $result; + } + + /** + * Create a test user + * + */ + private function _setupTestUser() { + $this->_user = SugarTestUserUtilities::createAnonymousUser(); + $this->_user->status = 'Active'; + $this->_user->is_admin = 1; + $this->_user->save(); + $GLOBALS['current_user'] = $this->_user; + } + + private function _setupTestContact() { + $this->_contact = SugarTestContactUtilities::createContact(); + $this->_contact->contacts_users_id = $this->_user->id; + $this->_contact->save(); + } + +} +?> diff --git a/tests/service/SOAPAPI2Test.php b/tests/service/SOAPAPI2Test.php new file mode 100755 index 00000000..4dbbe0e7 --- /dev/null +++ b/tests/service/SOAPAPI2Test.php @@ -0,0 +1,261 @@ +_soapClient = new nusoapclient($GLOBALS['sugar_config']['site_url'].'/service/v2/soap.php',false,false,false,false,false,600,600); + $this->_setupTestUser(); + } + + /** + * Remove anything that was used during this test + * + */ + public function tearDown() { + global $soap_version_test_accountId, $soap_version_test_opportunityId, $soap_version_test_contactId; + $this->_tearDownTestUser(); + $this->_user = null; + $this->_sessionId = ''; + unset($soap_version_test_accountId); + unset($soap_version_test_opportunityId); + unset($soap_version_test_contactId); + } + + /** + * Ensure we can create a session on the server. + * + */ + public function testCanLogin(){ + $result = $this->_login(); + $this->assertTrue(!empty($result['id']) && $result['id'] != -1, + 'SOAP Session not created. Error ('.$this->_soapClient->faultcode.'): '.$this->_soapClient->faultstring.': '.$this->_soapClient->faultdetail); + } + + public function testSetEntryForContact() { + global $soap_version_test_contactId; + $result = $this->_setEntryForContact(); + $soap_version_test_contactId = $result['id']; + $this->assertTrue(!empty($result['id']) && $result['id'] != -1, + 'Can not create new contact. Error ('.$this->_soapClient->faultcode.'): '.$this->_soapClient->faultstring.': '.$this->_soapClient->faultdetail); + } // fn + + public function testGetEntryForContact() { + $result = $this->_getEntryForContact(); + if (empty($this->_soapClient->faultcode)) { + if (($result['entry_list'][0]['name_value_list'][2]['value'] == 1) && + ($result['entry_list'][0]['name_value_list'][3]['value'] == "Cold Call") && + ($result['relationship_list'][0][0]['records'][0][1]['value'] == 'contact@sugar.com')) { + + $this->assertEquals($result['entry_list'][0]['name_value_list'][2]['value'],1,"testGetEntryForContact method - Get Entry For contact is not same as Set Entry"); + } // else + } else { + $this->assertTrue(empty($this->_soapClient->faultcode), 'Can not retrieve newly created contact. Error ('.$this->_soapClient->faultcode.'): '.$this->_soapClient->faultstring.': '.$this->_soapClient->faultdetail); + } + } // fn + + /** + * @ticket 38986 + */ + public function testGetEntryForContactNoSelectFields(){ + global $soap_version_test_contactId; + $this->_login(); + $result = $this->_soapClient->call('get_entry',array('session'=>$this->_sessionId,'module_name'=>'Contacts','id'=>$soap_version_test_contactId,'select_fields'=>array(), 'link_name_to_fields_array' => array())); + $this->assertTrue(!empty($result['entry_list'][0]['name_value_list']), "testGetEntryForContactNoSelectFields returned no field data"); + + } + + public function testSetEntriesForAccount() { + $result = $this->_setEntriesForAccount(); + $this->assertTrue(!empty($result['ids']) && $result['ids'][0] != -1, + 'Can not create new account using testSetEntriesForAccount. Error ('.$this->_soapClient->faultcode.'): '.$this->_soapClient->faultstring.': '.$this->_soapClient->faultdetail); + } // fn + + public function testSetEntryForOpportunity() { + $result = $this->_setEntryForOpportunity(); + $this->assertTrue(!empty($result['id']) && $result['id'] != -1, + 'Can not create new account using testSetEntryForOpportunity. Error ('.$this->_soapClient->faultcode.'): '.$this->_soapClient->faultstring.': '.$this->_soapClient->faultdetail); + } // fn + + public function testSetRelationshipForOpportunity() { + $result = $this->_setRelationshipForOpportunity(); + $this->assertTrue(($result['created'] > 0), 'testSetRelationshipForOpportunity method - Relationship for opportunity to Contact could not be created'); + + } // fn + + + public function testGetRelationshipForOpportunity() + { + global $soap_version_test_contactId; + $result = $this->_getRelationshipForOpportunity(); + $this->assertEquals( + $result['entry_list'][0]['id'], + $soap_version_test_contactId, + "testGetRelationshipForOpportunity - Get Relationship of Opportunity to Contact failed" + ); + } // fn + + public function testSearchByModule() { + $result = $this->_searchByModule(); + $this->assertTrue(($result['entry_list'][0]['records'] > 0 && $result['entry_list'][1]['records'] && $result['entry_list'][2]['records']), "testSearchByModule - could not retrieve any data by search"); + } // fn + + /********************************** + * HELPER PUBLIC FUNCTIONS + **********************************/ + + /** + * Attempt to login to the soap server + * + * @return $set_entry_result - this should contain an id and error. The id corresponds + * to the session_id. + */ + public function _login(){ + global $current_user; + $result = $this->_soapClient->call('login', + array('user_auth' => + array('user_name' => $current_user->user_name, + 'password' => $current_user->user_hash, + 'version' => '.01'), + 'application_name' => 'SoapTest', + 'name_value_list'=>array()) + ); + $this->_sessionId = $result['id']; + return $result; + } + + public function _setEntryForContact() { + $this->_login(); + global $timedate; + $current_date = $timedate->convert_to_gmt_datetime('now'); + $time = mt_rand(); + $first_name = 'SugarContactFirst' . $time; + $last_name = 'SugarContactLast'; + $email1 = 'contact@sugar.com'; + $result = $this->_soapClient->call('set_entry',array('session'=>$this->_sessionId,'module_name'=>'Contacts', 'name_value_list'=>array(array('name'=>'last_name' , 'value'=>"$last_name"), array('name'=>'first_name' , 'value'=>"$first_name"), array('name'=>'do_not_call' , 'value'=>"1"), array('name'=>'birthdate' , 'value'=>"$current_date"), array('name'=>'lead_source' , 'value'=>"Cold Call"), array('name'=>'email1' , 'value'=>"$email1")))); + SugarTestContactUtilities::setCreatedContact(array($this->_contactId)); + return $result; + } // fn + + public function _getEntryForContact() { + global $soap_version_test_contactId; + $this->_login(); + $result = $this->_soapClient->call('get_entry',array('session'=>$this->_sessionId,'module_name'=>'Contacts','id'=>$soap_version_test_contactId,'select_fields'=>array('last_name', 'first_name', 'do_not_call', 'lead_source', 'email1'), 'link_name_to_fields_array' => array(array('name' => 'email_addresses', 'value' => array('id', 'email_address', 'opt_out', 'primary_address'))))); $GLOBALS['log']->fatal("_getEntryForContact" . " " . $soap_version_test_contactId); + return $result; + } + + public function _setEntriesForAccount() { + global $soap_version_test_accountId; + $this->_login(); + global $timedate; + $current_date = $timedate->convert_to_gmt_datetime('now'); + $time = mt_rand(); + $name = 'SugarAccount' . $time; + $email1 = 'account@'. $time. 'sugar.com'; + $result = $this->_soapClient->call('set_entries',array('session'=>$this->_sessionId,'module_name'=>'Accounts', 'name_value_lists'=>array(array(array('name'=>'name' , 'value'=>"$name"), array('name'=>'email1' , 'value'=>"$email1"))))); + $soap_version_test_accountId = $result['ids'][0]; + $GLOBALS['log']->fatal("_setEntriesForAccount id = " . $soap_version_test_accountId); + SugarTestAccountUtilities::setCreatedAccount(array($soap_version_test_accountId)); + return $result; + } // fn + + public function _setEntryForOpportunity() { + global $soap_version_test_accountId, $soap_version_test_opportunityId; + $this->_login(); + global $timedate; + $date_closed = $timedate->convert_to_gmt_datetime(strtotime('+1 week')); + $time = mt_rand(); + $name = 'SugarOpportunity' . $time; + $account_id = $soap_version_test_accountId; + $sales_stage = 'Prospecting'; + $probability = 10; + $amount = 1000; + $GLOBALS['log']->fatal("_setEntryForOpportunity id = " . $soap_version_test_accountId); + $result = $this->_soapClient->call('set_entry',array('session'=>$this->_sessionId,'module_name'=>'Opportunities', 'name_value_lists'=>array(array('name'=>'name' , 'value'=>"$name"), array('name'=>'amount' , 'value'=>"$amount"), array('name'=>'probability' , 'value'=>"$probability"), array('name'=>'sales_stage' , 'value'=>"$sales_stage"), array('name'=>'account_id' , 'value'=>"$account_id")))); + $soap_version_test_opportunityId = $result['id']; + return $result; + } // fn + + public function _getEntryForOpportunity() { + global $soap_version_test_opportunityId; + $this->_login(); + $result = $this->_soapClient->call('get_entry',array('session'=>$this->_sessionId,'module_name'=>'Opportunities','id'=>$soap_version_test_opportunityId,'select_fields'=>array('name', 'amount'), 'link_name_to_fields_array' => array(array('name' => 'contacts', 'value' => array('id', 'first_name', 'last_name'))))); $GLOBALS['log']->fatal("_getEntryForContact" . " " . $soap_version_test_opportunityId); + return $result; + } + + public function _setRelationshipForOpportunity() { + + global $soap_version_test_contactId, $soap_version_test_opportunityId; + $this->_login(); + $result = $this->_soapClient->call('set_relationship',array('session'=>$this->_sessionId,'module_name' => 'Opportunities','module_id' => "$soap_version_test_opportunityId", 'link_field_name' => 'contacts','related_ids' =>array("$soap_version_test_contactId"), 'name_value_list' => array(array('name' => 'contact_role', 'value' => 'testrole')), 'delete'=>0)); + return $result; + } // fn + + public function _getRelationshipForOpportunity() { + global $soap_version_test_opportunityId; + $this->_login(); + $result = $this->_soapClient->call('get_relationships', + array( + 'session' => $this->_sessionId, + 'module_name' => 'Opportunities', + 'module_id' => "$soap_version_test_opportunityId", + 'link_field_name' => 'contacts', + 'related_module_query' => '', + 'related_fields' => array('id'), + 'related_module_link_name_to_fields_array' => array(array('name' => 'contacts', 'value' => array('id', 'first_name', 'last_name'))), + 'deleted'=>0, + ) + ); + return $result; + } // fn + + public function _searchByModule() { + $this->_login(); + $result = $this->_soapClient->call('search_by_module', + array( + 'session' => $this->_sessionId, + 'search_string' => 'Sugar', + 'modules' => array('Accounts', 'Contacts', 'Opportunities'), + 'offset' => '0', + 'max_results' => '10') + ); + return $result; + } // fn + + /** + * Create a test user + * + */ + public function _setupTestUser() { + $this->_user = SugarTestUserUtilities::createAnonymousUser(); + $this->_user->status = 'Active'; + $this->_user->is_admin = 1; + $this->_user->save(); + $GLOBALS['current_user'] = $this->_user; + } + + /** + * Remove user created for test + * + */ + public function _tearDownTestUser() { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + } +} +?> diff --git a/tests/service/SOAPAPI3Test.php b/tests/service/SOAPAPI3Test.php new file mode 100755 index 00000000..662ebf41 --- /dev/null +++ b/tests/service/SOAPAPI3Test.php @@ -0,0 +1,410 @@ +_soapClient = new nusoapclient($GLOBALS['sugar_config']['site_url'].'/service/v3/soap.php',false,false,false,false,false,600,600); + $this->_setupTestUser(); + $GLOBALS['app_strings'] = return_application_language($GLOBALS['current_language']); + $GLOBALS['app_list_strings'] = return_app_list_strings_language($GLOBALS['current_language']); + + self::$helperObject = new APIv3Helper(); + } + + /** + * Remove anything that was used during this test + * + */ + public function tearDown() { + global $soap_version_test_accountId, $soap_version_test_opportunityId, $soap_version_test_contactId; + $this->_tearDownTestUser(); + $this->_user = null; + $this->_sessionId = ''; + unset($soap_version_test_accountId); + unset($soap_version_test_opportunityId); + unset($soap_version_test_contactId); + } + + /** + * Ensure we can create a session on the server. + * + */ + public function testCanLogin(){ + $result = $this->_login(); + $this->assertTrue(!empty($result['id']) && $result['id'] != -1, + 'SOAP Session not created. Error ('.$this->_soapClient->faultcode.'): '.$this->_soapClient->faultstring.': '.$this->_soapClient->faultdetail); + } + + public function testSearchByModule() + { + $this->_login(); + + $seedData = self::$helperObject->populateSeedDataForSearchTest($this->_user->id); + + $searchModules = array('Accounts','Contacts','Opportunities'); + $searchString = "UNIT TEST"; + $offSet = 0; + $maxResults = 10; + + $results = $this->_soapClient->call('search_by_module', + array( + 'session' => $this->_sessionId, + 'search' => $searchString, + 'modules' => $searchModules, + 'offset' => $offSet, + 'max' => $maxResults, + 'user' => $this->_user->id) + ); + + $this->assertTrue( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[0]['id'],'Accounts') ); + $this->assertFalse( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[1]['id'],'Accounts') ); + $this->assertTrue( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[2]['id'],'Contacts') ); + $this->assertTrue( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[3]['id'],'Opportunities') ); + $this->assertFalse( self::$helperObject->findBeanIdFromEntryList($results['entry_list'],$seedData[4]['id'],'Opportunities') ); + $GLOBALS['db']->query("DELETE FROM accounts WHERE name like 'UNIT TEST%' "); + $GLOBALS['db']->query("DELETE FROM opportunities WHERE name like 'UNIT TEST%' "); + $GLOBALS['db']->query("DELETE FROM contacts WHERE first_name like 'UNIT TEST%' "); + } + + public function testSearchByModuleWithReturnFields() + { + $this->_login(); + + $seedData = self::$helperObject->populateSeedDataForSearchTest($this->_user->id); + + $returnFields = array('name','id','deleted'); + $searchModules = array('Accounts','Contacts','Opportunities'); + $searchString = "UNIT TEST"; + $offSet = 0; + $maxResults = 10; + + $results = $this->_soapClient->call('search_by_module', + array( + 'session' => $this->_sessionId, + 'search' => $searchString, + 'modules' => $searchModules, + 'offset' => $offSet, + 'max' => $maxResults, + 'user' => $this->_user->id, + 'fields' => $returnFields) + ); + + $this->assertEquals($seedData[0]['fieldValue'], self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[0]['id'],'Accounts', $seedData[0]['fieldName'])); + $this->assertFalse(self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[1]['id'],'Accounts', $seedData[1]['fieldName'])); + $this->assertEquals($seedData[2]['fieldValue'], self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[2]['id'],'Contacts', $seedData[2]['fieldName'])); + $this->assertEquals($seedData[3]['fieldValue'], self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[3]['id'],'Opportunities', $seedData[3]['fieldName'])); + $this->assertFalse(self::$helperObject->findFieldByNameFromEntryList($results['entry_list'],$seedData[4]['id'],'Opportunities', $seedData[4]['fieldName'])); + + $GLOBALS['db']->query("DELETE FROM accounts WHERE name like 'UNIT TEST%' "); + $GLOBALS['db']->query("DELETE FROM opportunities WHERE name like 'UNIT TEST%' "); + $GLOBALS['db']->query("DELETE FROM contacts WHERE first_name like 'UNIT TEST%' "); + } + + public function testGetVardefsMD5() + { + $GLOBALS['reload_vardefs'] = TRUE; + //Test a regular module + $result = $this->_getVardefsMD5('Accounts'); + $a = new Account(); + $soapHelper = new SugarWebServiceUtilv3(); + $actualVardef = $soapHelper->get_return_module_fields($a,'Accounts',''); + $actualMD5 = md5(serialize($actualVardef)); + $this->assertEquals($actualMD5, $result, "Unable to retrieve vardef md5."); + + //Test a fake module + $result = $this->_getVardefsMD5('BadModule'); + $this->assertTrue($result['faultstring'] == 'Module Does Not Exist'); + unset($GLOBALS['reload_vardefs']); + } + + public function testGetUpcomingActivities() + { + $this->_login(); + $expected = $this->_createUpcomingActivities(); //Seed the data. + $results = $this->_soapClient->call('get_upcoming_activities',array('session'=>$this->_sessionId)); + + $this->assertEquals($expected[0] ,$results[0]['id'] , 'Unable to get upcoming activities Error ('.$this->_soapClient->faultcode.'): '.$this->_soapClient->faultstring.': '.$this->_soapClient->faultdetail); + $this->assertEquals($expected[1] ,$results[1]['id'] , 'Unable to get upcoming activities Error ('.$this->_soapClient->faultcode.'): '.$this->_soapClient->faultstring.': '.$this->_soapClient->faultdetail); + + $this->_removeUpcomingActivities(); + } + + public function testGetLastViewed() + { + $testModule = 'Accounts'; + $testModuleID = uniqid(); + + $this->_createTrackerEntry($testModule,$testModuleID); + + $this->_login(); + $results = $this->_soapClient->call('get_last_viewed',array('session'=>$this->_sessionId,'module_names'=> array($testModule) )); + + $found = FALSE; + foreach ($results as $entry) + { + if($entry['item_id'] == $testModuleID) + { + $found = TRUE; + break; + } + } + + $this->assertTrue($found, "Unable to get last viewed modules"); + } + + private function _createTrackerEntry($module, $id,$summaryText = "UNIT TEST SUMMARY") + { + $trackerManager = TrackerManager::getInstance(); + $timeStamp = gmdate($GLOBALS['timedate']->get_db_date_time_format()); + $monitor = $trackerManager->getMonitor('tracker'); + $monitor->setValue('action', 'detail'); + $monitor->setValue('user_id', $this->_user->id); + $monitor->setValue('module_name', $module); + $monitor->setValue('date_modified', $timeStamp); + $monitor->setValue('visible', true); + $monitor->setValue('item_id', $id); + $monitor->setValue('item_summary', $summaryText); + $trackerManager->saveMonitor($monitor, true, true); + } + + + /** + * Get Module Layout functions not exposed to soap service, make sure they are not available. + * + */ + public function testGetModuleLayoutMD5() + { + $result = $this->_getModuleLayoutMD5(); + $this->assertContains('Client',$result['faultcode']); + + } + + public function testSetEntriesForAccount() { + $result = $this->_setEntriesForAccount(); + $this->assertTrue(!empty($result['ids']) && $result['ids'][0] != -1, + 'Can not create new account using testSetEntriesForAccount. Error ('.$this->_soapClient->faultcode.'): '.$this->_soapClient->faultstring.': '.$this->_soapClient->faultdetail); + } // fn + + /********************************** + * HELPER PUBLIC FUNCTIONS + **********************************/ + private function _removeUpcomingActivities() + { + $GLOBALS['db']->query("DELETE FROM calls where name = 'UNIT TEST'"); + $GLOBALS['db']->query("DELETE FROM tasks where name = 'UNIT TEST'"); + } + + private function _createUpcomingActivities() + { + $GLOBALS['current_user']->setPreference('datef','Y-m-d') ; + $GLOBALS['current_user']->setPreference('timef','H:i') ; + + $date1 = $GLOBALS['timedate']->to_display_date_time(gmdate("Y-m-d H:i:s", (gmmktime() + (3600 * 24 * 2) ) ),true,true, $GLOBALS['current_user']) ; //Two days from today + $date2 = $GLOBALS['timedate']->to_display_date_time(gmdate("Y-m-d H:i:s", (gmmktime() + (3600 * 24 * 4) ) ),true,true, $GLOBALS['current_user']) ; //Two days from today + + $callID = uniqid(); + $c = new Call(); + $c->id = $callID; + $c->new_with_id = TRUE; + $c->status = 'Not Planned'; + $c->date_start = $date1; + $c->name = "UNIT TEST"; + $c->assigned_user_id = $this->_user->id; + $c->save(FALSE); + + $callID = uniqid(); + $c = new Call(); + $c->id = $callID; + $c->new_with_id = TRUE; + $c->status = 'Planned'; + $c->date_start = $date1; + $c->name = "UNIT TEST"; + $c->assigned_user_id = $this->_user->id; + $c->save(FALSE); + + $taskID = uniqid(); + $t = new Task(); + $t->id = $taskID; + $t->new_with_id = TRUE; + $t->status = 'Not Started'; + $t->date_due = $date2; + $t->name = "UNIT TEST"; + $t->assigned_user_id = $this->_user->id; + $t->save(FALSE); + + return array($callID, $taskID); + } + + /** + * Attempt to login to the soap server + * + * @return $set_entry_result - this should contain an id and error. The id corresponds + * to the session_id. + */ + public function _login(){ + global $current_user; + $result = $this->_soapClient->call('login', + array('user_auth' => + array('user_name' => $current_user->user_name, + 'password' => $current_user->user_hash, + 'version' => '.01'), + 'application_name' => 'SoapTest') + ); + + $this->_sessionId = $result['id']; + return $result; + } + + public function _getVardefsMD5($module) + { + $this->_login(); + $result = $this->_soapClient->call('get_module_fields_md5',array('session'=>$this->_sessionId,'module'=> array($module) )); + if(isset($result[0])) + return $result[0]; + else + return $result; + } + + public function _getModuleLayoutMD5() + { + $this->_login(); + $result = $this->_soapClient->call('get_module_layout_md5', + array('session'=>$this->_sessionId,'module_names'=> array('Accounts'),'types' => array('default'),'views' => array('list'))); + if(isset($result['md5'])) + return $result['md5']; + else + return $result; + } + + public function _setEntryForContact() { + $this->_login(); + global $timedate; + $current_date = $timedate->convert_to_gmt_datetime('now'); + $time = mt_rand(); + $first_name = 'SugarContactFirst' . $time; + $last_name = 'SugarContactLast'; + $email1 = 'contact@sugar.com'; + $result = $this->_soapClient->call('set_entry',array('session'=>$this->_sessionId,'module_name'=>'Contacts', 'name_value_list'=>array(array('name'=>'last_name' , 'value'=>"$last_name"), array('name'=>'first_name' , 'value'=>"$first_name"), array('name'=>'do_not_call' , 'value'=>"1"), array('name'=>'birthdate' , 'value'=>"$current_date"), array('name'=>'lead_source' , 'value'=>"Cold Call"), array('name'=>'email1' , 'value'=>"$email1")))); + SugarTestContactUtilities::setCreatedContact(array($this->_contactId)); + return $result; + } // fn + + public function _getEntryForContact() { + global $soap_version_test_contactId; + $this->_login(); + $result = $this->_soapClient->call('get_entry',array('session'=>$this->_sessionId,'module_name'=>'Contacts','id'=>$soap_version_test_contactId,'select_fields'=>array('last_name', 'first_name', 'do_not_call', 'lead_source'), 'link_name_to_fields_array' => array(array('name' => 'email_addresses', 'value' => array('id', 'email_address', 'opt_out', 'primary_address'))))); + $GLOBALS['log']->fatal("_getEntryForContact" . " " . $soap_version_test_contactId); + return $result; + } + + public function _setEntriesForAccount() { + global $soap_version_test_accountId; + $this->_login(); + global $timedate; + $current_date = $timedate->convert_to_gmt_datetime('now'); + $time = mt_rand(); + $name = 'SugarAccount' . $time; + $email1 = 'account@'. $time. 'sugar.com'; + $result = $this->_soapClient->call('set_entries',array('session'=>$this->_sessionId,'module_name'=>'Accounts', 'name_value_lists'=>array(array(array('name'=>'name' , 'value'=>"$name"), array('name'=>'email1' , 'value'=>"$email1"))))); + $soap_version_test_accountId = $result['ids'][0]; + $GLOBALS['log']->fatal("_setEntriesForAccount id = " . $soap_version_test_accountId); + SugarTestAccountUtilities::setCreatedAccount(array($soap_version_test_accountId)); + return $result; + } // fn + + public function _setEntryForOpportunity() { + global $soap_version_test_accountId, $soap_version_test_opportunityId; + $this->_login(); + global $timedate; + $date_closed = $timedate->convert_to_gmt_datetime(strtotime('+1 week')); + $time = mt_rand(); + $name = 'SugarOpportunity' . $time; + $account_id = $soap_version_test_accountId; + $sales_stage = 'Prospecting'; + $probability = 10; + $amount = 1000; + $GLOBALS['log']->fatal("_setEntryForOpportunity id = " . $soap_version_test_accountId); + $result = $this->_soapClient->call('set_entry',array('session'=>$this->_sessionId,'module_name'=>'Opportunities', 'name_value_lists'=>array(array('name'=>'name' , 'value'=>"$name"), array('name'=>'amount' , 'value'=>"$amount"), array('name'=>'probability' , 'value'=>"$probability"), array('name'=>'sales_stage' , 'value'=>"$sales_stage"), array('name'=>'account_id' , 'value'=>"$account_id")))); + $soap_version_test_opportunityId = $result['id']; + return $result; + } // fn + + public function _setRelationshipForOpportunity() { + global $soap_version_test_contactId, $soap_version_test_opportunityId; + $this->_login(); + $result = $this->_soapClient->call('set_relationship',array('session'=>$this->_sessionId,'module_name' => 'Opportunities','module_id' => "$soap_version_test_opportunityId", 'link_field_name' => 'contacts','related_ids' =>array("$soap_version_test_contactId"), 'name_value_list' => array(array('name' => 'contact_role', 'value' => 'testrole')))); + return $result; + } // fn + + public function _getRelationshipForOpportunity() { + global $soap_version_test_opportunityId; + $this->_login(); + $result = $this->_soapClient->call('get_relationships', + array( + 'session' => $this->_sessionId, + 'module_name' => 'Opportunities', + 'module_id' => "$soap_version_test_opportunityId", + 'link_field_name' => 'contacts', + 'related_module_query' => '', + 'related_fields' => array('id'), + 'related_module_link_name_to_fields_array' => array(array('name' => 'email_addresses', 'value' => array('id', 'email_address', 'opt_out', 'primary_address')))) + ); + return $result; + } // fn + + public function _searchByModule() { + $this->_login(); + $result = $this->_soapClient->call('search_by_module', + array( + 'session' => $this->_sessionId, + 'search_string' => 'Sugar', + 'modules' => array('Accounts', 'Contacts', 'Opportunities'), + 'offset' => '0', + 'max_results' => '10') + ); + + return $result; + } // fn + + /** + * Create a test user + * + */ + public function _setupTestUser() { + $this->_user = SugarTestUserUtilities::createAnonymousUser(); + $this->_user->status = 'Active'; + $this->_user->is_admin = 1; + $this->_user->save(); + $GLOBALS['current_user'] = $this->_user; + } + + /** + * Remove user created for test + * + */ + public function _tearDownTestUser() { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + } +} +?> diff --git a/tests/service/SOAPTestCase.php b/tests/service/SOAPTestCase.php new file mode 100755 index 00000000..e48cfa6f --- /dev/null +++ b/tests/service/SOAPTestCase.php @@ -0,0 +1,79 @@ +_soapClient = new nusoapclient($this->_soapURL,false,false,false,false,false,600,600); + $this->_setupTestUser(); + parent::setUp(); + } + + /** + * Remove anything that was used during this test + * + */ + public function tearDown() + { + $this->_tearDownTestUser(); + $this->_user = null; + $this->_sessionId = ''; + + unset($GLOBALS['beanList']); + unset($GLOBALS['beanFiles']); + parent::tearDown(); + } + + protected function _login() + { + $result = $this->_soapClient->call('login', + array('user_auth' => + array('user_name' => $this->_user->user_name, + 'password' => $this->_user->user_hash, + 'version' => '.01'), + 'application_name' => 'SoapTest') + ); + $this->_sessionId = $result['id']; + return $result; + } + + /** + * Create a test user + * + */ + public function _setupTestUser() { + $this->_user = SugarTestUserUtilities::createAnonymousUser(); + $this->_user->status = 'Active'; + $this->_user->is_admin = 1; + $this->_user->save(); + $GLOBALS['current_user'] = $this->_user; + } + + /** + * Remove user created for test + * + */ + public function _tearDownTestUser() { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + unset($GLOBALS['current_user']); + } + +} + diff --git a/tests/tests/SugarTestImportUtilitiesTest.php b/tests/tests/SugarTestImportUtilitiesTest.php new file mode 100755 index 00000000..dceb2127 --- /dev/null +++ b/tests/tests/SugarTestImportUtilitiesTest.php @@ -0,0 +1,81 @@ +assertTrue(is_file($filename)); + $fp = fopen($filename,"r"); + $i = 0; + $buffer = ''; + while (!feof($fp)) { + $columns = $buffer; + $buffer = fgetcsv($fp, 4096); + if ( $buffer !== false ) + $i++; + } + fclose($fp); + $this->assertEquals($i,2000); + $this->assertEquals(count($columns),3); + } + + public function testCanCreateFileAndSpecifyLines() + { + $filename = SugarTestImportUtilities::createFile(1); + + $this->assertTrue(is_file($filename)); + $fp = fopen($filename,"r"); + $i = 0; + $buffer = ''; + while (!feof($fp)) { + $columns = $buffer; + $buffer = fgetcsv($fp, 4096); + if ( $buffer !== false ) + $i++; + } + fclose($fp); + $this->assertEquals($i,1); + $this->assertEquals(count($columns),3); + } + + public function testCanCreateFileAndSpecifyLinesAndColumns() + { + $filename = SugarTestImportUtilities::createFile(2,5); + + $this->assertTrue(is_file($filename)); + $fp = fopen($filename,"r"); + $i = 0; + $buffer = ''; + while (!feof($fp)) { + $columns = $buffer; + $buffer = fgetcsv($fp, 4096); + if ( $buffer !== false ) + $i++; + } + fclose($fp); + $this->assertEquals($i,2); + $this->assertEquals(count($columns),5); + } + + public function testCanRemoveAllCreatedFiles() + { + $filesCreated = array(); + + for ($i = 0; $i < 5; $i++) + $filesCreated[] = SugarTestImportUtilities::createFile(); + $filesCreated[] = $filesCreated[4].'-0'; + + SugarTestImportUtilities::removeAllCreatedFiles(); + + foreach ( $filesCreated as $filename ) + $this->assertFalse(is_file($filename)); + } +} + diff --git a/tests/tests/SugarTestLangPackCreatorTest.php b/tests/tests/SugarTestLangPackCreatorTest.php new file mode 100755 index 00000000..5233f6d8 --- /dev/null +++ b/tests/tests/SugarTestLangPackCreatorTest.php @@ -0,0 +1,47 @@ +setAppString('NTC_WELCOME','stringname'); + $langpack->setAppListString('checkbox_dom',array(''=>'','1'=>'Yep','2'=>'Nada')); + $langpack->setModString('LBL_MODULE_NAME','stringname','Contacts'); + $langpack->save(); + + $app_strings = return_application_language($GLOBALS['current_language']); + $app_list_strings = return_app_list_strings_language($GLOBALS['current_language']); + $mod_strings = return_module_language($GLOBALS['current_language'], 'Contacts'); + + $this->assertEquals($app_strings['NTC_WELCOME'],'stringname'); + + $this->assertEquals($app_list_strings['checkbox_dom'], + array(''=>'','1'=>'Yep','2'=>'Nada')); + + $this->assertEquals($mod_strings['LBL_MODULE_NAME'],'stringname'); + } + + public function testUndoStringsChangesMade() + { + $langpack = new SugarTestLangPackCreator(); + + $app_strings = return_application_language($GLOBALS['current_language']); + $prevString = $app_strings['NTC_WELCOME']; + + $langpack->setAppString('NTC_WELCOME','stringname'); + $langpack->save(); + + $app_strings = return_application_language($GLOBALS['current_language']); + + $this->assertEquals($app_strings['NTC_WELCOME'],'stringname'); + + // call the destructor directly to undo our changes + unset($langpack); + + $app_strings = return_application_language($GLOBALS['current_language']); + + $this->assertEquals($app_strings['NTC_WELCOME'],$prevString); + } +} diff --git a/tests/tests/SugarTestThemeUtilitiesTest.php b/tests/tests/SugarTestThemeUtilitiesTest.php new file mode 100755 index 00000000..54ba0bbc --- /dev/null +++ b/tests/tests/SugarTestThemeUtilitiesTest.php @@ -0,0 +1,61 @@ +assertTrue(is_dir("themes/$themename")); + $this->assertTrue(is_file("themes/$themename/themedef.php")); + } + + public function testCanCreateAnAnonymousCustomTheme() + { + $themename = SugarTestThemeUtilities::createAnonymousCustomTheme(); + + $this->assertTrue(is_dir("custom/themes/$themename")); + $this->assertTrue(is_file("custom/themes/$themename/themedef.php")); + + $themename = 'MyCustomTestTheme'.date("YmdHis"); + SugarTestThemeUtilities::createAnonymousCustomTheme($themename); + + $this->assertTrue(is_dir("custom/themes/$themename")); + $this->assertTrue(is_file("custom/themes/$themename/themedef.php")); + } + + public function testCanCreateAnAnonymousChildTheme() + { + $themename = SugarTestThemeUtilities::createAnonymousTheme(); + $childtheme = SugarTestThemeUtilities::createAnonymousChildTheme($themename); + + $this->assertTrue(is_dir("themes/$childtheme")); + $this->assertTrue(is_file("themes/$childtheme/themedef.php")); + + $themedef = array(); + include("themes/$childtheme/themedef.php"); + + $this->assertEquals($themedef['parentTheme'],$themename); + } + + public function testCanTearDownAllCreatedAnonymousThemes() + { + $themesCreated = array(); + + for ($i = 0; $i < 5; $i++) + $themesCreated[] = SugarTestThemeUtilities::createAnonymousTheme(); + + SugarTestThemeUtilities::removeAllCreatedAnonymousThemes(); + + foreach ( $themesCreated as $themename ) + $this->assertFalse(is_dir("themes/$themename")); + } +} + diff --git a/tests/tests/SugarTestUserUtilitiesTest.php b/tests/tests/SugarTestUserUtilitiesTest.php new file mode 100755 index 00000000..5a8a98b1 --- /dev/null +++ b/tests/tests/SugarTestUserUtilitiesTest.php @@ -0,0 +1,62 @@ +_before_snapshot = $this->_takeUserDBSnapshot(); + } + + public function tearDown() + { + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + } + + public function _takeUserDBSnapshot() + { + $snapshot = array(); + $query = 'SELECT * FROM users'; + $result = $GLOBALS['db']->query($query); + while ($row = $GLOBALS['db']->fetchByAssoc($result)) { + $snapshot[] = $row; + } + return $snapshot; + } + + + public function testCanCreateAnAnonymousUser() + { + $user = SugarTestUserUtilities::createAnonymousUser(); + + $this->assertType('User', $user); + + $after_snapshot = $this->_takeUserDBSnapshot(); + $this->assertNotEquals($this->_before_snapshot, $after_snapshot, + "Simply insure that something was added"); + } + + public function testAnonymousUserHasARandomUserName() + { + $first_user = SugarTestUserUtilities::createAnonymousUser(); + $this->assertTrue(!empty($first_user->user_name), 'team name should not be empty'); + + $second_user = SugarTestUserUtilities::createAnonymousUser(); + $this->assertNotEquals($first_user->user_name, $second_user->user_name, + 'each user should have a unique name property'); + } + + public function testCanTearDownAllCreatedAnonymousUsers() + { + for ($i = 0; $i < 5; $i++) { + SugarTestUserUtilities::createAnonymousUser(); + } + SugarTestUserUtilities::removeAllCreatedAnonymousUsers(); + + $this->assertEquals($this->_before_snapshot, $this->_takeUserDBSnapshot(), + 'SugarTest_UserUtilities::removeAllCreatedAnonymousUsers() should have removed the users it added'); + } +} + -- 2.42.0