How to use nice_classname method in Nose

Best Python code snippet using nose

memTest.py

Source:memTest.py Github

copy

Full Screen

...10import time11import os12import subprocess13import sys14def nice_classname(obj):15 """Returns a nice name for class object or class instance.16 17 >>> nice_classname(Exception()) # doctest: +ELLIPSIS18 '...Exception'19 >>> nice_classname(Exception)20 'exceptions.Exception'21 22 """23 if inspect.isclass(obj):24 cls_name = obj.__name__25 else:26 cls_name = obj.__class__.__name__27 mod = inspect.getmodule(obj)28 if mod:29 name = mod.__name__30 # jython31 if name.startswith('org.python.core.'):32 name = name[len('org.python.core.'):]33 return "%s.%s" % (name, cls_name)34 else:35 return cls_name36def write_message(fileleak, memoryleak):37 if fileleak != 0:38 print "Net file descriptors opened:", fileleak39 if memoryleak != 0:40 print "Net memory allocated:", memoryleak, "kB"41 return "<system-out>\42&lt;measurement&gt;&lt;name&gt;Files leaked&lt;/name&gt;&lt;value&gt;" + str(fileleak) + "&lt;/value&gt;&lt;/measurement&gt;\43&lt;measurement&gt;&lt;name&gt;Memory leaked (kB)&lt;/name&gt;&lt;value&gt;" + str(memoryleak) + "&lt;/value&gt;&lt;/measurement&gt;\44</system-out>"45class MemTest(nose.plugins.xunit.Xunit):46 name = "memtest"47 def options(self, parser, env):48 # Identical to the base class method, except that the command line49 # option needs to be called something different50 """Sets additional command line options."""51 nose.plugins.base.Plugin.options(self, parser, env)52 parser.add_option(53 '--memtest-file', action='store',54 dest='xunit_file', metavar="FILE",55 default=env.get('NOSE_XUNIT_FILE', 'nosetests.xml'),56 help=("Path to xml file to store the xunit report in. "57 "Default is nosetests.xml in the working directory "58 "[NOSE_XUNIT_FILE]"))59 # Find the lsof executable60 self.lsof = "/usr/sbin/lsof"61 if not os.path.exists(self.lsof):62 self.lsof = "/usr/bin/lsof"63 if not os.path.exists(self.lsof):64 print "Warning: Could not find lsof at /usr/sbin/lsof or /usr/bin/lsof"65 def report(self, stream):66 """Writes an Xunit-formatted XML file67 The file includes a report of test errors and failures.68 """69 self.stats['encoding'] = self.encoding70 self.stats['total'] = (self.stats['errors'] + self.stats['failures']71 + self.stats['passes'] + self.stats['skipped'])72 self.error_report_file.write(73 '<?xml version="1.0" encoding="%s"?>'74 '<testsuites>' % self.encoding)75 76 self.error_report_file.write(''.join(self.errorlist))77 self.error_report_file.write('</testsuites>')78 self.error_report_file.close()79 if self.config.verbosity > 1:80 stream.writeln("-" * 70)81 stream.writeln("XML: %s" % self.error_report_file.name)82 @staticmethod83 def _getstatusoutput(cmd):84 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)85 stdoutdata, stderrdata = p.communicate(None)86 if stderrdata is not None and len(stderrdata) > 0:87 print >> sys.stderr, stderrdata88 return (p.returncode, stdoutdata)89 def startTest(self, test):90 """Initializes a timer before starting a test."""91 self._timer = time.time()92 self._pid = os.getpid()93 msg = '***** List of open files after running %s\n'%test94 infile = open('ListOpenFiles','a')95 infile.write(msg)96 infile.close()97 (errorcode, n) = self._getstatusoutput(self.lsof + ' -p ' + str(self._pid) + ' | wc -l')98 if errorcode == 0:99 self._openfiles = n100 else:101 self._openfiles = 0102 (errorcode, n) = self._getstatusoutput('env -i ps -p ' + str(self._pid) + ' -o rss | tail -1')103 if errorcode == 0:104 self._resident_memory = n105 else:106 self._resident_memory = 0 107 def stopContext(self, context):108 try:109 out = subprocess.check_output("du -h", shell=True)110 except subprocess.CalledProcessError, e:111 out = e.output112 print "Directory contents after", context113 print out114 def _update_after_test(self):115 # The predefined hooks stopTest() and afterTest() cannot be used116 # because they get called after addError/addFailure/addSuccess117 subprocess.call(118 self.lsof + ' -p ' + str(self._pid) + ' | grep -i nosedir >> ListOpenFiles',119 shell=True)120 (errorcode, n) = self._getstatusoutput(self.lsof + ' -p ' + str(self._pid) + ' | wc -l')121 if errorcode == 0:122 self._fileleak = int(n) - int(self._openfiles)123 else:124 self._fileleak = -1125 (errorcode, n) = self._getstatusoutput('env -i ps -p ' + str(self._pid) + ' -o rss | tail -1')126 if errorcode == 0:127 self._memoryleak = int(n) - int(self._resident_memory)128 else:129 self._memoryleak = 0130 def addError(self, test, err, capt=None):131 """Add error output to Xunit report.132 """133 self._update_after_test()134 taken = time.time() - self._timer135 if issubclass(err[0], nose.exc.SkipTest):136 self.stats['skipped'] +=1137 return138 tb = ''.join(traceback.format_exception(*err))139 self.stats['errors'] += 1140 id = test.id()141 name = id[-id[::-1].find("."):]142 self.errorlist.append(143 '<testsuite name="nosetests" tests="1" errors="1" failures="0" skip="0">'144 '<testcase classname="%(cls)s" name="%(name)s" time="%(taken)d">'145 '<error type="%(errtype)s">%(tb)s</error></testcase>' %146 {'cls': '.'.join(id.split('.')[:-1]),147 'name': name,148 'errtype': nice_classname(err[0]),149 'tb': tb,150 'taken': taken,151 })152 self.errorlist.append(write_message(self._fileleak, self._memoryleak))153 self.errorlist.append('</testsuite>')154 def addFailure(self, test, err, capt=None, tb_info=None):155 """Add failure output to Xunit report.156 """157 self._update_after_test()158 taken = time.time() - self._timer159 tb = ''.join(traceback.format_exception(*err))160 self.stats['failures'] += 1161 id = test.id()162 name = id[-id[::-1].find("."):]163 self.errorlist.append(164 '<testsuite name="nosetests" tests="1" errors="0" failures="1" skip="0">'165 '<testcase classname="%(cls)s" name="%(name)s" time="%(taken)d">'166 '<failure type="%(errtype)s">%(tb)s</failure></testcase>' %167 {'cls': '.'.join(id.split('.')[:-1]),168 'name': name,169 'errtype': nice_classname(err[0]),170 'tb': tb,171 'taken': taken,172 })173 self.errorlist.append(write_message(self._fileleak, self._memoryleak))174 self.errorlist.append('</testsuite>')175 176 def addSuccess(self, test, capt=None):177 """Add success output to Xunit report.178 """179 self._update_after_test()180 taken = time.time() - self._timer181 self.stats['passes'] += 1182 id = test.id()183 name = id[-id[::-1].find("."):]...

Full Screen

Full Screen

xunit.py

Source:xunit.py Github

copy

Full Screen

...48 ("'", '&#39;', ),49 ]:50 s = s.replace(src, rep)51 return s52def nice_classname(obj):53 """Returns a nice name for class object or class instance.54 55 >>> nice_classname(Exception()) # doctest: +ELLIPSIS56 '...Exception'57 >>> nice_classname(Exception)58 'exceptions.Exception'59 60 """61 if inspect.isclass(obj):62 cls_name = obj.__name__63 else:64 cls_name = obj.__class__.__name__65 mod = inspect.getmodule(obj)66 if mod:67 name = mod.__name__68 # jython69 if name.startswith('org.python.core.'):70 name = name[len('org.python.core.'):]71 return "%s.%s" % (name, cls_name)72 else:73 return cls_name74class Xunit(Plugin):75 """This plugin provides test results in the standard XUnit XML format."""76 name = 'xunit'77 score = 200078 encoding = 'UTF-8'79 80 def _timeTaken(self):81 if hasattr(self, '_timer'):82 taken = time() - self._timer83 else:84 # test died before it ran (probably error in setup())85 # or success/failure added before test started probably 86 # due to custom TestResult munging87 taken = 0.088 return taken89 90 def _xmlsafe(self, s):91 return xmlsafe(s, encoding=self.encoding)92 93 def options(self, parser, env):94 """Sets additional command line options."""95 Plugin.options(self, parser, env)96 parser.add_option(97 '--xunit-file', action='store',98 dest='xunit_file', metavar="FILE",99 default=env.get('NOSE_XUNIT_FILE', 'nosetests.xml'),100 help=("Path to xml file to store the xunit report in. "101 "Default is nosetests.xml in the working directory "102 "[NOSE_XUNIT_FILE]"))103 def configure(self, options, config):104 """Configures the xunit plugin."""105 Plugin.configure(self, options, config)106 self.config = config107 if self.enabled:108 self.stats = {'errors': 0,109 'failures': 0,110 'passes': 0,111 'skipped': 0112 }113 self.errorlist = []114 self.error_report_file = open(options.xunit_file, 'w')115 def report(self, stream):116 """Writes an Xunit-formatted XML file117 The file includes a report of test errors and failures.118 """119 self.stats['encoding'] = self.encoding120 self.stats['total'] = (self.stats['errors'] + self.stats['failures']121 + self.stats['passes'] + self.stats['skipped'])122 self.error_report_file.write(123 '<?xml version="1.0" encoding="%(encoding)s"?>'124 '<testsuite name="nosetests" tests="%(total)d" '125 'errors="%(errors)d" failures="%(failures)d" '126 'skip="%(skipped)d">' % self.stats)127 self.error_report_file.write(''.join(self.errorlist))128 self.error_report_file.write('</testsuite>')129 self.error_report_file.close()130 if self.config.verbosity > 1:131 stream.writeln("-" * 70)132 stream.writeln("XML: %s" % self.error_report_file.name)133 def startTest(self, test):134 """Initializes a timer before starting a test."""135 self._timer = time()136 def addError(self, test, err, capt=None):137 """Add error output to Xunit report.138 """139 taken = self._timeTaken()140 141 if issubclass(err[0], SkipTest):142 self.stats['skipped'] +=1143 return144 tb = ''.join(traceback.format_exception(*err))145 self.stats['errors'] += 1146 id = test.id()147 self.errorlist.append(148 '<testcase classname="%(cls)s" name="%(name)s" time="%(taken)d">'149 '<error type="%(errtype)s">%(tb)s</error></testcase>' %150 {'cls': self._xmlsafe('.'.join(id.split('.')[:-1])),151 'name': self._xmlsafe(id),152 'errtype': self._xmlsafe(nice_classname(err[0])),153 'tb': self._xmlsafe(tb),154 'taken': taken,155 })156 def addFailure(self, test, err, capt=None, tb_info=None):157 """Add failure output to Xunit report.158 """159 taken = self._timeTaken()160 tb = ''.join(traceback.format_exception(*err))161 self.stats['failures'] += 1162 id = test.id()163 self.errorlist.append(164 '<testcase classname="%(cls)s" name="%(name)s" time="%(taken)d">'165 '<failure type="%(errtype)s">%(tb)s</failure></testcase>' %166 {'cls': self._xmlsafe('.'.join(id.split('.')[:-1])),167 'name': self._xmlsafe(id),168 'errtype': self._xmlsafe(nice_classname(err[0])),169 'tb': self._xmlsafe(tb),170 'taken': taken,171 })172 173 def addSuccess(self, test, capt=None):174 """Add success output to Xunit report.175 """176 taken = self._timeTaken()177 178 self.stats['passes'] += 1179 id = test.id()180 self.errorlist.append(181 '<testcase classname="%(cls)s" name="%(name)s" '182 'time="%(taken)d" />' %...

Full Screen

Full Screen

__init__.py

Source:__init__.py Github

copy

Full Screen

...17 head, tail = name.rsplit(".", 1)18 return [head, tail+fargs]19 else:20 return idval.rsplit(".", 1)21def nice_classname(obj):22 """Returns a nice name for class object or class instance.23 >>> nice_classname(Exception()) # doctest: +ELLIPSIS24 '...Exception'25 >>> nice_classname(Exception) # doctest: +ELLIPSIS26 '...Exception'27 """28 if inspect.isclass(obj):29 cls_name = obj.__name__30 else:31 cls_name = obj.__class__.__name__32 mod = inspect.getmodule(obj)33 if mod:34 name = mod.__name__35 # jython36 if name.startswith('org.python.core.'):37 name = name[len('org.python.core.'):]38 return "%s.%s" % (name, cls_name)39 else:40 return cls_name41def exc_message(exc_info):42 """Return the exception's message."""43 exc = exc_info[1]44 if exc is None:45 # str exception46 result = exc_info[0]47 else:48 try:49 result = str(exc)50 except UnicodeEncodeError:51 try:52 result = unicode(exc) # flake8: noqa53 except UnicodeError:54 # Fallback to args as neither str nor55 # unicode(Exception(u'\xe6')) work in Python < 2.656 result = exc.args[0]57 return result58class Group(object):59 def __init__(self):60 self.stats = {'errors': 0, 'failures': 0, 'passes': 0, 'skipped': 0}61 self.tests = []62class HtmlOutput(Plugin):63 """64 Output test results as pretty html.65 """66 name = 'html'67 score = 200068 encoding = 'UTF-8'69 report_file = None70 def options(self, parser, env):71 """Sets additional command line options."""72 Plugin.options(self, parser, env)73 parser.add_option(74 '--html-file', action='store',75 dest='html_file', metavar="FILE",76 default=env.get('NOSE_HTML_FILE', 'nosetests.html'),77 help="Path to html file to store the report in. "78 "Default is nosetests.html in the working directory "79 "[NOSE_HTML_FILE]")80 def configure(self, options, config):81 """Configures the xunit plugin."""82 Plugin.configure(self, options, config)83 self.config = config84 if self.enabled:85 self.jinja = Environment(86 loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')),87 trim_blocks=True,88 lstrip_blocks=True89 )90 self.stats = {'errors': 0, 'failures': 0, 'passes': 0, 'skipped': 0}91 self.report_data = defaultdict(Group)92 self.report_file = codecs.open(options.html_file, 'w', self.encoding, 'replace')93 def report(self, stream):94 """Writes an Xunit-formatted XML file95 The file includes a report of test errors and failures.96 """97 from collections import OrderedDict98 self.stats['total'] = sum(self.stats.values())99 for group in self.report_data.values():100 group.stats['total'] = sum(group.stats.values())101 self.report_file.write(self.jinja.get_template('report.html').render(102 report=OrderedDict(sorted(self.report_data.items())),103 stats=self.stats,104 ))105 self.report_file.close()106 if self.config.verbosity > 1:107 stream.writeln("-" * 70)108 stream.writeln("HTML: %s" % self.report_file.name)109 def addSuccess(self, test):110 name = id_split(test.id())111 group = self.report_data[name[0]]112 self.stats['passes'] += 1113 group.stats['passes'] += 1114 group.tests.append({115 'name': name[-1],116 'failed': False,117 })118 def addError(self, test, err, capt=None):119 """Add error output to Xunit report.120 """121 exc_type, exc_val, tb = err122 tb = ''.join(traceback.format_exception(123 exc_type,124 exc_val if isinstance(exc_val, exc_type) else exc_type(exc_val),125 tb126 ))127 name = id_split(test.id())128 group = self.report_data[name[0]]129 if issubclass(err[0], SkipTest):130 type = 'skipped'131 self.stats['skipped'] += 1132 group.stats['skipped'] += 1133 else:134 type = 'error'135 self.stats['errors'] += 1136 group.stats['errors'] += 1137 group.tests.append({138 'name': name[-1],139 'failed': True,140 'type': type,141 'errtype': nice_classname(err[0]),142 'message': exc_message(err),143 'tb': tb,144 })145 def addFailure(self, test, err, capt=None):146 """Add failure output to Xunit report.147 """148 exc_type, exc_val, tb = err149 tb = ''.join(traceback.format_exception(150 exc_type,151 exc_val if isinstance(exc_val, exc_type) else exc_type(exc_val),152 tb153 ))154 name = id_split(test.id())155 group = self.report_data[name[0]]156 self.stats['failures'] += 1157 group.stats['failures'] += 1158 group.tests.append({159 'name': name[-1],160 'failed': True,161 'errtype': nice_classname(err[0]),162 'message': exc_message(err),163 'tb': tb,...

Full Screen

Full Screen

patch-nose::plugins::xunit.py

Source:patch-nose::plugins::xunit.py Github

copy

Full Screen

...14+ else:15+ return idval.rsplit(".", 1)16+ 17+18 def nice_classname(obj):19 """Returns a nice name for class object or class instance.20 21@@ -190,8 +201,8 @@22 '<testcase classname=%(cls)s name=%(name)s time="%(taken)d">'23 '<%(type)s type=%(errtype)s message=%(message)s><![CDATA[%(tb)s]]>'24 '</%(type)s></testcase>' %25- {'cls': self._quoteattr('.'.join(id.split('.')[:-1])),26- 'name': self._quoteattr(id.split('.')[-1]),27+ {'cls': self._quoteattr(id_split(id)[0]),28+ 'name': self._quoteattr(id_split(id)[-1]),29 'taken': taken,30 'type': type,31 'errtype': self._quoteattr(nice_classname(err[0])),32@@ -210,8 +221,8 @@33 '<testcase classname=%(cls)s name=%(name)s time="%(taken)d">'34 '<failure type=%(errtype)s message=%(message)s><![CDATA[%(tb)s]]>'35 '</failure></testcase>' %36- {'cls': self._quoteattr('.'.join(id.split('.')[:-1])),37- 'name': self._quoteattr(id.split('.')[-1]),38+ {'cls': self._quoteattr(id_split(id)[0]),39+ 'name': self._quoteattr(id_split(id)[-1]),40 'taken': taken,41 'errtype': self._quoteattr(nice_classname(err[0])),42 'message': self._quoteattr(exc_message(err)),43@@ -227,7 +238,7 @@44 self.errorlist.append(45 '<testcase classname=%(cls)s name=%(name)s '46 'time="%(taken)d" />' %47- {'cls': self._quoteattr('.'.join(id.split('.')[:-1])),48- 'name': self._quoteattr(id.split('.')[-1]),49+ {'cls': self._quoteattr(id_split(id)[0]),50+ 'name': self._quoteattr(id_split(id)[-1]),51 'taken': taken,...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Nose automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful