PageRenderTime 39ms CodeModel.GetById 5ms RepoModel.GetById 0ms app.codeStats 0ms

/src/concordion/impl/tests/java_test.py

http://pyconcordion.googlecode.com/
Python | 393 lines | 389 code | 4 blank | 0 comment | 13 complexity | 719952192b51e5accce7517f3a919139 MD5 | raw file
Possible License(s): LGPL-2.1
  1. import unittest, os, shutil, pmock
  2. from concordion.impl.java import JavaClassGenerator, Classpath, JavaFileCompiler, JavaTestLauncher
  3. class JavaClassGeneratorTest(unittest.TestCase):
  4. def test_can_generate_for_an_empty_list_of_classes(self):
  5. "Class Generator - Can be run on an empty file list"
  6. generator = JavaClassGenerator(".")
  7. self.assertEquals([], generator.run([]))
  8. def test_can_generate_for_a_single_simple_python_file(self):
  9. "Class Generator - Can be run on a single simple python file"
  10. _createFile("MyPythonFile.py", """
  11. class MyPythonFile:
  12. pass
  13. """)
  14. result = JavaClassGenerator(".").run(["MyPythonFile.py"])
  15. self.assertEquals(1, len(result))
  16. self.assertEquals("MyPythonFile.java", result[0])
  17. self.assertEquals("""
  18. import java.net.*;
  19. import org.apache.ws.commons.util.NamespaceContextImpl;
  20. import org.apache.xmlrpc.common.TypeFactoryImpl;
  21. import org.apache.xmlrpc.common.XmlRpcController;
  22. import org.apache.xmlrpc.common.XmlRpcStreamConfig;
  23. import org.apache.xmlrpc.parser.NullParser;
  24. import org.apache.xmlrpc.parser.TypeParser;
  25. import org.apache.xmlrpc.serializer.NullSerializer;
  26. import org.apache.xmlrpc.client.XmlRpcClient;
  27. import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
  28. import org.apache.xmlrpc.XmlRpcException;
  29. import org.concordion.integration.junit3.ConcordionTestCase;
  30. import org.concordion.api.ExpectedToPass;
  31. import java.lang.reflect.Array;
  32. import java.lang.System;
  33. import java.util.*;
  34. @ExpectedToPass
  35. public class MyPythonFile extends ConcordionTestCase{
  36. XmlRpcClient client = null;
  37. public MyPythonFile() throws MalformedURLException{
  38. XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
  39. config.setServerURL(new URL("http://localhost:1337/"));
  40. this.client = new XmlRpcClient();
  41. this.client.setTypeFactory(new MyTypeFactory(this.client));
  42. this.client.setConfig(config);
  43. }
  44. class MyTypeFactory extends TypeFactoryImpl {
  45. public MyTypeFactory(XmlRpcController pController) {
  46. super(pController);
  47. }
  48. @Override
  49. public TypeParser getParser(XmlRpcStreamConfig pConfig,
  50. NamespaceContextImpl pContext, String pURI, String pLocalName) {
  51. if ("".equals(pURI) && NullSerializer.NIL_TAG.equals(pLocalName)) {
  52. return new NullParser();
  53. } else {
  54. return super.getParser(pConfig, pContext, pURI, pLocalName);
  55. }
  56. }
  57. }
  58. }""", file(result[0]).read())
  59. os.remove("MyPythonFile.py")
  60. os.remove("MyPythonFile.java")
  61. def test_can_generate_java_method_for_an_argument_less_python_method(self):
  62. "Class Generator - Can generate Java method for an argument less python method"
  63. _createFile("MyPythonFile2.py", """
  64. class MyPythonFile2:
  65. def do_plop(self):
  66. pass
  67. """)
  68. JavaClassGenerator(".").run(["MyPythonFile2.py"])
  69. self.assertTrue(file("MyPythonFile2.java").read().find("""
  70. public Object do_plop() throws XmlRpcException{
  71. Object result = this.client.execute("MyPythonFile2_do_plop", new Object[]{});
  72. if(result != null && result.getClass().isArray()){
  73. List<Object> list = new ArrayList<Object>();
  74. for(int i = 0; i < Array.getLength(result); i++){
  75. list.add(Array.get(result, i));
  76. }
  77. return list;
  78. }
  79. return result;
  80. }""") >= 0)
  81. os.remove("MyPythonFile2.py")
  82. os.remove("MyPythonFile2.java")
  83. # This test is a bug fix !
  84. def test_can_generate_correct_java_even_if_method_contains_variables(self):
  85. "Class Generator - Can generate Java method even if python contains local variables"
  86. _createFile("MyPythonFile2.py", """
  87. class MyPythonFile2:
  88. def do_plop(self):
  89. local_variable = "polop"
  90. """)
  91. JavaClassGenerator(".").run(["MyPythonFile2.py"])
  92. self.assertTrue(file("MyPythonFile2.java").read().find("""
  93. public Object do_plop() throws XmlRpcException{
  94. Object result = this.client.execute("MyPythonFile2_do_plop", new Object[]{});
  95. """) >= 0)
  96. os.remove("MyPythonFile2.py")
  97. os.remove("MyPythonFile2.java")
  98. def test_can_generate_java_method_for_a_python_method_with_arguments(self):
  99. "Class Generator - Can generate Java method for a python method with arguments"
  100. _createFile("MyPythonFile3.py", """
  101. class MyPythonFile3:
  102. def do_plop(self, polop, pilip):
  103. pass
  104. """)
  105. JavaClassGenerator(".").run(["MyPythonFile3.py"])
  106. self.assertTrue(file("MyPythonFile3.java").read().find("""
  107. public Object do_plop(String polop, String pilip) throws XmlRpcException{
  108. Object result = this.client.execute("MyPythonFile3_do_plop", new Object[]{polop, pilip});
  109. """) >= 0)
  110. os.remove("MyPythonFile3.py")
  111. os.remove("MyPythonFile3.java")
  112. def test_can_generate_for_a_simple_python_file_in_another_directory(self):
  113. "Class Generator - Can generate even for a file that is not in the same directory"
  114. if not os.path.exists("tmp"):
  115. os.mkdir("tmp")
  116. _createFile("tmp/MyPythonFile.py", """
  117. class MyPythonFile:
  118. pass
  119. """)
  120. result = JavaClassGenerator("tmp/").run(["tmp/MyPythonFile.py"])
  121. self.assertEquals(1, len(result))
  122. self.assertEquals("tmp/MyPythonFile.java", result[0])
  123. shutil.rmtree("tmp")
  124. def test_can_generate_annotation_expected_to_fail(self):
  125. "Class Generator - Can generate annotation ExpectedToFail"
  126. _createFile("MyPythonFile.py", """
  127. from concordion.annotation import ExpectedToFail
  128. @ExpectedToFail
  129. class MyPythonFile:
  130. pass
  131. """)
  132. result = JavaClassGenerator(".").run(["MyPythonFile.py"])
  133. self.assertTrue(file("MyPythonFile.java").read().find("""
  134. @ExpectedToFail
  135. """) >= 0)
  136. self.assertTrue(file("MyPythonFile.java").read().find("""
  137. import org.concordion.api.ExpectedToFail;
  138. """) >= 0)
  139. def test_can_generate_annotation_unimplemented(self):
  140. "Class Generator - Can generate annotation Unimplemented"
  141. _createFile("MyPythonFile.py", """
  142. from concordion.annotation import Unimplemented
  143. @Unimplemented
  144. class MyPythonFile:
  145. pass
  146. """)
  147. result = JavaClassGenerator(".").run(["MyPythonFile.py"])
  148. self.assertTrue(file("MyPythonFile.java").read().find("""
  149. @Unimplemented
  150. """) >= 0)
  151. self.assertTrue(file("MyPythonFile.java").read().find("""
  152. import org.concordion.api.Unimplemented;
  153. """) >= 0)
  154. def test_can_generate_with_package_declaration(self):
  155. "Class Generator - Can generate package declaration"
  156. if not os.path.exists("tmp"):
  157. os.mkdir("tmp")
  158. if not os.path.exists("tmp/polop"):
  159. os.mkdir("tmp/polop")
  160. _createFile("tmp/polop/MyPythonFile.py", """
  161. class MyPythonFile:
  162. pass
  163. """)
  164. result = JavaClassGenerator(".").run(["tmp/polop/MyPythonFile.py"])
  165. self.assertEquals(1, len(result))
  166. self.assertEquals("tmp/polop/MyPythonFile.java", result[0])
  167. self.assertTrue(file("tmp/polop/MyPythonFile.java").read().find("""
  168. package tmp.polop;
  169. """) >= 0)
  170. shutil.rmtree("tmp")
  171. def test_can_generate_when_python_class_got_attributes(self):
  172. "Class Generator - Can generate when python class got attributes"
  173. _createFile("MyPythonFile.py", """
  174. class MyPythonFile:
  175. attribute = []
  176. def polop(self):
  177. pass
  178. """)
  179. result = JavaClassGenerator(".").run(["MyPythonFile.py"])
  180. self.assertEquals(1, len(result))
  181. self.assertEquals("MyPythonFile.java", result[0])
  182. os.remove("MyPythonFile.py")
  183. os.remove("MyPythonFile.java")
  184. def test_can_generate_java_method_for_setUp_and_tearDown(self):
  185. "Class Generator - Can generate for setUp and tearDown"
  186. _createFile("MyPythonFile2.py", """
  187. class MyPythonFile2:
  188. def setUp(self):
  189. pass
  190. def tearDown(self):
  191. pass
  192. """)
  193. JavaClassGenerator(".").run(["MyPythonFile2.py"])
  194. self.assertTrue(file("MyPythonFile2.java").read().find("""
  195. public void setUp() throws XmlRpcException{
  196. this.client.execute("MyPythonFile2_setUp", new Object[]{});
  197. }""") >= 0)
  198. self.assertTrue(file("MyPythonFile2.java").read().find("""
  199. public void tearDown() throws XmlRpcException{
  200. this.client.execute("MyPythonFile2_tearDown", new Object[]{});
  201. }""") >= 0)
  202. os.remove("MyPythonFile2.py")
  203. os.remove("MyPythonFile2.java")
  204. def test_can_generate_extensions_inclusion(self):
  205. "Class Generator - Can generate extensions inclusion based on configuration"
  206. _createFile("MyPythonFile2.py", """
  207. class MyPythonFile2:
  208. def polop(self):
  209. pass
  210. """)
  211. configuration = {"extensions":"This is the extension value"}
  212. JavaClassGenerator(".", configuration=configuration).run(["MyPythonFile2.py"])
  213. self.assertTrue(file("MyPythonFile2.java").read().find("""
  214. System.setProperty("concordion.extensions", "This is the extension value");
  215. """) >= 0)
  216. os.remove("MyPythonFile2.py")
  217. os.remove("MyPythonFile2.java")
  218. def test_can_generate_testsuite(self):
  219. "Class Generator - Can generate test suite"
  220. if not os.path.exists("tmp"):
  221. os.mkdir("tmp")
  222. expected = """import junit.framework.Test;
  223. import junit.framework.TestSuite;
  224. public class Suite {
  225. public static Test suite(){
  226. TestSuite suite = new TestSuite();
  227. suite.setName("pyConcordion test suite");
  228. suite.addTest(new TestSuite(polop.MyPythonFile.class));
  229. suite.addTest(new TestSuite(polop.OtherPythonFile.class));
  230. return suite;
  231. }
  232. }
  233. """
  234. result = JavaClassGenerator("tmp").suite(["tmp/polop/MyPythonFile.java", "tmp/polop/OtherPythonFile.java"])
  235. self.assertEquals("tmp/Suite.java", result)
  236. self.assertEquals(expected, file(result).read())
  237. shutil.rmtree("tmp")
  238. class ClasspathTest(unittest.TestCase):
  239. def setUp(self):
  240. if not os.path.exists("lib"):
  241. os.mkdir("lib")
  242. def tearDown(self):
  243. shutil.rmtree("lib");
  244. def testEmptyClassPath(self):
  245. "Classpath - can create empty classpath"
  246. self.assertEquals('""', Classpath("lib").getClasspath())
  247. def testCanAddADirectoryToAnEmptyClasspath(self):
  248. "Classpath - can add a directory to empty classpath"
  249. classpath = Classpath("lib")
  250. classpath.addDirectory("/tmp")
  251. self.assertEquals('"/tmp"', classpath.getClasspath())
  252. def testCanRemoveADirectory(self):
  253. "Classpath - can remove a directory"
  254. classpath = Classpath("lib")
  255. classpath.addDirectory("/tmp")
  256. classpath.removeDirectory("/tmp")
  257. self.assertEquals('""', classpath.getClasspath())
  258. def testClasspathWithOneJar(self):
  259. "Classpath - can create classpath with one jar"
  260. path = _createFile(os.path.join("lib", "test.jar"), "polop")
  261. self.assertEquals('"' + path + '"', Classpath("lib").getClasspath())
  262. def testClasspathWithManyJar(self):
  263. "Classpath - can create classpath with many jars"
  264. path = _createFile(os.path.join("lib", "test.jar"), "polop")
  265. path2 = _createFile(os.path.join("lib", "test2.jar"), "polop aussi")
  266. self.assertEquals('"' + path + ":" + path2 + '"', Classpath("lib").getClasspath())
  267. def testClasspathWithManyDirectoriesAdded(self):
  268. "Classpath - can add many directories to a classpath"
  269. path = _createFile(os.path.join("lib", "test.jar"), "polop")
  270. path2 = _createFile(os.path.join("lib", "test2.jar"), "polop aussi")
  271. classpath = Classpath("lib")
  272. classpath.addDirectories(["lib", "/tmp"])
  273. self.assertEquals('"' + path + ":" + path2 + ":lib:/tmp" + '"', classpath.getClasspath())
  274. class JavaFileCompilerTest(unittest.TestCase):
  275. def testCanCompile(self):
  276. "JavaFileCompiler - can compile files"
  277. executor = pmock.Mock()
  278. config = pmock.Mock()
  279. classpath = pmock.Mock()
  280. config.expects(pmock.once()).get(pmock.eq("javac_command")).will(pmock.return_value("myJavac"))
  281. classpath.expects(pmock.once()).getClasspath().will(pmock.return_value("myclasspath"))
  282. executor.expects(pmock.once()).run(pmock.eq("myJavac -cp myclasspath polop/MyClass.java a/pif.java")).will(pmock.return_value(0))
  283. result = JavaFileCompiler(config, classpath, executor).compile(["polop/MyClass.java", "a/pif.java"])
  284. self.assertEquals(["polop/MyClass.class", "a/pif.class"], result)
  285. def testRaisesExceptionInCaseCompilationFails(self):
  286. "JavaFileCompiler - raises exception in case compilation fails"
  287. executor = pmock.Mock()
  288. config = pmock.Mock()
  289. classpath = pmock.Mock()
  290. config.expects(pmock.once()).method("get").will(pmock.return_value(""))
  291. classpath.expects(pmock.once()).getClasspath().will(pmock.return_value("myclasspath"))
  292. executor.expects(pmock.once()).method("run").will(pmock.return_value(1))
  293. try:
  294. result = JavaFileCompiler(config, classpath, executor).compile(["polop/MyClass.java"])
  295. self.fail("Should have raised an exception")
  296. except Exception, e:
  297. self.assertEquals("Sorry, an exception occured in the compilation process", str(e))
  298. class JavaTestLauncherTest(unittest.TestCase):
  299. def testCanLaunchAndReturnOK(self):
  300. "JavaTestLauncher - can launch a file and returns OK if executor returns OK"
  301. executor = pmock.Mock()
  302. config = pmock.Mock()
  303. classpath = pmock.Mock()
  304. config.expects(pmock.once()).get(pmock.eq("java_command")).will(pmock.return_value("myJava"))
  305. config.expects(pmock.once()).get(pmock.eq("output_folder")).will(pmock.return_value("myOutput"))
  306. classpath.expects(pmock.once()).getClasspath().will(pmock.return_value("myclasspath"))
  307. classpath.expects(pmock.once()).addDirectory(pmock.eq("."))
  308. classpath.expects(pmock.once()).removeDirectory(pmock.eq("."))
  309. executor.expects(pmock.once()).run(pmock.eq("myJava -Dconcordion.output.dir=myOutput -cp myclasspath junit.textui.TestRunner polop.MyClass"), pmock.eq(True)).will(pmock.return_value(0))
  310. result = JavaTestLauncher(config, classpath, executor, ".").launch("polop/MyClass.class")
  311. self.assertEquals(0, result)
  312. def testAddsAndRemovesDirectoriesFromClasspath(self):
  313. "JavaTestLauncher - when launching a file it adds the directory to the classpath and removes it after"
  314. mock = pmock.Mock()
  315. mock.expects(pmock.once()).get(pmock.eq("java_command")).will(pmock.return_value("myJava"))
  316. mock.expects(pmock.once()).get(pmock.eq("output_folder")).will(pmock.return_value("myOutput"))
  317. mock.expects(pmock.once()).addDirectory(pmock.eq(".")).id("add")
  318. mock.expects(pmock.once()).getClasspath().will(pmock.return_value("myclasspath;.")).after("add").id("getPath")
  319. mock.expects(pmock.once()).run(pmock.eq("myJava -Dconcordion.output.dir=myOutput -cp myclasspath;. junit.textui.TestRunner polop.MyClass"), pmock.eq(True)) \
  320. .will(pmock.return_value(0)).id("exec").after("getPath")
  321. mock.expects(pmock.once()).removeDirectory(pmock.eq(".")).after("exec")
  322. JavaTestLauncher(mock, mock, mock, ".").launch("polop/MyClass.class")
  323. def testCanLaunchAndReturnFailure(self):
  324. "JavaTestLauncher - can launch a file and return a non zero code in case of failure"
  325. executor = pmock.Mock()
  326. config = pmock.Mock()
  327. classpath = pmock.Mock()
  328. config.expects(pmock.once()).get(pmock.eq("java_command")).will(pmock.return_value(""))
  329. config.expects(pmock.once()).get(pmock.eq("output_folder")).will(pmock.return_value(""))
  330. classpath.expects(pmock.once()).getClasspath().will(pmock.return_value(""))
  331. classpath.expects(pmock.once()).addDirectory(pmock.eq(""))
  332. classpath.expects(pmock.once()).removeDirectory(pmock.eq(""))
  333. executor.expects(pmock.once()).method("run").will(pmock.return_value(1))
  334. result = JavaTestLauncher(config, classpath, executor, "").launch("")
  335. self.assertEquals(1, result)
  336. def _createFile(name, content):
  337. file(name, "w").write(content)
  338. return os.path.abspath(name);