Skip to content

Commit

Permalink
Merge pull request #4226 from rlaverde/test-search-avoided-patterns-3…
Browse files Browse the repository at this point in the history
….1.x

PR: Generalice previous is_instance test to search other avoided patterns
  • Loading branch information
ccordoba12 authored Mar 8, 2017
2 parents 988e292 + f5b7cdc commit 61f64ef
Show file tree
Hide file tree
Showing 31 changed files with 139 additions and 89 deletions.
5 changes: 2 additions & 3 deletions spyder/app/mainwindow.py
Original file line number Diff line number Diff line change
Expand Up @@ -1620,7 +1620,6 @@ def setup_default_layouts(self, index, settings):
# widget.setMinimumWidth(new_width)
# widget.setMaximumWidth(new_width)
# widget.updateGeometry()
# print(c, widgets_layout[c][0][0], new_width)

# fix column height
for c, column in enumerate(widgets_layout):
Expand Down Expand Up @@ -2725,8 +2724,8 @@ def restart(self, reset=False):
except Exception as error:
# If there is an error with subprocess, Spyder should not quit and
# the error can be inspected in the internal console
print(error)
print(command)
print(error) # spyder: test-skip
print(command) # spyder: test-skip

# ---- Interactive Tours
def show_tour(self, index):
Expand Down
2 changes: 1 addition & 1 deletion spyder/app/tour.py
Original file line number Diff line number Diff line change
Expand Up @@ -811,7 +811,7 @@ def keyReleaseEvent(self, event):
""" """
key = event.key()
self.key_pressed = key
# print(key)

keys = [Qt.Key_Right, Qt.Key_Left, Qt.Key_Down, Qt.Key_Up,
Qt.Key_Escape, Qt.Key_PageUp, Qt.Key_PageDown,
Qt.Key_Home, Qt.Key_End, Qt.Key_Menu]
Expand Down
2 changes: 1 addition & 1 deletion spyder/config/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ def translate_gettext(x):
return to_text_string(y, "utf-8")
return translate_gettext
except IOError as _e: # analysis:ignore
#print "Not using translations (%s)" % _e
# Not using translations
def translate_dumb(x):
if not is_unicode(x):
return to_text_string(x, "utf-8")
Expand Down
2 changes: 1 addition & 1 deletion spyder/config/gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def get_family(families):
if font_is_installed(family):
return family
else:
print("Warning: None of the following fonts is installed: %r" % families)
print("Warning: None of the following fonts is installed: %r" % families) # spyder: test-skip
return QFont().family()


Expand Down
10 changes: 5 additions & 5 deletions spyder/config/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def _set(self, section, option, value, verbose):
if not is_text_string(value):
value = repr( value )
if verbose:
print('%s[ %s ] = %s' % (section, option, value))
print('%s[ %s ] = %s' % (section, option, value)) # spyder: test-skip
cp.ConfigParser.set(self, section, option, value)

def _save(self):
Expand Down Expand Up @@ -116,8 +116,8 @@ def _write_file(fname):
time.sleep(0.05)
_write_file(fname)
except Exception as e:
print("Failed to write user configuration file.")
print("Please submit a bug report.")
print("Failed to write user configuration file.") # spyder: test-skip
print("Please submit a bug report.") # spyder: test-skip
raise(e)

def filename(self):
Expand Down Expand Up @@ -246,12 +246,12 @@ def load_from_ini(self):
with codecs.open(fname, encoding='utf-8') as configfile:
self.readfp(configfile)
except IOError:
print("Failed reading file", fname)
print("Failed reading file", fname) # spyder: test-skip
else:
# Python 3
self.read(self.filename(), encoding='utf-8')
except cp.MissingSectionHeaderError:
print("Warning: File contains no section headers.")
print("Warning: File contains no section headers.") # spyder: test-skip

def _load_old_defaults(self, old_version):
"""Read old defaults"""
Expand Down
2 changes: 1 addition & 1 deletion spyder/interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def help_replacement(self, text=None, interactive=False):
try:
eval("pydoc.help(%s)" % text)
except (NameError, SyntaxError):
print("no Python documentation found for '%r'" % text)
print("no Python documentation found for '%r'" % text) # spyder: test-skip
self.write(os.linesep)
self.widget_proxy.new_prompt("help> ")
inp = self.raw_input_replacement()
Expand Down
2 changes: 1 addition & 1 deletion spyder/plugins/shortcuts.py
Original file line number Diff line number Diff line change
Expand Up @@ -835,7 +835,7 @@ def test():
table = ShortcutsTable()
table.show()
app.exec_()
print([str(s) for s in table.source_model.shortcuts])
print([str(s) for s in table.source_model.shortcuts]) # spyder: test-skip
table.check_shortcuts()

if __name__ == '__main__':
Expand Down
8 changes: 4 additions & 4 deletions spyder/scientific_startup.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@
def exec_print(string="", end_space=False):
if sys.version[0] == '2':
if end_space:
exec("print '" + string + "',")
exec("print '" + string + "',") # spyder: test-skip
else:
exec("print '" + string + "'")
exec("print '" + string + "'") # spyder: test-skip
else:
if end_space:
exec("print('" + string + "', end=' ')")
exec("print('" + string + "', end=' ')") # spyder: test-skip
else:
exec("print('" + string + "')")
exec("print('" + string + "')") # spyder: test-skip


#==============================================================================
Expand Down
54 changes: 54 additions & 0 deletions spyder/tests/test_dont_use.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)

import os
import re
import codecs

import pytest

root_path = os.path.realpath(os.path.join(os.getcwd(), 'spyder'))


@pytest.mark.parametrize("pattern,exclude_patterns,message", [
("isinstance\(.*,.*str\)", ['py3compat.py'],
("Don't use builtin isinstance() function,"
"use spyder.py3compat.is_text_string() instead")),
(r"^[\s\#]*\bprint\(((?!file=).)*\)", ['.*test.*', 'example.py', 'binaryornot'],
("Don't use print() functions, ",
"for debuging you could use debug_print instead")),
(r"^[\s\#]*\bprint\s+(?!>>)((?!#).)*", ['.*test.*'],
("Don't use print __builtin__, ",
"for debuging you could use debug_print instead")),
])
def test_dont_use(pattern, exclude_patterns, message):
"""
This test is used for discouraged using of some expresions that could
introduce errors, and encourage use spyder function instead.
If you want to skip some line from this test just use:
# spyder: test-skip
"""
pattern = re.compile(pattern + "((?!# spyder: test-skip)\s)*$")

found = 0
for dir_name, _, file_list in os.walk(root_path):
for fname in file_list:
exclude = any([re.search(ex, fname) for ex in exclude_patterns])
exclude = exclude or any([re.search(ex, dir_name) for ex in exclude_patterns])

if fname.endswith('.py') and not exclude:
file = os.path.join(dir_name, fname)

with codecs.open(file, encoding="utf-8") as f:
for i, line in enumerate(f):
for match in re.finditer(pattern, line):
print("{}\nline:{}, {}".format(file, i + 1, line))
found += 1

assert found == 0, "{}\n{} errors found".format(message, found)
10 changes: 5 additions & 5 deletions spyder/utils/bsdsocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ class PacketNotReceived(object):
# socket read/write testing - client and server in one thread

# (techtonik): the stuff below is placed into public domain
print("-- Testing standard Python socket interface --")
print("-- Testing standard Python socket interface --") # spyder: test-skip

address = ("127.0.0.1", 9999)

Expand All @@ -162,7 +162,7 @@ class PacketNotReceived(object):
# accepted server socket is the one we can read from
# note that it is different from server socket
accsock, addr = server.accept()
print('..got "%s" from %s' % (accsock.recv(4096), addr))
print('..got "%s" from %s' % (accsock.recv(4096), addr)) # spyder: test-skip

# accsock.close()
# client.send("more data for recv")
Expand All @@ -171,12 +171,12 @@ class PacketNotReceived(object):
#socket.error: [Errno 11] Resource temporarily unavailable


print("-- Testing BSD socket write_packet/read_packet --")
print("-- Testing BSD socket write_packet/read_packet --") # spyder: test-skip

write_packet(client, "a tiny piece of data")
print('..got "%s" from read_packet()' % (read_packet(accsock)))
print('..got "%s" from read_packet()' % (read_packet(accsock))) # spyder: test-skip

client.close()
server.close()

print("-- Done.")
print("-- Done.") # spyder: test-skip
22 changes: 11 additions & 11 deletions spyder/utils/dochelpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,14 +331,14 @@ def isdefined(obj, force_import=False, namespace=None):
class Test(object):
def method(self, x, y=2):
pass
print(getargtxt(Test.__init__))
print(getargtxt(Test.method))
print(isdefined('numpy.take', force_import=True))
print(isdefined('__import__'))
print(isdefined('.keys', force_import=True))
print(getobj('globals'))
print(getobj('globals().keys'))
print(getobj('+scipy.signal.'))
print(getobj('4.'))
print(getdoc(sorted))
print(getargtxt(sorted))
print(getargtxt(Test.__init__)) # spyder: test-skip
print(getargtxt(Test.method)) # spyder: test-skip
print(isdefined('numpy.take', force_import=True)) # spyder: test-skip
print(isdefined('__import__')) # spyder: test-skip
print(isdefined('.keys', force_import=True)) # spyder: test-skip
print(getobj('globals')) # spyder: test-skip
print(getobj('globals().keys')) # spyder: test-skip
print(getobj('+scipy.signal.')) # spyder: test-skip
print(getobj('4.')) # spyder: test-skip
print(getdoc(sorted)) # spyder: test-skip
print(getargtxt(sorted)) # spyder: test-skip
4 changes: 2 additions & 2 deletions spyder/utils/inputhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,12 +146,12 @@ def qt4():
event_loop.exec_()
timer.stop()
except KeyboardInterrupt:
print("\nKeyboardInterrupt - Press Enter for new prompt")
print("\nKeyboardInterrupt - Press Enter for new prompt") # spyder: test-skip
except: # NO exceptions are allowed to escape from a ctypes callback
ignore_CTRL_C()
from traceback import print_exc
print_exc()
print("Got exception from inputhook, unregistering.")
print("Got exception from inputhook, unregistering.") # spyder: test-skip
clear_inputhook()
finally:
allow_CTRL_C()
Expand Down
2 changes: 1 addition & 1 deletion spyder/utils/introspection/module_completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def get_root_modules(paths):
for path in sys.path:
modules += module_list(path)
if time() - t > TIMEOUT_GIVEUP:
print("Module list generation is taking too long, we give up.\n")
print("Module list generation is taking too long, we give up.\n") # spyder: test-skip
modules_db['rootmodules'] = []
return []

Expand Down
6 changes: 3 additions & 3 deletions spyder/utils/introspection/plugin_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,18 +206,18 @@ def __init__(self, plugin_name, executable=None, env=None):
plugin.run()

def handle_return(value):
print(value)
print(value) # spyder: test-skip
if value['func_name'] == 'foo':
app.quit()
else:
plugin.request('foo')

def handle_errored():
print('errored')
print('errored') # spyder: test-skip
sys.exit(1)

def start():
print('start')
print('start') # spyder: test-skip
plugin.request('validate')

plugin.errored.connect(handle_errored)
Expand Down
10 changes: 5 additions & 5 deletions spyder/utils/introspection/plugin_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def run(self):
if events == 0 and initialized:
if timed_out:
delta = int(time.time() - t0)
print('Timed out after %s sec' % delta)
print('Timed out after %s sec' % delta) # spyder: test-skip
return
timed_out = True
continue
Expand All @@ -66,13 +66,13 @@ def run(self):
time.sleep(0.1)
continue
if request['func_name'] == 'server_quit':
print('Quitting')
print('Quitting') # spyder: test-skip
sys.stdout.flush()
return
elif request['func_name'] != 'server_heartbeat':
requests.append(request)
else:
print('Got heartbeat')
print('Got heartbeat') # spyder: test-skip
try:
events = self.socket.poll(0)
except KeyboardInterrupt:
Expand Down Expand Up @@ -122,8 +122,8 @@ def initialize(self, plugin_name):
if __name__ == '__main__':
args = sys.argv[1:]
if not len(args) == 2:
print('Usage: plugin_server.py client_port plugin_name')
print('Usage: plugin_server.py client_port plugin_name') # spyder: test-skip
sys.exit(0)
plugin = PluginServer(*args)
print('Started')
print('Started') # spyder: test-skip
plugin.run()
6 changes: 2 additions & 4 deletions spyder/utils/iofuncs.py
Original file line number Diff line number Diff line change
Expand Up @@ -491,12 +491,10 @@ def save_auto(data, filename):
import time
t0 = time.time()
save_dictionary(example, "test.spydata")
print(" Data saved in %.3f seconds" % (time.time()-t0))
print(" Data saved in %.3f seconds" % (time.time()-t0)) # spyder: test-skip
t0 = time.time()
example2, ok = load_dictionary("test.spydata")
print("Data loaded in %.3f seconds" % (time.time()-t0))
# for key in example:
# print key, ":", example[key] == example2[key]
print("Data loaded in %.3f seconds" % (time.time()-t0)) # spyder: test-skip

a = MatlabStruct()
a.b = 'spam'
Expand Down
2 changes: 1 addition & 1 deletion spyder/utils/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ def decorator(func):
if old_func is not None:
# Add the old func to a list of old funcs.
old_ref = "_old_%s_%s" % (patch_name, fname)
#print old_ref, old_func

old_attr = getattr(cls, old_ref, None)
if old_attr is None:
setattr(cls, old_ref, old_func)
Expand Down
2 changes: 1 addition & 1 deletion spyder/utils/site/osx_app_site.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def __call__(self):
while 1:
try:
for i in range(lineno, lineno + self.MAXLINES):
print(self.__lines[i])
print(self.__lines[i]) # spyder: test-skip
except IndexError:
break
else:
Expand Down
2 changes: 1 addition & 1 deletion spyder/utils/site/sitecustomize.py
Original file line number Diff line number Diff line change
Expand Up @@ -580,7 +580,7 @@ def decorator(func):
if old_func is not None:
# Add the old func to a list of old funcs.
old_ref = "_old_%s_%s" % (patch_name, fname)
#print(old_ref, old_func)

old_attr = getattr(cls, old_ref, None)
if old_attr is None:
setattr(cls, old_ref, old_func)
Expand Down
6 changes: 3 additions & 3 deletions spyder/utils/stringmatching.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,13 +268,13 @@ def test():
sort=True)
# Full results
for r in a:
print(r)
print(r) # spyder: test-skip

# Ordered and filtered results
print('\n')
print('\n') # spyder: test-skip

for r in b:
print(r)
print(r) # spyder: test-skip

if __name__ == '__main__':
test()
12 changes: 6 additions & 6 deletions spyder/utils/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,11 @@ def psutil_phymem_usage():


if __name__ == '__main__':
print("*"*80)
print(memory_usage.__doc__)
print(memory_usage())
print("*"*80) # spyder: test-skip
print(memory_usage.__doc__) # spyder: test-skip
print(memory_usage()) # spyder: test-skip
if os.name == 'nt':
# windll can only be imported if os.name = 'nt' or 'ce'
print("*"*80)
print(windows_memory_usage.__doc__)
print(windows_memory_usage())
print("*"*80) # spyder: test-skip
print(windows_memory_usage.__doc__) # spyder: test-skip
print(windows_memory_usage()) # spyder: test-skip
Loading

0 comments on commit 61f64ef

Please sign in to comment.