How Pylint determine Instance has variable or not - python

I have written simple file and run Pylint on this code code. Does anyone have idea How Pylint determine that Class sample does not have second variable.
Purpose: I would like to write simple script which will read sample
file(python code) and check which instance variable is accessed and
set by Instance. Ex if I write in main time.initial_time than my script able to detect that initial_time has been accessed by time Instance. it will be run at the run time. I mean, it will be part of existing flow
Real Purpose
To filter out unused member variable of class which is used thousands places and more than 100 variable
Sample file
"""testing pylint code"""
#!/usr/bin/env py
class Sample(object):
"""create sample class"""
def __init__(self):
"""seting variable"""
self.intial_time = 0
def main():
"""main functionality"""
time = Sample()
print time.second
if __name__ == " __main__":
main()
Pylint Error:
************* Module class_instance
R: 3, 0: Too few public methods (0/2) (too-few-public-methods)
E: 12,10: Instance of 'Sample' has no 'second' member (no-member)

Related

Why unit tests fil whereas the program runs?

I'm asked to develop unit tests for a program which is such badly developed that the tests don't run... but the program does. Thus, I need to explain the reason why and I actually don't know!
Here is a piece of code that intends to represent the code I need to test:
from services import myModule1
from services.spec1 import importedFunc
from services.spec2 import getTool
from services.spec3 import getDict
class myClass(object):
def __init__(self, param1, param2):
self.param1 = param1
self.param2 = param2
self.param3 = 0
self.param4 = 0
def myMethod(self):
try:
myVar1 = globalDict['key1']
myVar2 = globalDict['key2']
newVar = importedFunc(par1=myVar1, par2=myVar2, par3=extVar3)
calcParam = myModule1.methodMod1(self.param1)
self.param3 = calcParam["keyParam3"]
self.param4 = newVar.meth1(self.param2)
globTools.send_message(self.param3, self.param4)
except:
globTools.error_message(self.param3, self.param4)
return
class myClass2(object):
def __init__(self, *myclass2_params):
# some piece of code to intialize dedicated attributes
self.add_objects()
def add_objects(self):
# Some piece of code
my_class = myClass(**necessary_params)
# Some piece of code
return
if __name__ == '__main__':
globTools = getTool("my_program")
globalDict = getDict(some_params)
# Some piece of code
my_class2 = myClass2(**any_params)
# Some piece of code
As you can see, the problem is that the class and its methods uses global variables, defined in the main scope. And it's just a quick summary because it's actually a bit more complicated, but I hope it's enough to give you an overview of the context and help me understand why the unit test fail.
I tried to mock the imported modules, but I did not manage to a successful result, so I first tried to make it simple and just initialize all parameters.
I went to this test file:
import unittest
from my_module import myClass
from services import myModule1
from services.spec1 import importedFunc
from services.spec2 import getTool
from services.spec3 import getDict
def test_myClass(unittest.TestCase):
def setUp(self):
globTools = getTool("my_program")
globalDict = getDict(some_params)
def test_myMethod(self):
test_class = myClass(*necessary_parameters)
test_res = test_class.myMethod()
self.assertIsNotNone(test_res)
if __name__ == '__main__':
unittest.main()
But the test fail, telling me 'globTools is not defined' when trying to instantiate myClass
I also tried to initialize variables directly in the test method, but the result is the same
And to be complete about the technical environment, I cannot run python programs directly and need to launch a docker environment via a Jenkins pipeline - I'm not very familiar with this but I imagine it should not have an impact on the result
I guess the problem comes from the variable's scopes, but I'm not able to explain it in this case: why the test fail where as the method itself works (yes, it actually works, or at least the program globally runs without)
It's not as bad as you think. Your setUp method just needs to define the appropriate top-level globals in your module, rather than local variables.
import unittest
import my_module
from my_module import myClass
from services import myModule1
from services.spec1 import importedFunc
from services.spec2 import getTool
from services.spec3 import getDict
class test_myClass(unittest.TestCase):
def setUp(self):
my_module.globTools = getTool("my_program")
my_module.globalDict = getDict(some_params)
def test_myMethod(self):
test_class = myClass(*necessary_parameters)
test_res = test_class.myMethod()
self.assertIsNotNone(test_res)
if __name__ == '__main__':
unittest.main()
Depending on how the code uses the two globals, setUpClass might be a better place to initialize them, but it's probably not worth worrying about. Once you have tests for the code, you are in a better position to remove the dependency on these globals from the code.

Module has no attribute... unsure

In an effort to create a simple script for another question to highlight an issue I am having, I ran into this confusing problem. My code won't run. I read several other Stack Overflow answers and ensured that I am not using a pre-defined class. I am also not doing a cyclical import. I have no idea. I am new to Python.
TestClass.py:
class TestClass:
test_number = 10000 # Default score limit
def __init__(self):
pass
def check_test_number(self):
# this needs to be an instance method
print(TestClass.test_number)
TestScript.py:
import TestClass
def main():
t1 = TestClass.TestClass()
print(TestClass.test_number)
print(t1.check_test_number())
TestClass.test_number = 500
print(TestClass.test_number)
print(t1.check_test_number())
if __name__ == "__main__":
main()
I recieve this error:
AttributeError: module 'TestClass' has no attribute 'test_number'
Thanks in advance, guys!
You need to refer to the fields test_number and score_limit on lines print(TestClass.test_number) and TestClass.test_number= 500 like this: TestClass.TestClass.test_number or use expression from *your_file* import *ClassName*. In your code you're trying to refer not to a class field, but to a method or variable in the file TestClass.py. I advise you to use snake_case to name .py files to avoid confusions. I think your code can be rewritten like this (with renaming TestClass.py):
test_script.py
from test_class import TestClass
def main():
t1 = TestClass()
print(TestClass.test_number)
print(t1.check_test_number())
TestClass.test_number= 500
print(TestClass.test_number)
print(t1.check_test_number())
if __name__ == "__main__":
main()

Passing a variable through a class Python

I am trying to print to pass the endpoint variable to the __init__ function within the RUN() class. However it is giving me an error. AttributeError: module 'configs' has no attribute 'endpoint'. The endpoint document is saved in the file1.py and it is called in file2.py. How would I be able to pass endpoint as a param.
file1
endpoint = 'hello'
file2
import file1
class RUN():
def __init__(self, endpoint= file1.endpoint):
print("Initialized")
run_websocket = RUN()
The code is absolutely correct. Try deleting the cache of your IDE or build and dist folders, etc. then run again.

how to test a Python class that requires command line argument?

I have a python class that requires a command line argument:
class SomeClass:
request = sys.argv[1] + ".json"
def __init__(self_:
self.req = request
i'd run someClass.py on the commandline i.e. python someClass 1234, which would set the json to 1234.json.
I want a second class, testClass.py, to be able to test methods inside of the main class. But first, i just want to make sure its connected by printing variables:
from someClass import SomeClass
i = SomeClass()
print(i.req)
if i run python testClass.py (without any input), i get a missing input error,
error: the following arguments are required: input
so if i run python testClass.py 1234, i get
none
i just want to know how to pull the class in and make sure its provided with an argument so i can test individual components inside of it.
Just overwrite request in every test that needs it:
import unittest
from x import SomeClass
class TestClass(unittest.TestCase):
def setUp(self):
SomeClass.request = ''
In general, don't make classes which set themselves up. Make the class take parameters which are not defaulted.
You can always make higher level code which supplies default values.
Don't make your class depend on sys.argv in the first place.
class SomeClass:
def __init__(self, base):
self.req = base + ".json"
Then
from someClass import SomeClass
i = SomeClass(sys.argv[1]) # or any other value
print(i.req)

Access global instance modified inside main() function of a server from different modules

I have a server that contains a class which performs an expensive computation
during its initialization. I want to initialize this class once, inside the main() method of the server module, before starting the server. Then, I want other modules that import the server module to be able to retrieve the instance of this class.
Example (the sleep emulates the server running)
import time
# I want to store the shared_instance of this global variable
shared_instance = None
class Shared:
def __init__(self):
# Expensive computation that I only want to run once
pass
def main():
global shared_instance
shared_instance = Shared() # Now instance_of_scorer is not None anymore
print(shared_instance)
print("Starting server...")
time.sleep(1000)
if __name__ == '__main__':
main()
When I run this server it prints:
<__main__.Shared object at 0x000001865A3C4320>
Starting server...
Now I have other module that should be able to see the instance:
import server
print(server.shared_instance)
However, shared_instance is not '<main.Shared object at 0x000001865A3C4320>' as expected. It is 'None'. Could you please tell me want I'm doing wrong and how can I solve this issue and achieve this functionality?.
Many thanks

Categories