Python unitest doesn't run test functions from PythonAnywhere - python

I'm having a problem with unittest testing, code and results below.
I try to run my test from the PythonAnywhere IDE, and it says that 0 test has been made.
I tested the code with prints to find out where things went wrong and I found out that interpreter doesn't even go into the function to see the test.
I know the test names should start with "test_", which they do.
Any other idea?
I am working on pythonAnywhere if it's matter somehow.
My code:
import unittest
import signUpForm
class Test_signUp(unittest.TestCase):
print ("i got to here")
def test_Utility(self):
print ("but never here")
# test all utlity functions in the sign up form. and delete the changes afterward
#check system addition and manipulation
self.assertEqual(addSystem ("dungeons" , 8000) , "added dungeons to systems list")
if __name__ == '__main__':
unittest.main(exit = False)
When I run this I get:
i got to here
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
>>>

That looks like a bug in the IDE in PythonAnywhere -- the easiest workaround would be to close the console in the editor (using exit()), then refresh the page, and start a new console using the "Bash console here" button that will appear where the old console was. Then you can use the command that #jfaccioni suggested in the comments to your question:
python3 -m unittest code.py
...but have your test results on the same browser tab as your editor.

Related

Function recall working in other IDEs but not VS Code

I wrote some very simple code:
def yo():
text = "hi there"
print(text)
print(text)
yo()
I ran this in Spyder and online compilers without error. Obviously it spits out:
hi there
hi there
But when I run this in VS Code terminal using the "Run Python file in terminal" play button I get
"SyntaxError: invalid syntax"
for line 1 (the def line).
When I type yo() into the terminal itself, I get the expected output of:
hi there
hi there
Why is do I get a different result from these? I executed other simple bits of Python in VS Code using the "play" button without issue. It goes without saying that I have the python extension and interpreter installed.
UPDATE: I restarted VS Code and now the file runs without issue. I guess "did you restart the computer" really does solve the issue sometimes...
Your function - yo(), is being defined, however Visual Studio Code does not know how to run it. To fix this, try adding the if __name__ == '__main__': clause. Here is your full code:
def yo():
text = "hi there"
print(text)
print(text)
if __name__ == '__main__':
yo()
Here is some more information about if __name__ == '__main__':
If that doesn't fix it, you must have some formatting issues or some different settings of Visual Studio Code. You could do the following things.
Make sure you're running the right file
Delete all of the code and paste it in again
Reset your Visual Studio Code settings
Make sure your settings for Tab are 4 spaces.
Disable terminal.integrated.inheritEnv in Settings
If all else fails, try these:
You should use the exit() command in the terminal to end python session. Then re-run and see if anything works.
Run your code using 'Start without debugging'.

Problem with exercism.io python track test/submit process

I have registered with exercism.io on the Python track, and haven't got off to a good start! The first exercise is a simple print hello world example, and I am of course able to write the code that executes this. The problem I have is where on earth do I place my code? Should I overwrite the existing hello_world.py file with my own file, or add my script lines to the existing file? I have read the documentation and must be missing something as I can't fathom out what to do with my code to test and submit.
When I download the test material, there is a default hello.world.py file created in the relevant directory, which contains this;
def hello():
pass
There is also a hello_world_test.py that contains this;
import unittest
import hello_world
# Tests adapted from `problem-specifications//canonical-data.json` # v1.1.0
class HelloWorldTest(unittest.TestCase):
def test_hello(self):
self.assertEqual(hello_world.hello(), 'Hello, World!')
if __name__ == '__main__':
unittest.main()
I have written a file called exercism_hello_world.py which contains this;
# This script prints "Hello, World!" to the console
print ("Hello, World!")
# end of script
Can anyone who may already be using exercism.io please advise how / where I place my code so that I can test / submit the first exercise and continue with the learning. Thanks.
After installing the cli script.
Enter the file location of full python file along with the name of the file.
Example
exercism submit C:\Users\srag\Exercism\python\hello-world\hello_world.py
You want the Exercism directory to begin with a capital "E" if you're running on macOS.
Try out:
exercism submit /Users/(your username)/Exercism/python/hello-world/hello_world.py
You should add your solution to the hello_world.py file.
However, you can change the default Exercism workspace directory. If you are on MacOS or Unix you can do that via terminal:
exercism configure --workspace="YOUR_PATH"
By changing this setting, everytime you run the command to "clone" the problem, it will get copied to the path you specified.
Regarding this problem, I am not sure if it helps, but it was stated to return "Hello, World!" and not print it.

Why doesn't IDLE need 'if __name__ == "__main__": to run a test case, but PyCharm does?

I'm practicing working with unittest, and I tried the following in PyCharm:
import unittest
from format_name import name_formatted
class TestName_formatted(unittest.TestCase):
"""practice with unittest"""
def test_name(self):
"""Testing name_formatted function"""
formatted_name = name_formatted("mike", "Cronin")
self.assertEqual(formatted_name, "mike Cronin")
unittest.main()
After research, I saw that it was written like this:
if __name__ == "__main__":
unittest.main()
And suddenly it worked perfectly. HOWEVER, the reason I wrote it that way, without the if statement, is because that's how I learned it from "Python Crash Course" which uses GEANY and IDLE for its example code. And sure enough, in both of those programs, you don't need the if statement.
Why is it that in one IDE the code doesn't work and in the others it does?
You are running the code in PyCharm as if it were a normal Python application; which is why you need the if __name__ == '__main__' conditional. This is also best practice when writing modules (files) that can be imported or run at the command line - the case with unit tests.
PyCharm is basically trying to do python your_file_name.py
The reason IDLE doesn't need this is because IDLE is running the application by first loading the file in the Python shell.
What IDLE is doing is:
python
>>> import your_file_name
By doing so, the code is automatically evaluated, the function is called and thus the test runs.
I would also suggest reading the documentation on testing in PyCharm's manual as testing is something PyCharm has extensive support for. In that link you'll also notice the default stub (or template) for a sample test case already has the if __name__ == '__main__' check:

How to execute a python test using httpretty/sure

I'm new to python tests so don't hesitate to provide any obvious information.
Basically I want to do some RESTful tests using python, and found the httpretty and sure libraries which look really nice.
I have a python file containing:
#!/usr/bin/python
from sure import expect
import requests, httpretty
#httpretty.activate
def RestTest():
httpretty.register_uri(httpretty.GET, "http://localhost:8090/test.json",
body='{"status": "ok"}',
content_type="application/json")
response = requests.get("http://localhost:8090/test.json")
expect(response.json()).to.equal({"status": "ok"}
Which is basically the same as the example code provided at https://github.com/gabrielfalcao/HTTPretty
My question is; how do I simply run this test to see it either passing or failing? I tried just executing it using ./pythonFile but that doesn't work.
If your test is implemented as a Python function, then of course simply trying to execute the file isn't going to run the test: nothing in that file actually calls RestTest.
You need some sort of test framework that will call your tests and collate the results.
One such solution is python-nose, which will look for methods named test_* and run them. So if you were to rename RestTest to test_rest, you could run:
$ nosetests myfile.py
.
----------------------------------------------------------------------
Ran 1 test in 0.012s
OK
The nosetests command has a variety of options that control which tests are run, how errors are handled and reported, and more.
Python 3 includes similar functionality in the unittest module, which is also available as a backport for Python 2 called unittest2. You could modify your code to take advantage of unittest like this:
#!/usr/bin/python
from sure import expect
import requests, httpretty
import unittest
class RestTest(unittest.TestCase):
#httpretty.activate
def test_rest(self):
httpretty.register_uri(httpretty.GET, "http://localhost:8090/test.json",
body='{"status": "ok"}',
content_type="application/json")
response = requests.get("http://localhost:8090/test.json")
expect(response.json()).to.equal({"status": "ok"})
if __name__ == '__main__':
unittest.main()
Running your file would now provide output similar to what we saw with
nosetests:
$ python myfile.py
.
----------------------------------------------------------------------
Ran 1 test in 0.012s
OK
Have you tried calling your method?
Or does the annotation mean you don't have to explicitly call your method?
If I call your method, it seems like it works. If I change the value on one side of the expect, it complains properly about the values not matching.

PyCharm and unittest won't run

I have a problem with PyCharm 3.0.1 I can't run basic unittests.
Here is my code :
import unittest from MysqlServer import MysqlServer
class MysqlServerTest(unittest.TestCase):
def setUp(self):
self.mysqlServer = MysqlServer("ip", "username", "password", "db", port)
def test_canConnect(self):
self.mysqlServer.connect()
self.fail()
if __name__ == '__main__':
unittest.main()
Here is All the stuff PyCharm give me
Unable to attach test reporter to test framework or test framework quit unexpectedly
It also says
AttributeError: class TestLoader has no attribute '__init__'
And the event log :
2:14:28 PM Empty test suite
The problem is when I run manually the Python file (with PyCharm, as a script)
Ran 1 tests in 0.019s
FAILED (failures=1)
Which is normal I make the test fail on purpose. I am a bit clueless on what is going on.
here more information :
Setting->Python Integrated Tools->Package requirements file: <PROJECT_HOME>/src/test
Default test runner: Unittests
pyunit 1.4.1 Is installed
EDIT: Same thing happen with the basic usage from unitests.py
import unittest
class IntegerArithmenticTestCase(unittest.TestCase):
def testAdd(self): ## test method names begin 'test*'
self.assertEquals((1 + 2), 3)
self.assertEquals(0 + 1, 1)
def testMultiply(self):
self.assertEquals((0 * 10), 0)
self.assertEquals((5 * 8), 40)
if __name__ == '__main__':
unittest.main()
Although this wasn't the case with the original poster, I'd like to note that another thing that will cause this are test functions that don't begin with the word 'test.'
class TestSet(unittest.TestCase):
def test_will_work(self):
pass
def will_not_work(self):
pass
This is probably because you did not set your testing framework correctly in the settings dialogue.
Definitely a pycharm thingy, repeating from above,
Run --> Edit Configurations.
select the instances of the test, and press the red minus button.
I have the exact same problem. It turned out that the fact of recognizing an individual test was related to the file name. In my case, test_calculate_kpi.py, which PyCharm didn't recognize as a test when renamed to test_calculate_kpis.py, was immediately recognized.
4 steps to generate html reports with PyCharm and most default test runners (py.test, nosetest, unittest etc.):
make sure you give your test methods a prefix 'test' (as stated before by others), e.g. def test_run1()
the widespread example code from test report packageā€˜s documentation is
import unittest
import HtmlTestRunner
class TestGoodnessOfFitTests(unittest.TestCase):
def test_run1(self):
...
if __name__ == '__main__':
unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='t.html'))
This code is usually located in a test class file which contains all the unittests and the "main"-catcher code. This code continuously yielded the warning Empty test suite for me. Therefore, remove all the if __name__ ... code. The file now only contains the TestGoodnessOfFitTests class. Now, additionally
create a new main.py in the same directory of the test class file and use the following code:
import unittest
import HtmlTestRunner
test_class = TestGoodnessOfFitTests()
unittest.main(module=test_class,
testRunner=HtmlTestRunner.HTMLTestRunner(output='t.html'))
Remove your old run configurations, right-click on your main.py and press Run 'main'. Verify correct settings under Preferences -> Python Integrated Tools -> Default test runner (in my case py.test and nose worked)
Output:
Running tests...
----------------------------------------------------------------------
test_gaussian_dummy_kolmogorov_cdf_1 (tests.evaluation_tests.TestGoodnessOfFitTests) ... OK (1.033877)s
----------------------------------------------------------------------
Ran 1 test in 0:00:01
OK
Generating HTML reports...
Even I had the same problem, I felt the workspace was not properly refreshed. Even I did File->Synchronize(Ctrl+Aly+y). But that wasn't the solution. I just renamed my test python file name and again I tried executing the code, it started worked fine.
I had the same problem. The file was named test_exercise_detectors.py (note the plural "detectors") and it was in a packed named test_exercise_detectors. Changing the name of the file to test_exercise_detector.py (singular "detector") fixed the problem.
Adding
if __name__ == "__main__":
unittest.main()
fixed the issue for me.

Categories

Resources