Description: Upstream changes introduced in version 0.1b2 This patch has been created by dpkg-source during the package build. Here's the last changelog entry, hopefully it gives details on why those changes were made: . jcl (0.1b2) unstable; urgency=low . * JCL v0.1 beta 2 . The person named in the Author field signed this changelog entry. Author: David Rousselie --- The information above should follow the Patch Tagging Guidelines, please checkout http://dep.debian.net/deps/dep3/ to learn about the format. Here are templates for supplementary fields that you might want to add: Origin: , Bug: Bug-Debian: http://bugs.debian.org/ Forwarded: Reviewed-By: Last-Update: --- /dev/null +++ jcl-0.1b2/coverage.py @@ -0,0 +1,952 @@ +#!/usr/bin/python +# +# Perforce Defect Tracking Integration Project +# +# +# COVERAGE.PY -- COVERAGE TESTING +# +# Gareth Rees, Ravenbrook Limited, 2001-12-04 +# Ned Batchelder, 2004-12-12 +# http://nedbatchelder.com/code/modules/coverage.html +# +# +# 1. INTRODUCTION +# +# This module provides coverage testing for Python code. +# +# The intended readership is all Python developers. +# +# This document is not confidential. +# +# See [GDR 2001-12-04a] for the command-line interface, programmatic +# interface and limitations. See [GDR 2001-12-04b] for requirements and +# design. + +r"""Usage: + +coverage.py -x [-p] MODULE.py [ARG1 ARG2 ...] + Execute module, passing the given command-line arguments, collecting + coverage data. With the -p option, write to a temporary file containing + the machine name and process ID. + +coverage.py -e + Erase collected coverage data. + +coverage.py -c + Collect data from multiple coverage files (as created by -p option above) + and store it into a single file representing the union of the coverage. + +coverage.py -r [-m] [-o dir1,dir2,...] FILE1 FILE2 ... + Report on the statement coverage for the given files. With the -m + option, show line numbers of the statements that weren't executed. + +coverage.py -a [-d dir] [-o dir1,dir2,...] FILE1 FILE2 ... + Make annotated copies of the given files, marking statements that + are executed with > and statements that are missed with !. With + the -d option, make the copies in that directory. Without the -d + option, make each copy in the same directory as the original. + +-o dir,dir2,... + Omit reporting or annotating files when their filename path starts with + a directory listed in the omit list. + e.g. python coverage.py -i -r -o c:\python23,lib\enthought\traits + +Coverage data is saved in the file .coverage by default. Set the +COVERAGE_FILE environment variable to save it somewhere else.""" + +__version__ = "2.6.20060823" # see detailed history at the end of this file. + +import compiler +import compiler.visitor +import os +import re +import string +import sys +import threading +import types +from socket import gethostname + +# 2. IMPLEMENTATION +# +# This uses the "singleton" pattern. +# +# The word "morf" means a module object (from which the source file can +# be deduced by suitable manipulation of the __file__ attribute) or a +# filename. +# +# When we generate a coverage report we have to canonicalize every +# filename in the coverage dictionary just in case it refers to the +# module we are reporting on. It seems a shame to throw away this +# information so the data in the coverage dictionary is transferred to +# the 'cexecuted' dictionary under the canonical filenames. +# +# The coverage dictionary is called "c" and the trace function "t". The +# reason for these short names is that Python looks up variables by name +# at runtime and so execution time depends on the length of variables! +# In the bottleneck of this application it's appropriate to abbreviate +# names to increase speed. + +class StatementFindingAstVisitor(compiler.visitor.ASTVisitor): + def __init__(self, statements, excluded, suite_spots): + compiler.visitor.ASTVisitor.__init__(self) + self.statements = statements + self.excluded = excluded + self.suite_spots = suite_spots + self.excluding_suite = 0 + + def doRecursive(self, node): + self.recordNodeLine(node) + for n in node.getChildNodes(): + self.dispatch(n) + + visitStmt = visitModule = doRecursive + + def doCode(self, node): + if hasattr(node, 'decorators') and node.decorators: + self.dispatch(node.decorators) + self.recordAndDispatch(node.code) + else: + self.doSuite(node, node.code) + + visitFunction = visitClass = doCode + + def getFirstLine(self, node): + # Find the first line in the tree node. + lineno = node.lineno + for n in node.getChildNodes(): + f = self.getFirstLine(n) + if lineno and f: + lineno = min(lineno, f) + else: + lineno = lineno or f + return lineno + + def getLastLine(self, node): + # Find the first line in the tree node. + lineno = node.lineno + for n in node.getChildNodes(): + lineno = max(lineno, self.getLastLine(n)) + return lineno + + def doStatement(self, node): + self.recordLine(self.getFirstLine(node)) + + visitAssert = visitAssign = visitAssTuple = visitDiscard = visitPrint = \ + visitPrintnl = visitRaise = visitSubscript = visitDecorators = \ + doStatement + + def recordNodeLine(self, node): + return self.recordLine(node.lineno) + + def recordLine(self, lineno): + # Returns a bool, whether the line is included or excluded. + if lineno: + # Multi-line tests introducing suites have to get charged to their + # keyword. + if lineno in self.suite_spots: + lineno = self.suite_spots[lineno][0] + # If we're inside an exluded suite, record that this line was + # excluded. + if self.excluding_suite: + self.excluded[lineno] = 1 + return 0 + # If this line is excluded, or suite_spots maps this line to + # another line that is exlcuded, then we're excluded. + elif self.excluded.has_key(lineno) or \ + self.suite_spots.has_key(lineno) and \ + self.excluded.has_key(self.suite_spots[lineno][1]): + return 0 + # Otherwise, this is an executable line. + else: + self.statements[lineno] = 1 + return 1 + return 0 + + default = recordNodeLine + + def recordAndDispatch(self, node): + self.recordNodeLine(node) + self.dispatch(node) + + def doSuite(self, intro, body, exclude=0): + exsuite = self.excluding_suite + if exclude or (intro and not self.recordNodeLine(intro)): + self.excluding_suite = 1 + self.recordAndDispatch(body) + self.excluding_suite = exsuite + + def doPlainWordSuite(self, prevsuite, suite): + # Finding the exclude lines for else's is tricky, because they aren't + # present in the compiler parse tree. Look at the previous suite, + # and find its last line. If any line between there and the else's + # first line are excluded, then we exclude the else. + lastprev = self.getLastLine(prevsuite) + firstelse = self.getFirstLine(suite) + for l in range(lastprev+1, firstelse): + if self.suite_spots.has_key(l): + self.doSuite(None, suite, exclude=self.excluded.has_key(l)) + break + else: + self.doSuite(None, suite) + + def doElse(self, prevsuite, node): + if node.else_: + self.doPlainWordSuite(prevsuite, node.else_) + + def visitFor(self, node): + self.doSuite(node, node.body) + self.doElse(node.body, node) + + def visitIf(self, node): + # The first test has to be handled separately from the rest. + # The first test is credited to the line with the "if", but the others + # are credited to the line with the test for the elif. + self.doSuite(node, node.tests[0][1]) + for t, n in node.tests[1:]: + self.doSuite(t, n) + self.doElse(node.tests[-1][1], node) + + def visitWhile(self, node): + self.doSuite(node, node.body) + self.doElse(node.body, node) + + def visitTryExcept(self, node): + self.doSuite(node, node.body) + for i in range(len(node.handlers)): + a, b, h = node.handlers[i] + if not a: + # It's a plain "except:". Find the previous suite. + if i > 0: + prev = node.handlers[i-1][2] + else: + prev = node.body + self.doPlainWordSuite(prev, h) + else: + self.doSuite(a, h) + self.doElse(node.handlers[-1][2], node) + + def visitTryFinally(self, node): + self.doSuite(node, node.body) + self.doPlainWordSuite(node.body, node.final) + + def visitGlobal(self, node): + # "global" statements don't execute like others (they don't call the + # trace function), so don't record their line numbers. + pass + +the_coverage = None + +class CoverageException(Exception): pass + +class coverage: + # Name of the cache file (unless environment variable is set). + cache_default = ".coverage" + + # Environment variable naming the cache file. + cache_env = "COVERAGE_FILE" + + # A dictionary with an entry for (Python source file name, line number + # in that file) if that line has been executed. + c = {} + + # A map from canonical Python source file name to a dictionary in + # which there's an entry for each line number that has been + # executed. + cexecuted = {} + + # Cache of results of calling the analysis2() method, so that you can + # specify both -r and -a without doing double work. + analysis_cache = {} + + # Cache of results of calling the canonical_filename() method, to + # avoid duplicating work. + canonical_filename_cache = {} + + def __init__(self): + global the_coverage + if the_coverage: + raise CoverageException, "Only one coverage object allowed." + self.usecache = 1 + self.cache = None + self.exclude_re = '' + self.nesting = 0 + self.cstack = [] + self.xstack = [] + self.relative_dir = os.path.normcase(os.path.abspath(os.curdir)+os.path.sep) + + # t(f, x, y). This method is passed to sys.settrace as a trace function. + # See [van Rossum 2001-07-20b, 9.2] for an explanation of sys.settrace and + # the arguments and return value of the trace function. + # See [van Rossum 2001-07-20a, 3.2] for a description of frame and code + # objects. + + def t(self, f, w, a): #pragma: no cover + if w == 'line': + self.c[(f.f_code.co_filename, f.f_lineno)] = 1 + for c in self.cstack: + c[(f.f_code.co_filename, f.f_lineno)] = 1 + return self.t + + def help(self, error=None): + if error: + print error + print + print __doc__ + sys.exit(1) + + def command_line(self, argv, help=None): + import getopt + help = help or self.help + settings = {} + optmap = { + '-a': 'annotate', + '-c': 'collect', + '-d:': 'directory=', + '-e': 'erase', + '-h': 'help', + '-i': 'ignore-errors', + '-m': 'show-missing', + '-p': 'parallel-mode', + '-r': 'report', + '-x': 'execute', + '-o:': 'omit=', + } + short_opts = string.join(map(lambda o: o[1:], optmap.keys()), '') + long_opts = optmap.values() + options, args = getopt.getopt(argv, short_opts, long_opts) + for o, a in options: + if optmap.has_key(o): + settings[optmap[o]] = 1 + elif optmap.has_key(o + ':'): + settings[optmap[o + ':']] = a + elif o[2:] in long_opts: + settings[o[2:]] = 1 + elif o[2:] + '=' in long_opts: + settings[o[2:]+'='] = a + else: #pragma: no cover + pass # Can't get here, because getopt won't return anything unknown. + + if settings.get('help'): + help() + + for i in ['erase', 'execute']: + for j in ['annotate', 'report', 'collect']: + if settings.get(i) and settings.get(j): + help("You can't specify the '%s' and '%s' " + "options at the same time." % (i, j)) + + args_needed = (settings.get('execute') + or settings.get('annotate') + or settings.get('report')) + action = (settings.get('erase') + or settings.get('collect') + or args_needed) + if not action: + help("You must specify at least one of -e, -x, -c, -r, or -a.") + if not args_needed and args: + help("Unexpected arguments: %s" % " ".join(args)) + + self.get_ready(settings.get('parallel-mode')) + self.exclude('#pragma[: ]+[nN][oO] [cC][oO][vV][eE][rR]') + + if settings.get('erase'): + self.erase() + if settings.get('execute'): + if not args: + help("Nothing to do.") + sys.argv = args + self.start() + import __main__ + sys.path[0] = os.path.dirname(sys.argv[0]) + execfile(sys.argv[0], __main__.__dict__) + if settings.get('collect'): + self.collect() + if not args: + args = self.cexecuted.keys() + + ignore_errors = settings.get('ignore-errors') + show_missing = settings.get('show-missing') + directory = settings.get('directory=') + + omit = settings.get('omit=') + if omit is not None: + omit = omit.split(',') + else: + omit = [] + + if settings.get('report'): + self.report(args, show_missing, ignore_errors, omit_prefixes=omit) + if settings.get('annotate'): + self.annotate(args, directory, ignore_errors, omit_prefixes=omit) + + def use_cache(self, usecache, cache_file=None): + self.usecache = usecache + if cache_file and not self.cache: + self.cache_default = cache_file + + def get_ready(self, parallel_mode=False): + if self.usecache and not self.cache: + self.cache = os.environ.get(self.cache_env, self.cache_default) + if parallel_mode: + self.cache += "." + gethostname() + "." + str(os.getpid()) + self.restore() + self.analysis_cache = {} + + def start(self, parallel_mode=False): + self.get_ready(parallel_mode) + if self.nesting == 0: #pragma: no cover + sys.settrace(self.t) + if hasattr(threading, 'settrace'): + threading.settrace(self.t) + self.nesting += 1 + + def stop(self): + self.nesting -= 1 + if self.nesting == 0: #pragma: no cover + sys.settrace(None) + if hasattr(threading, 'settrace'): + threading.settrace(None) + + def erase(self): + self.c = {} + self.analysis_cache = {} + self.cexecuted = {} + if self.cache and os.path.exists(self.cache): + os.remove(self.cache) + self.exclude_re = "" + + def exclude(self, re): + if self.exclude_re: + self.exclude_re += "|" + self.exclude_re += "(" + re + ")" + + def begin_recursive(self): + self.cstack.append(self.c) + self.xstack.append(self.exclude_re) + + def end_recursive(self): + self.c = self.cstack.pop() + self.exclude_re = self.xstack.pop() + + # save(). Save coverage data to the coverage cache. + + def save(self): + if self.usecache and self.cache: + self.canonicalize_filenames() + cache = open(self.cache, 'wb') + import marshal + marshal.dump(self.cexecuted, cache) + cache.close() + + # restore(). Restore coverage data from the coverage cache (if it exists). + + def restore(self): + self.c = {} + self.cexecuted = {} + assert self.usecache + if os.path.exists(self.cache): + self.cexecuted = self.restore_file(self.cache) + + def restore_file(self, file_name): + try: + cache = open(file_name, 'rb') + import marshal + cexecuted = marshal.load(cache) + cache.close() + if isinstance(cexecuted, types.DictType): + return cexecuted + else: + return {} + except: + return {} + + # collect(). Collect data in multiple files produced by parallel mode + + def collect(self): + cache_dir, local = os.path.split(self.cache) + for file in os.listdir(cache_dir): + if not file.startswith(local): + continue + + full_path = os.path.join(cache_dir, file) + cexecuted = self.restore_file(full_path) + self.merge_data(cexecuted) + + def merge_data(self, new_data): + for file_name, file_data in new_data.items(): + if self.cexecuted.has_key(file_name): + self.merge_file_data(self.cexecuted[file_name], file_data) + else: + self.cexecuted[file_name] = file_data + + def merge_file_data(self, cache_data, new_data): + for line_number in new_data.keys(): + if not cache_data.has_key(line_number): + cache_data[line_number] = new_data[line_number] + + # canonical_filename(filename). Return a canonical filename for the + # file (that is, an absolute path with no redundant components and + # normalized case). See [GDR 2001-12-04b, 3.3]. + + def canonical_filename(self, filename): + if not self.canonical_filename_cache.has_key(filename): + f = filename + if os.path.isabs(f) and not os.path.exists(f): + f = os.path.basename(f) + if not os.path.isabs(f): + for path in [os.curdir] + sys.path: + g = os.path.join(path, f) + if os.path.exists(g): + f = g + break + cf = os.path.normcase(os.path.abspath(f)) + self.canonical_filename_cache[filename] = cf + return self.canonical_filename_cache[filename] + + # canonicalize_filenames(). Copy results from "c" to "cexecuted", + # canonicalizing filenames on the way. Clear the "c" map. + + def canonicalize_filenames(self): + for filename, lineno in self.c.keys(): + f = self.canonical_filename(filename) + if not self.cexecuted.has_key(f): + self.cexecuted[f] = {} + self.cexecuted[f][lineno] = 1 + self.c = {} + + # morf_filename(morf). Return the filename for a module or file. + + def morf_filename(self, morf): + if isinstance(morf, types.ModuleType): + if not hasattr(morf, '__file__'): + raise CoverageException, "Module has no __file__ attribute." + file = morf.__file__ + else: + file = morf + return self.canonical_filename(file) + + # analyze_morf(morf). Analyze the module or filename passed as + # the argument. If the source code can't be found, raise an error. + # Otherwise, return a tuple of (1) the canonical filename of the + # source code for the module, (2) a list of lines of statements + # in the source code, and (3) a list of lines of excluded statements. + + def analyze_morf(self, morf): + if self.analysis_cache.has_key(morf): + return self.analysis_cache[morf] + filename = self.morf_filename(morf) + ext = os.path.splitext(filename)[1] + if ext == '.pyc': + if not os.path.exists(filename[0:-1]): + raise CoverageException, ("No source for compiled code '%s'." + % filename) + filename = filename[0:-1] + elif ext != '.py': + raise CoverageException, "File '%s' not Python source." % filename + source = open(filename, 'r') + lines, excluded_lines = self.find_executable_statements( + source.read(), exclude=self.exclude_re + ) + source.close() + result = filename, lines, excluded_lines + self.analysis_cache[morf] = result + return result + + def get_suite_spots(self, tree, spots): + import symbol, token + for i in range(1, len(tree)): + if type(tree[i]) == type(()): + if tree[i][0] == symbol.suite: + # Found a suite, look back for the colon and keyword. + lineno_colon = lineno_word = None + for j in range(i-1, 0, -1): + if tree[j][0] == token.COLON: + lineno_colon = tree[j][2] + elif tree[j][0] == token.NAME: + if tree[j][1] == 'elif': + # Find the line number of the first non-terminal + # after the keyword. + t = tree[j+1] + while t and token.ISNONTERMINAL(t[0]): + t = t[1] + if t: + lineno_word = t[2] + else: + lineno_word = tree[j][2] + break + elif tree[j][0] == symbol.except_clause: + # "except" clauses look like: + # ('except_clause', ('NAME', 'except', lineno), ...) + if tree[j][1][0] == token.NAME: + lineno_word = tree[j][1][2] + break + if lineno_colon and lineno_word: + # Found colon and keyword, mark all the lines + # between the two with the two line numbers. + for l in range(lineno_word, lineno_colon+1): + spots[l] = (lineno_word, lineno_colon) + self.get_suite_spots(tree[i], spots) + + def find_executable_statements(self, text, exclude=None): + # Find lines which match an exclusion pattern. + excluded = {} + suite_spots = {} + if exclude: + reExclude = re.compile(exclude) + lines = text.split('\n') + for i in range(len(lines)): + if reExclude.search(lines[i]): + excluded[i+1] = 1 + + import parser + tree = parser.suite(text+'\n\n').totuple(1) + self.get_suite_spots(tree, suite_spots) + + # Use the compiler module to parse the text and find the executable + # statements. We add newlines to be impervious to final partial lines. + statements = {} + ast = compiler.parse(text+'\n\n') + visitor = StatementFindingAstVisitor(statements, excluded, suite_spots) + compiler.walk(ast, visitor, walker=visitor) + + lines = statements.keys() + lines.sort() + excluded_lines = excluded.keys() + excluded_lines.sort() + return lines, excluded_lines + + # format_lines(statements, lines). Format a list of line numbers + # for printing by coalescing groups of lines as long as the lines + # represent consecutive statements. This will coalesce even if + # there are gaps between statements, so if statements = + # [1,2,3,4,5,10,11,12,13,14] and lines = [1,2,5,10,11,13,14] then + # format_lines will return "1-2, 5-11, 13-14". + + def format_lines(self, statements, lines): + pairs = [] + i = 0 + j = 0 + start = None + pairs = [] + while i < len(statements) and j < len(lines): + if statements[i] == lines[j]: + if start == None: + start = lines[j] + end = lines[j] + j = j + 1 + elif start: + pairs.append((start, end)) + start = None + i = i + 1 + if start: + pairs.append((start, end)) + def stringify(pair): + start, end = pair + if start == end: + return "%d" % start + else: + return "%d-%d" % (start, end) + return string.join(map(stringify, pairs), ", ") + + # Backward compatibility with version 1. + def analysis(self, morf): + f, s, _, m, mf = self.analysis2(morf) + return f, s, m, mf + + def analysis2(self, morf): + filename, statements, excluded = self.analyze_morf(morf) + self.canonicalize_filenames() + if not self.cexecuted.has_key(filename): + self.cexecuted[filename] = {} + missing = [] + for line in statements: + if not self.cexecuted[filename].has_key(line): + missing.append(line) + return (filename, statements, excluded, missing, + self.format_lines(statements, missing)) + + def relative_filename(self, filename): + """ Convert filename to relative filename from self.relative_dir. + """ + return filename.replace(self.relative_dir, "") + + def morf_name(self, morf): + """ Return the name of morf as used in report. + """ + if isinstance(morf, types.ModuleType): + return morf.__name__ + else: + return self.relative_filename(os.path.splitext(morf)[0]) + + def filter_by_prefix(self, morfs, omit_prefixes): + """ Return list of morfs where the morf name does not begin + with any one of the omit_prefixes. + """ + filtered_morfs = [] + for morf in morfs: + for prefix in omit_prefixes: + if self.morf_name(morf).startswith(prefix): + break + else: + filtered_morfs.append(morf) + + return filtered_morfs + + def morf_name_compare(self, x, y): + return cmp(self.morf_name(x), self.morf_name(y)) + + def report(self, morfs, show_missing=1, ignore_errors=0, file=None, omit_prefixes=[]): + if not isinstance(morfs, types.ListType): + morfs = [morfs] + morfs = self.filter_by_prefix(morfs, omit_prefixes) + morfs.sort(self.morf_name_compare) + + max_name = max([5,] + map(len, map(self.morf_name, morfs))) + fmt_name = "%%- %ds " % max_name + fmt_err = fmt_name + "%s: %s" + header = fmt_name % "Name" + " Stmts Exec Cover" + fmt_coverage = fmt_name + "% 6d % 6d % 5d%%" + if show_missing: + header = header + " Missing" + fmt_coverage = fmt_coverage + " %s" + if not file: + file = sys.stdout + print >>file, header + print >>file, "-" * len(header) + total_statements = 0 + total_executed = 0 + for morf in morfs: + name = self.morf_name(morf) + try: + _, statements, _, missing, readable = self.analysis2(morf) + n = len(statements) + m = n - len(missing) + if n > 0: + pc = 100.0 * m / n + else: + pc = 100.0 + args = (name, n, m, pc) + if show_missing: + args = args + (readable,) + print >>file, fmt_coverage % args + total_statements = total_statements + n + total_executed = total_executed + m + except KeyboardInterrupt: #pragma: no cover + raise + except: + if not ignore_errors: + type, msg = sys.exc_info()[0:2] + print >>file, fmt_err % (name, type, msg) + if len(morfs) > 1: + print >>file, "-" * len(header) + if total_statements > 0: + pc = 100.0 * total_executed / total_statements + else: + pc = 100.0 + args = ("TOTAL", total_statements, total_executed, pc) + if show_missing: + args = args + ("",) + print >>file, fmt_coverage % args + + # annotate(morfs, ignore_errors). + + blank_re = re.compile(r"\s*(#|$)") + else_re = re.compile(r"\s*else\s*:\s*(#|$)") + + def annotate(self, morfs, directory=None, ignore_errors=0, omit_prefixes=[]): + morfs = self.filter_by_prefix(morfs, omit_prefixes) + for morf in morfs: + try: + filename, statements, excluded, missing, _ = self.analysis2(morf) + self.annotate_file(filename, statements, excluded, missing, directory) + except KeyboardInterrupt: + raise + except: + if not ignore_errors: + raise + + def annotate_file(self, filename, statements, excluded, missing, directory=None): + source = open(filename, 'r') + if directory: + dest_file = os.path.join(directory, + os.path.basename(filename) + + ',cover') + else: + dest_file = filename + ',cover' + dest = open(dest_file, 'w') + lineno = 0 + i = 0 + j = 0 + covered = 1 + while 1: + line = source.readline() + if line == '': + break + lineno = lineno + 1 + while i < len(statements) and statements[i] < lineno: + i = i + 1 + while j < len(missing) and missing[j] < lineno: + j = j + 1 + if i < len(statements) and statements[i] == lineno: + covered = j >= len(missing) or missing[j] > lineno + if self.blank_re.match(line): + dest.write(' ') + elif self.else_re.match(line): + # Special logic for lines containing only 'else:'. + # See [GDR 2001-12-04b, 3.2]. + if i >= len(statements) and j >= len(missing): + dest.write('! ') + elif i >= len(statements) or j >= len(missing): + dest.write('> ') + elif statements[i] == missing[j]: + dest.write('! ') + else: + dest.write('> ') + elif lineno in excluded: + dest.write('- ') + elif covered: + dest.write('> ') + else: + dest.write('! ') + dest.write(line) + source.close() + dest.close() + +# Singleton object. +the_coverage = coverage() + +# Module functions call methods in the singleton object. +def use_cache(*args, **kw): return the_coverage.use_cache(*args, **kw) +def start(*args, **kw): return the_coverage.start(*args, **kw) +def stop(*args, **kw): return the_coverage.stop(*args, **kw) +def erase(*args, **kw): return the_coverage.erase(*args, **kw) +def begin_recursive(*args, **kw): return the_coverage.begin_recursive(*args, **kw) +def end_recursive(*args, **kw): return the_coverage.end_recursive(*args, **kw) +def exclude(*args, **kw): return the_coverage.exclude(*args, **kw) +def analysis(*args, **kw): return the_coverage.analysis(*args, **kw) +def analysis2(*args, **kw): return the_coverage.analysis2(*args, **kw) +def report(*args, **kw): return the_coverage.report(*args, **kw) +def annotate(*args, **kw): return the_coverage.annotate(*args, **kw) +def annotate_file(*args, **kw): return the_coverage.annotate_file(*args, **kw) + +# Save coverage data when Python exits. (The atexit module wasn't +# introduced until Python 2.0, so use sys.exitfunc when it's not +# available.) +try: + import atexit + atexit.register(the_coverage.save) +except ImportError: + sys.exitfunc = the_coverage.save + +# Command-line interface. +if __name__ == '__main__': + the_coverage.command_line(sys.argv[1:]) + + +# A. REFERENCES +# +# [GDR 2001-12-04a] "Statement coverage for Python"; Gareth Rees; +# Ravenbrook Limited; 2001-12-04; +# . +# +# [GDR 2001-12-04b] "Statement coverage for Python: design and +# analysis"; Gareth Rees; Ravenbrook Limited; 2001-12-04; +# . +# +# [van Rossum 2001-07-20a] "Python Reference Manual (releae 2.1.1)"; +# Guide van Rossum; 2001-07-20; +# . +# +# [van Rossum 2001-07-20b] "Python Library Reference"; Guido van Rossum; +# 2001-07-20; . +# +# +# B. DOCUMENT HISTORY +# +# 2001-12-04 GDR Created. +# +# 2001-12-06 GDR Added command-line interface and source code +# annotation. +# +# 2001-12-09 GDR Moved design and interface to separate documents. +# +# 2001-12-10 GDR Open cache file as binary on Windows. Allow +# simultaneous -e and -x, or -a and -r. +# +# 2001-12-12 GDR Added command-line help. Cache analysis so that it +# only needs to be done once when you specify -a and -r. +# +# 2001-12-13 GDR Improved speed while recording. Portable between +# Python 1.5.2 and 2.1.1. +# +# 2002-01-03 GDR Module-level functions work correctly. +# +# 2002-01-07 GDR Update sys.path when running a file with the -x option, +# so that it matches the value the program would get if it were run on +# its own. +# +# 2004-12-12 NMB Significant code changes. +# - Finding executable statements has been rewritten so that docstrings and +# other quirks of Python execution aren't mistakenly identified as missing +# lines. +# - Lines can be excluded from consideration, even entire suites of lines. +# - The filesystem cache of covered lines can be disabled programmatically. +# - Modernized the code. +# +# 2004-12-14 NMB Minor tweaks. Return 'analysis' to its original behavior +# and add 'analysis2'. Add a global for 'annotate', and factor it, adding +# 'annotate_file'. +# +# 2004-12-31 NMB Allow for keyword arguments in the module global functions. +# Thanks, Allen. +# +# 2005-12-02 NMB Call threading.settrace so that all threads are measured. +# Thanks Martin Fuzzey. Add a file argument to report so that reports can be +# captured to a different destination. +# +# 2005-12-03 NMB coverage.py can now measure itself. +# +# 2005-12-04 NMB Adapted Greg Rogers' patch for using relative filenames, +# and sorting and omitting files to report on. +# +# 2006-07-23 NMB Applied Joseph Tate's patch for function decorators. +# +# 2006-08-21 NMB Applied Sigve Tjora and Mark van der Wal's fixes for argument +# handling. +# +# 2006-08-22 NMB Applied Geoff Bache's parallel mode patch. +# +# 2006-08-23 NMB Refactorings to improve testability. Fixes to command-line +# logic for parallel mode and collect. + +# C. COPYRIGHT AND LICENCE +# +# Copyright 2001 Gareth Rees. All rights reserved. +# Copyright 2004-2006 Ned Batchelder. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the +# distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +# DAMAGE. +# +# $Id: coverage.py 47 2006-08-24 01:08:48Z Ned $ --- /dev/null +++ jcl-0.1b2/Makefile @@ -0,0 +1,32 @@ +PYTHON=`which python` +DESTDIR=/ +BUILDIR=$(CURDIR)/debian/jcl +PROJECT=jcl +VERSION=0.1b2 + +all: + @echo "make source - Create source package" + @echo "make install - Install on local system" + @echo "make buildrpm - Generate a rpm package" + @echo "make builddeb - Generate a deb package" + @echo "make clean - Get rid of scratch and byte files" + +source: + $(PYTHON) setup.py sdist $(COMPILE) + +install: + $(PYTHON) setup.py install --root $(DESTDIR) $(COMPILE) + +buildrpm: + $(PYTHON) setup.py bdist_rpm --post-install=rpm/postinstall --pre-uninstall=rpm/preuninstall + +builddeb: + $(PYTHON) setup.py sdist $(COMPILE) --dist-dir=../ + rename -f 's/$(PROJECT)-(.*)\.tar\.gz/$(PROJECT)_$$1\.orig\.tar\.gz/' ../* + dpkg-buildpackage -i -I -rfakeroot + +clean: + $(PYTHON) setup.py clean + fakeroot $(MAKE) -f $(CURDIR)/debian/rules clean + rm -rf build/ MANIFEST + find . -name '*.pyc' -delete --- /dev/null +++ jcl-0.1b2/run_tests.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- +## +## run_tests.py +## Login : David Rousselie +## Started on Wed Aug 9 21:37:35 2006 David Rousselie +## $Id$ +## +## Copyright (C) 2006 David Rousselie +## This program is free software; you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation; either version 2 of the License, or +## (at your option) any later version. +## +## This program is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with this program; if not, write to the Free Software +## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +## + +import coverage +coverage.erase() +coverage.start() + +import logging +import unittest + +import sys +sys.path.append("src") +reload(sys) +sys.setdefaultencoding('utf8') +del sys.setdefaultencoding + +import jcl.tests +import jcl.jabber.tests + +def suite(): + return jcl.tests.suite() + +if __name__ == '__main__': + class MyTestProgram(unittest.TestProgram): + def runTests(self): + """run tests but do not exit after""" + self.testRunner = unittest.TextTestRunner(verbosity=self.verbosity) + self.testRunner.run(self.test) + + logger = logging.getLogger() + logger.addHandler(logging.StreamHandler()) + logger.setLevel(logging.CRITICAL) + try: + print "Trying to launch test with testoob" + import testoob + testoob.main(defaultTest='suite') + except ImportError: + print "Falling back to standard unittest" + MyTestProgram(defaultTest='suite') + +coverage.report(["src/jcl/__init__.py", + "src/jcl/lang.py", + "src/jcl/runner.py", + "src/jcl/error.py", + "src/jcl/jabber/__init__.py", + "src/jcl/jabber/component.py", + "src/jcl/jabber/command.py", + "src/jcl/jabber/feeder.py", + "src/jcl/jabber/message.py", + "src/jcl/jabber/presence.py", + "src/jcl/jabber/disco.py", + "src/jcl/jabber/register.py", + "src/jcl/model/__init__.py", + "src/jcl/model/account.py"]) --- /dev/null +++ jcl-0.1b2/COPYING @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + --- /dev/null +++ jcl-0.1b2/release @@ -0,0 +1,6 @@ +export DEBFULLNAME=David Rousselie +export DEBEMAIL=dax@happycoders.org +#debchange --create --package jcl -v 0.1b2 +debchange -v 0.1b2 + +debchange -r # UNRELEASED -> released --- /dev/null +++ jcl-0.1b2/doc/README @@ -0,0 +1,5 @@ +Jabber Component Library Documentation +====================================== + +TODO + --- /dev/null +++ jcl-0.1b2/sqlobject_history/2008-11-08/PresenceAccount_sqlite.sql @@ -0,0 +1,13 @@ +-- Exported definition from 2008-11-09T13:58:16 +-- Class jcl.model.account.PresenceAccount +-- Database: sqlite +CREATE TABLE presence_account ( + id INTEGER PRIMARY KEY, + chat_action INT, + online_action INT, + away_action INT, + xa_action INT, + dnd_action INT, + offline_action INT, + child_name VARCHAR (255) +) --- /dev/null +++ jcl-0.1b2/sqlobject_history/2008-11-08/User_sqlite.sql @@ -0,0 +1,9 @@ +-- Exported definition from 2008-11-09T13:58:16 +-- Class jcl.model.account.User +-- Database: sqlite +CREATE TABLE user ( + id INTEGER PRIMARY KEY, + jid TEXT, + has_received_motd BOOLEAN, + child_name VARCHAR (255) +) --- /dev/null +++ jcl-0.1b2/sqlobject_history/2008-11-08/LegacyJID_sqlite.sql @@ -0,0 +1,10 @@ +-- Exported definition from 2008-11-09T13:58:16 +-- Class jcl.model.account.LegacyJID +-- Database: sqlite +CREATE TABLE legacy_j_id ( + id INTEGER PRIMARY KEY, + legacy_address TEXT, + jid TEXT, + account_id INT CONSTRAINT account_id_exists REFERENCES account(id) , + child_name VARCHAR (255) +) --- /dev/null +++ jcl-0.1b2/sqlobject_history/2008-11-08/Account_sqlite.sql @@ -0,0 +1,14 @@ +-- Exported definition from 2008-11-09T13:58:16 +-- Class jcl.model.account.Account +-- Database: sqlite +CREATE TABLE account ( + id INTEGER PRIMARY KEY, + name TEXT, + jid TEXT, + status TEXT, + error TEXT, + enabled BOOLEAN, + lastlogin TIMESTAMP, + user_id INT CONSTRAINT user_id_exists REFERENCES user(id) , + child_name VARCHAR (255) +) --- /dev/null +++ jcl-0.1b2/sqlobject_history/2008-11-08/upgrade_sqlite_2008-11-09.sql @@ -0,0 +1,30 @@ +alter table user rename to user_table; +begin transaction; +CREATE TEMPORARY TABLE account_backup ( + id INTEGER PRIMARY KEY, + name TEXT, + jid TEXT, + status TEXT, + error TEXT, + enabled BOOLEAN, + lastlogin TIMESTAMP, + user_id INT CONSTRAINT user_id_exists REFERENCES user_table(id) , + child_name VARCHAR (255) +); +INSERT INTO account_backup SELECT * FROM account; +DROP TABLE account; +CREATE TABLE account ( + id INTEGER PRIMARY KEY, + name TEXT, + jid TEXT, + status TEXT, + error TEXT, + enabled BOOLEAN, + lastlogin TIMESTAMP, + user_id INT CONSTRAINT user_id_exists REFERENCES user_table(id) , + child_name VARCHAR (255) +); +INSERT INTO account SELECT * FROM account_backup; +DROP TABLE account_backup; +commit; + --- /dev/null +++ jcl-0.1b2/sqlobject_history/2009-02-17/PresenceAccount_sqlite.sql @@ -0,0 +1,13 @@ +-- Exported definition from 2009-02-17T13:58:34 +-- Class jcl.model.account.PresenceAccount +-- Database: sqlite +CREATE TABLE presence_account ( + id INTEGER PRIMARY KEY, + chat_action INT, + online_action INT, + away_action INT, + xa_action INT, + dnd_action INT, + offline_action INT, + child_name VARCHAR (255) +); --- /dev/null +++ jcl-0.1b2/sqlobject_history/2009-02-17/User_sqlite.sql @@ -0,0 +1,9 @@ +-- Exported definition from 2009-02-17T13:58:34 +-- Class jcl.model.account.User +-- Database: sqlite +CREATE TABLE user_table ( + id INTEGER PRIMARY KEY, + jid TEXT, + has_received_motd BOOLEAN, + child_name VARCHAR (255) +); --- /dev/null +++ jcl-0.1b2/sqlobject_history/2009-02-17/LegacyJID_sqlite.sql @@ -0,0 +1,10 @@ +-- Exported definition from 2009-02-17T13:58:34 +-- Class jcl.model.account.LegacyJID +-- Database: sqlite +CREATE TABLE legacy_j_id ( + id INTEGER PRIMARY KEY, + legacy_address TEXT, + jid TEXT, + account_id INT CONSTRAINT account_id_exists REFERENCES account(id) , + child_name VARCHAR (255) +); --- /dev/null +++ jcl-0.1b2/sqlobject_history/2009-02-17/Account_sqlite.sql @@ -0,0 +1,14 @@ +-- Exported definition from 2009-02-17T13:58:34 +-- Class jcl.model.account.Account +-- Database: sqlite +CREATE TABLE account ( + id INTEGER PRIMARY KEY, + name TEXT, + jid TEXT, + status TEXT, + error TEXT, + enabled BOOLEAN, + lastlogin TIMESTAMP, + user_table_id INT CONSTRAINT user_table_id_exists REFERENCES user_table(id), + child_name VARCHAR (255) +); --- /dev/null +++ jcl-0.1b2/sqlobject_history/2008-11-09/PresenceAccount_sqlite.sql @@ -0,0 +1,13 @@ +-- Exported definition from 2008-11-09T13:58:34 +-- Class jcl.model.account.PresenceAccount +-- Database: sqlite +CREATE TABLE presence_account ( + id INTEGER PRIMARY KEY, + chat_action INT, + online_action INT, + away_action INT, + xa_action INT, + dnd_action INT, + offline_action INT, + child_name VARCHAR (255) +); --- /dev/null +++ jcl-0.1b2/sqlobject_history/2008-11-09/User_sqlite.sql @@ -0,0 +1,9 @@ +-- Exported definition from 2008-11-09T13:58:34 +-- Class jcl.model.account.User +-- Database: sqlite +CREATE TABLE user_table ( + id INTEGER PRIMARY KEY, + jid TEXT, + has_received_motd BOOLEAN, + child_name VARCHAR (255) +); --- /dev/null +++ jcl-0.1b2/sqlobject_history/2008-11-09/upgrade_sqlite_2009-02-17.sql @@ -0,0 +1,29 @@ +begin transaction; +CREATE TEMPORARY TABLE account_backup ( + id INTEGER PRIMARY KEY, + name TEXT, + jid TEXT, + status TEXT, + error TEXT, + enabled BOOLEAN, + lastlogin TIMESTAMP, + user_id INT CONSTRAINT user_id_exists REFERENCES user_table(id) , + child_name VARCHAR (255) +); +INSERT INTO account_backup SELECT * FROM account; +DROP TABLE account; +CREATE TABLE account ( + id INTEGER PRIMARY KEY, + name TEXT, + jid TEXT, + status TEXT, + error TEXT, + enabled BOOLEAN, + lastlogin TIMESTAMP, + user_table_id INT CONSTRAINT user_table_id_exists REFERENCES user_table(id), + child_name VARCHAR (255) +); +INSERT INTO account SELECT * FROM account_backup; +DROP TABLE account_backup; +commit; + --- /dev/null +++ jcl-0.1b2/sqlobject_history/2008-11-09/LegacyJID_sqlite.sql @@ -0,0 +1,10 @@ +-- Exported definition from 2008-11-09T13:58:34 +-- Class jcl.model.account.LegacyJID +-- Database: sqlite +CREATE TABLE legacy_j_id ( + id INTEGER PRIMARY KEY, + legacy_address TEXT, + jid TEXT, + account_id INT CONSTRAINT account_id_exists REFERENCES account(id) , + child_name VARCHAR (255) +); --- /dev/null +++ jcl-0.1b2/sqlobject_history/2008-11-09/Account_sqlite.sql @@ -0,0 +1,14 @@ +-- Exported definition from 2008-11-09T13:58:34 +-- Class jcl.model.account.Account +-- Database: sqlite +CREATE TABLE account ( + id INTEGER PRIMARY KEY, + name TEXT, + jid TEXT, + status TEXT, + error TEXT, + enabled BOOLEAN, + lastlogin TIMESTAMP, + user_id INT CONSTRAINT user_id_exists REFERENCES user_table(id) , + child_name VARCHAR (255) +); --- /dev/null +++ jcl-0.1b2/conf/jcl.conf @@ -0,0 +1,29 @@ +[jabber] +server: localhost +port: 5347 +secret: secret +service_jid: jcl.localhost +#supported language: en, fr (See src/jcl/lang.py to add more) +language: en + +[db] +#SQLite config +type: sqlite +host: +name: /var/spool/jabber/jcl.db +#Mysql config +#type: mysql +#host: root:pass@localhost +#name: /jcl +#db_url: %(type)s://%(host)s%(name)s?debug=1&debugThreading=1 +db_url: %(type)s://%(host)s%(name)s + +[component] +pid_file: /var/run/jabber/jcl.pid +#motd: "Message of the day" +welcome_message: "Welcome to JCL" +admins: admin1@domain.com, admin2@domain.com +log_file: /var/log/jabber/jcl.log + +[vcard] +url: http://people.happycoders.org/dax/projects/jcl --- /dev/null +++ jcl-0.1b2/src/jcl/tests/runner.py @@ -0,0 +1,283 @@ +## +## runner.py +## Login : David Rousselie +## Started on Fri May 18 13:43:37 2007 David Rousselie +## $Id$ +## +## Copyright (C) 2007 David Rousselie +## This program is free software; you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation; either version 2 of the License, or +## (at your option) any later version. +## +## This program is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with this program; if not, write to the Free Software +## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +## + +import unittest +import sys +import os +import tempfile +import logging + +from sqlobject import * + +import jcl +from jcl.runner import JCLRunner +import jcl.model as model +from jcl.model.account import Account, PresenceAccount, User, LegacyJID +from jcl.jabber.component import JCLComponent + +if sys.platform == "win32": + DB_DIR = "/c|/temp/" +else: + DB_DIR = "/tmp/" + +class JCLRunner_TestCase(unittest.TestCase): + def setUp(self): + self.runner = JCLRunner("JCL", jcl.version) + + def tearDown(self): + self.runner = None + sys.argv = [""] + + def test_configure_default(self): + self.runner.configure() + self.assertEquals(self.runner.config_file, "jcl.conf") + self.assertEquals(self.runner.server, "localhost") + self.assertEquals(self.runner.port, 5347) + self.assertEquals(self.runner.secret, "secret") + self.assertEquals(self.runner.service_jid, "jcl.localhost") + self.assertEquals(self.runner.language, "en") + self.assertEquals(self.runner.db_url, "sqlite:///var/spool/jabber/jcl.db") + self.assertEquals(self.runner.pid_file, "/var/run/jabber/jcl.pid") + self.assertFalse(self.runner.debug) + self.assertEquals(self.runner.logger.getEffectiveLevel(), + logging.CRITICAL) + + def test_configure_configfile(self): + self.runner.config_file = "src/jcl/tests/jcl.conf" + self.runner.configure() + self.assertEquals(self.runner.server, "test_localhost") + self.assertEquals(self.runner.port, 42) + self.assertEquals(self.runner.secret, "test_secret") + self.assertEquals(self.runner.service_jid, "test_jcl.localhost") + self.assertEquals(self.runner.language, "test_en") + self.assertEquals(self.runner.db_url, "test_sqlite://root@localhost/var/spool/jabber/test_jcl.db") + self.assertEquals(self.runner.pid_file, "/var/run/jabber/test_jcl.pid") + self.assertFalse(self.runner.debug) + self.assertEquals(self.runner.logger.getEffectiveLevel(), + logging.CRITICAL) + + def test_configure_uncomplete_configfile(self): + self.runner.config_file = "src/jcl/tests/uncomplete_jcl.conf" + self.runner.configure() + self.assertEquals(self.runner.server, "test_localhost") + self.assertEquals(self.runner.port, 42) + self.assertEquals(self.runner.secret, "test_secret") + self.assertEquals(self.runner.service_jid, "test_jcl.localhost") + self.assertEquals(self.runner.language, "test_en") + self.assertEquals(self.runner.db_url, "test_sqlite://root@localhost/var/spool/jabber/test_jcl.db") + # pid_file is not in uncmplete_jcl.conf, must be default value + self.assertEquals(self.runner.pid_file, "/var/run/jabber/jcl.pid") + self.assertFalse(self.runner.debug) + self.assertEquals(self.runner.logger.getEffectiveLevel(), + logging.CRITICAL) + + def test_configure_commandline_shortopt(self): + sys.argv = ["", "-c", "src/jcl/test/jcl.conf", + "-S", "test2_localhost", + "-P", "43", + "-s", "test2_secret", + "-j", "test2_jcl.localhost", + "-l", "test2_en", + "-u", "sqlite:///tmp/test_jcl.db", + "-p", "/tmp/test_jcl.pid"] + self.runner.configure() + self.assertEquals(self.runner.server, "test2_localhost") + self.assertEquals(self.runner.port, 43) + self.assertEquals(self.runner.secret, "test2_secret") + self.assertEquals(self.runner.service_jid, "test2_jcl.localhost") + self.assertEquals(self.runner.language, "test2_en") + self.assertEquals(self.runner.db_url, "sqlite:///tmp/test_jcl.db") + self.assertEquals(self.runner.pid_file, "/tmp/test_jcl.pid") + self.assertFalse(self.runner.debug) + self.assertEquals(self.runner.logger.getEffectiveLevel(), + logging.CRITICAL) + + def test_configure_commandline_longopt(self): + sys.argv = ["", "--config-file", "src/jcl/tests/jcl.conf", + "--server", "test2_localhost", + "--port", "43", + "--secret", "test2_secret", + "--service-jid", "test2_jcl.localhost", + "--language", "test2_en", + "--db-url", "sqlite:///tmp/test_jcl.db", + "--pid-file", "/tmp/test_jcl.pid"] + self.runner.configure() + self.assertEquals(self.runner.server, "test2_localhost") + self.assertEquals(self.runner.port, 43) + self.assertEquals(self.runner.secret, "test2_secret") + self.assertEquals(self.runner.service_jid, "test2_jcl.localhost") + self.assertEquals(self.runner.language, "test2_en") + self.assertEquals(self.runner.db_url, "sqlite:///tmp/test_jcl.db") + self.assertEquals(self.runner.pid_file, "/tmp/test_jcl.pid") + self.assertFalse(self.runner.debug) + self.assertEquals(self.runner.logger.getEffectiveLevel(), + logging.CRITICAL) + + def test_configure_commandline_shortopts_configfile(self): + sys.argv = ["", "-c", "src/jcl/tests/jcl.conf"] + self.runner.configure() + self.assertEquals(self.runner.server, "test_localhost") + self.assertEquals(self.runner.port, 42) + self.assertEquals(self.runner.secret, "test_secret") + self.assertEquals(self.runner.service_jid, "test_jcl.localhost") + self.assertEquals(self.runner.language, "test_en") + self.assertEquals(self.runner.db_url, "test_sqlite://root@localhost/var/spool/jabber/test_jcl.db") + self.assertEquals(self.runner.pid_file, "/var/run/jabber/test_jcl.pid") + self.assertFalse(self.runner.debug) + self.assertEquals(self.runner.logger.getEffectiveLevel(), + logging.CRITICAL) + + def test_configure_commandline_longopts_configfile(self): + sys.argv = ["", "--config-file", "src/jcl/tests/jcl.conf"] + self.runner.configure() + self.assertEquals(self.runner.server, "test_localhost") + self.assertEquals(self.runner.port, 42) + self.assertEquals(self.runner.secret, "test_secret") + self.assertEquals(self.runner.service_jid, "test_jcl.localhost") + self.assertEquals(self.runner.language, "test_en") + self.assertEquals(self.runner.db_url, "test_sqlite://root@localhost/var/spool/jabber/test_jcl.db") + self.assertEquals(self.runner.pid_file, "/var/run/jabber/test_jcl.pid") + self.assertFalse(self.runner.debug) + self.assertEquals(self.runner.logger.getEffectiveLevel(), + logging.CRITICAL) + + def test_configure_commandline_short_debug(self): + sys.argv = ["", "-d"] + old_debug_func = self.runner.logger.debug + old_info_func = self.runner.logger.debug + try: + self.runner.logger.debug = lambda msg: None + self.runner.logger.info = lambda msg: None + self.runner.configure() + self.assertTrue(self.runner.debug) + self.assertEquals(self.runner.logger.getEffectiveLevel(), + logging.DEBUG) + finally: + self.runner.logger.debug = old_debug_func + self.runner.logger.info = old_info_func + + def test_configure_commandline_long_debug(self): + sys.argv = ["", "--debug"] + old_debug_func = self.runner.logger.debug + old_info_func = self.runner.logger.debug + try: + self.runner.logger.debug = lambda msg: None + self.runner.logger.info = lambda msg: None + self.runner.configure() + self.assertTrue(self.runner.debug) + self.assertEquals(self.runner.logger.getEffectiveLevel(), + logging.DEBUG) + finally: + self.runner.logger.debug = old_debug_func + self.runner.logger.info = old_info_func + + def test_setup_pidfile(self): + try: + self.runner.pid_file = "/tmp/jcl.pid" + self.runner.setup_pidfile() + pidfile = open("/tmp/jcl.pid", "r") + pid = int(pidfile.read()) + pidfile.close() + self.assertEquals(pid, os.getpid()) + finally: + os.remove("/tmp/jcl.pid") + + def test_run(self): + """Test if run method of JCLComponent is executed""" + self.has_run_func = False + def run_func(component_self): + self.has_run_func = True + return (False, 0) + + self.runner.pid_file = "/tmp/jcl.pid" + db_path = tempfile.mktemp("db", "jcltest", DB_DIR) + db_url = "sqlite://" + db_path + self.runner.db_url = db_url + self.runner.config = None + old_run_func = JCLComponent.run + JCLComponent.run = run_func + try: + self.runner.run() + finally: + JCLComponent.run = old_run_func + self.assertTrue(self.has_run_func) + Account.dropTable() + PresenceAccount.dropTable() + User.dropTable() + LegacyJID.dropTable() + model.db_disconnect() + os.unlink(db_path) + self.assertFalse(os.access("/tmp/jcl.pid", os.F_OK)) + + def test__run(self): + self.runner.pid_file = "/tmp/jcl.pid" + db_path = tempfile.mktemp("db", "jcltest", DB_DIR) + db_url = "sqlite://" + db_path + self.runner.db_url = db_url + def do_nothing(): + return (False, 0) + self.runner._run(do_nothing) + model.db_connect() + # dropTable should succeed because tables should exist + Account.dropTable() + PresenceAccount.dropTable() + User.dropTable() + LegacyJID.dropTable() + model.db_disconnect() + os.unlink(db_path) + self.assertFalse(os.access("/tmp/jcl.pid", os.F_OK)) + + def test__run_restart(self): + self.runner.pid_file = "/tmp/jcl.pid" + db_path = tempfile.mktemp("db", "jcltest", DB_DIR) + db_url = "sqlite://" + db_path + self.runner.db_url = db_url + self.i = 0 + def restart(self): + self.i += 1 + yield (True, 0) + self.i += 1 + yield (False, 0) + self.i += 1 + restart_generator = restart(self) + self.runner._run(lambda : restart_generator.next()) + model.db_connect() + # dropTable should succeed because tables should exist + Account.dropTable() + PresenceAccount.dropTable() + User.dropTable() + LegacyJID.dropTable() + model.db_disconnect() + os.unlink(db_path) + self.assertFalse(os.access("/tmp/jcl.pid", os.F_OK)) + self.assertEquals(self.i, 2) + + def test__get_help(self): + self.assertNotEquals(self.runner._get_help(), None) + +def suite(): + test_suite = unittest.TestSuite() + test_suite.addTest(unittest.makeSuite(JCLRunner_TestCase, 'test')) + return test_suite + +if __name__ == '__main__': + unittest.main(defaultTest='suite') --- /dev/null +++ jcl-0.1b2/src/jcl/tests/__init__.py @@ -0,0 +1,500 @@ +"""JCL test module""" +__revision__ = "" + +import unittest +import os +import tempfile +import sys +import types +import libxml2 +import logging + +from sqlobject.dbconnection import TheURIOpener +import jcl.model + +if sys.platform == "win32": + DB_DIR = "/c|/temp/" +else: + DB_DIR = "/tmp/" + +__logger = logging.getLogger("jcl.tests") + +def is_xml_equal(xml_ref, xml_test, strict=False, + strict_attribut=False, test_sibling=True): + """ + Test for xml structures equality. + By default (`strict`=False), it only test if `xml_ref` structure is included + in `xml_test` (ie. if all elements of `xml_ref` exists in `xml_test`). + if `strict`=True, it also checks if all elements of `xml_test` are in `xml_ref`. + siblings are tested only if `test_sibling` is True. Attribut equality is + tested only if `strict_attribut`=True. + `xml_ref`. + `xml_ref`: xml node + `xml_test`: xml node + `strict`: boolean + `strict_attribut`: boolean + `test_sibling`: boolean + """ + __logger.info("Testing xml node equality:\n--\n" + str(xml_ref) + "\n--\n" + + str(xml_test) + "\n--\n") + if (xml_ref is None) ^ (xml_test is None): + if xml_test is None: + __logger.error("xml_test (" + str(xml_test) + ") or xml_ref (" + + str(xml_ref) + ") is None") + return False + elif strict: + # libxml2 parser set content to None for empty node but + # pyxmpp parser set content to an empty string + if xml_test.type == "text" and xml_test.content == "": + return True + else: + __logger.error("xml_test (" + str(xml_test) + ") or xml_ref (" + + str(xml_ref) + ") is None") + return False + else: + return True + if (xml_ref is None) and (xml_test is None): + return True + if isinstance(xml_ref, types.StringType) \ + or isinstance(xml_ref, types.UnicodeType): + libxml2.pedanticParserDefault(True) + xml_ref = libxml2.parseDoc(xml_ref).children + if isinstance(xml_test, types.StringType) \ + or isinstance(xml_test, types.UnicodeType): + libxml2.pedanticParserDefault(True) + xml_test = libxml2.parseDoc(xml_test).children + + def check_equality(test_func, ref, test, strict): + """ + Check equality with testing function `test_func`. If `strict` is + False, test xml node equality (without its siblings) + """ + if not test_func(ref, test): + if strict: + return False + else: + if test.next is not None: + return is_xml_equal(ref, test.next, strict, + strict_attribut, False) + else: + return False + else: + return True + + if not check_equality(lambda ref, test: ref.type == test.type, + xml_ref, xml_test, strict): + __logger.error("XML node types are different: " + str(xml_ref.type) + + " != " + str(xml_test.type)) + return False + + if xml_ref.type == "text": + return xml_ref.content.strip() == xml_test.content.strip() + if not check_equality(lambda ref, test: ref.name == test.name, + xml_ref, xml_test, strict): + __logger.error("XML node names are different: " + str(xml_ref.name) + + " != " + str(xml_test.name)) + return False + + if not check_equality(lambda ref, test: str(ref.ns()) == str(test.ns()), + xml_ref, xml_test, strict): + __logger.error("XML node namespaces are different: " + str(xml_ref.ns()) + + " != " + str(xml_test.ns())) + return False + + def check_attribut_equality(ref, test): + """ + Check if `ref` xml node attributs are in `test` xml node. + if `strict` is True, check if `test` attributs are in `ref` xml node. + """ + if ref.properties is not None: + if test.properties is None: + return False + for attr in ref.properties: + if ref.prop(attr.name) != test.prop(attr.name): + __logger.error("XML node attributs are different: " + + str(attr) + + " != " + str(test.prop(attr.name))) + return False + if strict_attribut: + for attr in test.properties: + if ref.prop(attr.name) != test.prop(attr.name): + __logger.error("XML node attributs are different: " + + str(attr) + + " != " + str(ref.prop(attr.name))) + return False + elif strict_attribut and test.properties is not None: + return False + return True + + if not check_equality(check_attribut_equality, + xml_ref, xml_test, strict): + return False + + if not check_equality(lambda ref, test: \ + is_xml_equal(ref.children, test.children, + strict, strict_attribut), + xml_ref, xml_test, strict): + __logger.error("XML node children are different: " + + str(xml_ref.children) + + " != " + str(xml_test.children)) + return False + + if test_sibling: + if strict: + new_xml_test = xml_test.next + else: + new_xml_test = xml_test + if not check_equality(lambda ref, test: \ + is_xml_equal(ref, test, strict, + strict_attribut), + xml_ref.next, new_xml_test, strict): + __logger.error("XML node siblings are different") + return False + return True + +class JCLTest_TestCase(unittest.TestCase): + def test_is_xml_equal_str_node_vs_xml_node(self): + """ + Test if an xml node is equal to its string representation. + """ + # Get xml_node children because parseDoc return an xmlDocument + # and we usually test against an xmlNode + xml_node = libxml2.parseDoc("").children + self.assertTrue(is_xml_equal(str(xml_node), xml_node)) + + def test_is_xml_equal_xml_node_vs_str_node(self): + """ + Test if an xml node is equal to its string representation. + """ + # Get xml_node children because parseDoc return an xmlDocument + # and we usually test against an xmlNode + xml_node = libxml2.parseDoc("").children + self.assertTrue(is_xml_equal(xml_node, str(xml_node))) + + def test_is_xml_equal_namespace(self): + """ + Test for namespace equality. + """ + self.assertTrue(is_xml_equal("", + "")) + + ########################################################################### + ## Test weak equality + ########################################################################### + def test_is_xml_equal_simple_str_node_weak_equal(self): + """ + Test with only one node (as string) weak equality (inclusion) 2 equals + structures. + """ + self.assertTrue(is_xml_equal("", "")) + + def test_is_xml_equal_simple_str_node_weak_different(self): + """ + Test with only one node (as string) weak equality (inclusion) 2 + differents structures (attribut added). + """ + self.assertTrue(is_xml_equal("", "")) + + def test_is_xml_equal_simple_str_node_weak_different_missing_attribut(self): + """ + Test with only one node (as string) weak equality (inclusion) 2 + differents structures (attribut missing). + """ + self.assertFalse(is_xml_equal("", "")) + + def test_is_xml_equal_simple_str_node_weak_different_subnode(self): + """ + Test with only one node (as string) weak equality (inclusion) 2 + differents structures (subnode added). + """ + self.assertTrue(is_xml_equal("", "")) + + def test_is_xml_equal_simple_str_node_weak_different_node(self): + """ + Test with only one node (as string) weak equality (inclusion) 2 + differents nodes. + """ + self.assertFalse(is_xml_equal("", "")) + + def test_is_xml_equal_simple_str_node_weak_different_attribut(self): + """ + Test with only one node (as string) weak equality (inclusion) 2 + differents structures (different attributs). + """ + self.assertFalse(is_xml_equal("", + "")) + + def test_is_xml_equal_simple_str_node_weak_different_attribut_value(self): + """ + Test with only one node (as string) weak equality (inclusion) 2 + differents structures (different attributs values). + """ + self.assertFalse(is_xml_equal("", + "")) + + def test_is_xml_equal_complex_str_node_weak_equal(self): + """ + Test 2 complex equal xml structures (weak equality). + """ + self.assertTrue(is_xml_equal("""""", + """""")) + + def test_is_xml_equal_complex_str_node_weak_equal_content(self): + """ + Test 2 complex equal xml structures with equal content. + """ + self.assertTrue(is_xml_equal("content", + "content")) + + def test_is_xml_equal_complex_str_node_weak_different_content(self): + """ + Test 2 complex equal xml structures with different content. + """ + self.assertFalse(is_xml_equal("other", + "content")) + + def test_is_xml_equal_complex_str_node_weak_different_node_order(self): + """ + Test 2 complex equal xml structures (weak equality) but with different + node order. + """ + self.assertTrue(is_xml_equal("""""", + """""")) + + def test_is_xml_equal_complex_str_node_weak_different_attribut_order(self): + """ + Test 2 complex equal xml structures (weak equality) but with different + attribut order. + """ + self.assertTrue(is_xml_equal("""""", + """""")) + + def test_is_xml_equal_complex_str_node_weak_different(self): + """ + Test 2 complex not strictly equal (attribut added) xml structures + (weak equality). + """ + self.assertTrue(is_xml_equal("""""", + """""")) + + def test_is_xml_equal_complex_str_node_weak_different_missing_attribut(self): + """ + Test 2 complex not strictly equal (missing attribut) xml structures + (weak equality). + """ + self.assertFalse(is_xml_equal("""""", + """""")) + + def test_is_xml_equal_complex_str_node_weak_different_subnode(self): + """ + Test 2 complex not strictly equal (subnode added) xml structures + (weak equality). + """ + self.assertTrue(is_xml_equal("""""", + """""")) + + def test_is_xml_equal_complex_str_node_weak_different_siblingnode(self): + """ + Test 2 complex not strictly equal (sibling node added) xml structures + (weak equality). + """ + self.assertTrue(is_xml_equal("""""", + """""")) + + ########################################################################### + ## Test strict equality + ########################################################################### + def test_is_xml_equal_simple_str_node_strict_equal(self): + """ + Test with only one node (as string) strict equality 2 equals + structures. + """ + self.assertTrue(is_xml_equal("", "", True)) + + def test_is_xml_equal_simple_str_node_strict_different(self): + """ + Test with only one node (as string) strict equality 2 + differents structures (attribut added). + """ + self.assertTrue(is_xml_equal("", "", + True)) + + def test_is_xml_equal_simple_str_node_strict_attribut_different(self): + """ + Test with only one node (as string) strict equality 2 + differents structures (attribut added). + """ + self.assertFalse(is_xml_equal("", "", + strict_attribut=True)) + + def test_is_xml_equal_simple_str_node_strict_different2(self): + """ + Test with only one node (as string) strict equality 2 + differents structures (attribut missing). + """ + self.assertFalse(is_xml_equal("", "", + True)) + + def test_is_xml_equal_simple_str_node_strict_different_subnode(self): + """ + Test with only one node (as string) strict equality 2 + differents structures (subnode added). + """ + self.assertFalse(is_xml_equal("", "", + True)) + + def test_is_xml_equal_simple_str_node_strict_different_node(self): + """ + Test with only one node (as string) strict equality 2 + differents nodes. + """ + self.assertFalse(is_xml_equal("", "", True)) + + def test_is_xml_equal_simple_str_node_strict_different_attribut(self): + """ + Test with only one node (as string) strict equality 2 + differents structures (different attributs). + """ + self.assertFalse(is_xml_equal("", + "", + True)) + + def test_is_xml_equal_simple_str_node_strict_different_attribut_value(self): + """ + Test with only one node (as string) strict equality 2 + differents structures (different attributs values). + """ + self.assertFalse(is_xml_equal("", + "", + True)) + + def test_is_xml_equal_complex_str_node_strict_equal(self): + """ + Test 2 complex equal xml structures (strict equality). + """ + self.assertTrue(is_xml_equal("""""", + """""", + True)) + + def test_is_xml_equal_complex_str_node_strict_equal_content(self): + """ + Test 2 complex equal xml structures with equal content. + """ + self.assertTrue(is_xml_equal("content", + "content", + True)) + + def test_is_xml_equal_complex_str_node_strict_different_content(self): + """ + Test 2 complex equal xml structures with different content. + """ + self.assertFalse(is_xml_equal("other", + "content", + True)) + + def test_is_xml_equal_complex_str_node_strict_different_node_order(self): + """ + Test 2 complex equal xml structures but with different + node order. + """ + self.assertFalse(is_xml_equal("""""", + """""", + True)) + + def test_is_xml_equal_complex_str_node_strict_different_attribut_order(self): + """ + Test 2 complex equal xml structures but with different + attribut order. + """ + self.assertTrue(is_xml_equal("""""", + """""", + True)) + + def test_is_xml_equal_complex_str_node_strict_different(self): + """ + Test 2 complex not strictly equal (attribut added) xml structures + (strict equality). + """ + self.assertTrue(is_xml_equal("""""", + """""", + True)) + + def test_is_xml_equal_complex_str_node_strict_attribut_different(self): + """ + Test 2 complex not strictly equal (attribut added) xml structures + (strict equality). + """ + self.assertFalse(is_xml_equal("""""", + """""", + strict_attribut=True)) + + def test_is_xml_equal_complex_str_node_strict_different_missing_attribut(self): + """ + Test 2 complex not strictly equal (missing attribut) xml structures + (strict equality). + """ + self.assertFalse(is_xml_equal("""""", + """""", + True)) + + def test_is_xml_equal_complex_str_node_strict_different_subnode(self): + """ + Test 2 complex not strictly equal (subnode added) xml structures + (strict equality). + """ + self.assertFalse(is_xml_equal("""""", + """""", + True)) + + def test_is_xml_equal_complex_str_node_strict_different_siblingnode(self): + """ + Test 2 complex not strictly equal (sibling node added) xml structures + (strict equality). + """ + self.assertFalse(is_xml_equal("""""", + """""", + True)) + +class JCLTestCase(unittest.TestCase): + def __init__(self, methodName='runTest'): + unittest.TestCase.__init__(self, methodName) + self.tables = [] + + def setUp(self, tables=[]): + self.tables = tables + self.db_path = tempfile.mktemp(".db", "jcltest", DB_DIR) + if os.path.exists(self.db_path): + os.unlink(self.db_path) + self.db_url = "sqlite://" + self.db_path #+ "?debug=True" + jcl.model.db_connection_str = self.db_url + jcl.model.db_connect() + for table in tables: + table.createTable(ifNotExists=True) + jcl.model.db_disconnect() + + def tearDown(self): + jcl.model.db_connect() + for table in self.tables: + table.dropTable(ifExists=True) + del TheURIOpener.cachedURIs[self.db_url] + jcl.model.hub.threadConnection.close() + jcl.model.db_disconnect() + if os.path.exists(self.db_path): + os.unlink(self.db_path) + +def suite(): + from jcl.tests import lang, runner + from jcl.jabber import tests as jabber + from jcl.model import tests as model + test_suite = unittest.TestSuite() + test_suite.addTest(lang.suite()) + test_suite.addTest(runner.suite()) + test_suite.addTest(jabber.suite()) + test_suite.addTest(model.suite()) + test_suite.addTest(unittest.makeSuite(JCLTest_TestCase, 'test')) + return test_suite + +if __name__ == '__main__': + if "-v" in sys.argv: + __logger.setLevel(logging.INFO) + unittest.main(defaultTest='suite') --- /dev/null +++ jcl-0.1b2/src/jcl/tests/jcl.conf @@ -0,0 +1,23 @@ +[jabber] +server: test_localhost +port: 42 +secret: test_secret +service_jid: test_jcl.localhost +#supported language: en, fr (See src/jmc/lang.py to add more) +language: test_en + +[db] +#type: mysql +type: test_sqlite +#host: root@localhost +host: root@localhost +name: /var/spool/jabber/test_jcl.db +#url: %(type)%(host)%(name)?debug=1&debugThreading=1 +db_url: %(type)s://%(host)s%(name)s + +[component] +pid_file: /var/run/jabber/test_jcl.pid +log_file: /tmp/jcl.log + +[vcard] +url: http://people.happycoders.org/dax/projects/jcl --- /dev/null +++ jcl-0.1b2/src/jcl/tests/lang.py @@ -0,0 +1,280 @@ +## +## test_lang.py +## Login : David Rousselie +## Started on Wed Nov 22 19:19:25 2006 David Rousselie +## $Id$ +## +## Copyright (C) 2006 David Rousselie +## This program is free software; you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation; either version 2 of the License, or +## (at your option) any later version. +## +## This program is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with this program; if not, write to the Free Software +## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +## + +import unittest +from jcl.lang import Lang + +from pyxmpp.iq import Iq + +class Lang_TestCase(unittest.TestCase): + def setUp(self): + self.lang = Lang() + + def tearDown(self): + self.lang = None + + def test_get_lang_class_exist(self): + lang_class = self.lang.get_lang_class("fr") + self.assertEquals(lang_class, Lang.fr) + + def test_get_lang_class_not_exist(self): + lang_class = self.lang.get_lang_class("not_exist") + self.assertEquals(lang_class, Lang.en) + + def test_get_lang_class_long_code(self): + lang_class = self.lang.get_lang_class("fr_FR") + self.assertEquals(lang_class, Lang.fr) + + def test_get_lang_from_node(self): + iq = Iq(from_jid = "test@test.com", \ + to_jid = "test2@test.com", \ + stanza_type = "get") + iq_node = iq.get_node() + iq_node.setLang("fr") + lang = self.lang.get_lang_from_node(iq_node) + self.assertEquals(lang, "fr") + + def test_get_lang_class_from_node(self): + iq = Iq(from_jid = "test@test.com", \ + to_jid = "test2@test.com", \ + stanza_type = "get") + iq_node = iq.get_node() + iq_node.setLang("fr") + lang = self.lang.get_lang_class_from_node(iq_node) + self.assertEquals(lang, Lang.fr) + + def test_get_default_lang_class(self): + self.assertEquals(self.lang.get_default_lang_class(), Lang.en) + + def test_get_default_lang_class_other(self): + self.lang = Lang("fr") + self.assertEquals(self.lang.get_default_lang_class(), Lang.fr) + +class Language_TestCase(unittest.TestCase): + """Test language classes""" + + def setUp(self): + """must define self.lang_class. Lang.en is default""" + self.lang_class = Lang.en + + def test_strings(self): + self.assertNotEquals(self.lang_class.component_name, None) + self.assertNotEquals(self.lang_class.register_title, None) + self.assertNotEquals(self.lang_class.register_instructions, None) + self.assertNotEquals(self.lang_class.message_status, None) + self.assertNotEquals(self.lang_class.account_name, None) + + self.assertNotEquals(self.lang_class.password_saved_for_session, None) + self.assertNotEquals(self.lang_class.ask_password_subject, None) + self.assertNotEquals(self.lang_class.ask_password_body % (""), None) + self.assertNotEquals(self.lang_class.new_account_message_subject % (""), None) + self.assertNotEquals(self.lang_class.new_account_message_body, None) + self.assertNotEquals(self.lang_class.update_account_message_subject % (""), None) + self.assertNotEquals(self.lang_class.update_account_message_body, None) + + self.assertNotEquals(self.lang_class.field_error % ("", ""), None) + self.assertNotEquals(self.lang_class.mandatory_field, None) + self.assertNotEquals(self.lang_class.not_well_formed_field, None) + self.assertNotEquals(self.lang_class.arobase_in_name_forbidden, None) + + self.assertNotEquals(self.lang_class.field_chat_action, None) + self.assertNotEquals(self.lang_class.field_online_action, None) + self.assertNotEquals(self.lang_class.field_away_action, None) + self.assertNotEquals(self.lang_class.field_xa_action, None) + self.assertNotEquals(self.lang_class.field_dnd_action, None) + self.assertNotEquals(self.lang_class.field_offline_action, None) + + self.assertNotEquals(self.lang_class.field_action_0, None) + self.assertNotEquals(self.lang_class.field_chat_action_0, None) + self.assertNotEquals(self.lang_class.field_online_action_0, None) + self.assertNotEquals(self.lang_class.field_away_action_0, None) + self.assertNotEquals(self.lang_class.field_xa_action_0, None) + self.assertNotEquals(self.lang_class.field_dnd_action_0, None) + self.assertNotEquals(self.lang_class.field_offline_action_0, None) + + self.assertNotEquals(self.lang_class.field_user_jid, None) + self.assertNotEquals(self.lang_class.field_password, None) + + self.assertNotEquals(self.lang_class.error_subject, None) + self.assertNotEquals(self.lang_class.error_body % (""), None) + + self.assertNotEquals(self.lang_class.get_gateway_desc, None) + self.assertNotEquals(self.lang_class.get_gateway_prompt, None) + + self.assertNotEquals(self.lang_class.command_add_user, None) + self.assertNotEquals(self.lang_class.command_add_user_1_description, + None) + self.assertNotEquals(self.lang_class.field_account_type, None) + + self.assertNotEquals(self.lang_class.command_delete_user, None) + self.assertNotEquals(self.lang_class.command_delete_user_1_description, + None) + self.assertNotEquals(self.lang_class.command_delete_user_2_description, + None) + self.assertNotEquals(self.lang_class.field_users_jids, None) + self.assertNotEquals(self.lang_class.field_account, None) + self.assertNotEquals(self.lang_class.field_accounts, None) + + self.assertNotEquals(self.lang_class.command_disable_user, None) + self.assertNotEquals(self.lang_class.command_disable_user_1_description, + None) + self.assertNotEquals(self.lang_class.command_disable_user_2_description, + None) + + self.assertNotEquals(self.lang_class.command_reenable_user, None) + self.assertNotEquals(self.lang_class.command_reenable_user_1_description, + None) + self.assertNotEquals(self.lang_class.command_reenable_user_2_description, + None) + + self.assertNotEquals(self.lang_class.command_end_user_session, None) + self.assertNotEquals(self.lang_class.command_end_user_session_1_description, + None) + self.assertNotEquals(self.lang_class.command_end_user_session_2_description, + None) + + self.assertNotEquals(self.lang_class.command_get_user_password, None) + self.assertNotEquals(self.lang_class.command_get_user_password_1_description, + None) + self.assertNotEquals(self.lang_class.command_get_user_password_2_description, + None) + + self.assertNotEquals(self.lang_class.command_change_user_password, + None) + self.assertNotEquals(self.lang_class.command_change_user_password_1_description, + None) + self.assertNotEquals(self.lang_class.command_change_user_password_2_description, + None) + + self.assertNotEquals(self.lang_class.command_get_user_roster, None) + self.assertNotEquals(self.lang_class.command_get_user_roster_1_description, + None) + + self.assertNotEquals(self.lang_class.command_get_user_lastlogin, + None) + self.assertNotEquals(self.lang_class.command_get_user_lastlogin_1_description, + None) + self.assertNotEquals(self.lang_class.command_get_user_lastlogin_2_description, + None) + + self.assertNotEquals(self.lang_class.command_get_registered_users_num, + None) + self.assertNotEquals(self.lang_class.command_get_disabled_users_num, + None) + self.assertNotEquals(self.lang_class.command_get_online_users_num, + None) + + self.assertNotEquals(self.lang_class.command_get_registered_users_list, + None) + self.assertNotEquals(self.lang_class.command_get_disabled_users_list, + None) + self.assertNotEquals(self.lang_class.command_get_online_users_list, + None) + + self.assertNotEquals(self.lang_class.field_registered_users_num, None) + self.assertNotEquals(self.lang_class.field_disabled_users_num, None) + self.assertNotEquals(self.lang_class.field_online_users_num, None) + + self.assertNotEquals(self.lang_class.field_max_items, None) + self.assertNotEquals(self.lang_class.field_registered_users_list, None) + self.assertNotEquals(self.lang_class.field_disabled_users_list, None) + self.assertNotEquals(self.lang_class.field_online_users_list, None) + + self.assertNotEquals(self.lang_class.command_announce, None) + self.assertNotEquals(self.lang_class.command_announce_1_description, None) + self.assertNotEquals(self.lang_class.field_announcement, None) + + self.assertNotEquals(self.lang_class.command_set_motd, None) + self.assertNotEquals(self.lang_class.command_set_motd_1_description, None) + self.assertNotEquals(self.lang_class.field_motd, None) + + self.assertNotEquals(self.lang_class.command_edit_motd, None) + + self.assertNotEquals(self.lang_class.command_delete_motd, None) + + self.assertNotEquals(self.lang_class.command_set_welcome, None) + self.assertNotEquals(self.lang_class.command_set_welcome_1_description, None) + self.assertNotEquals(self.lang_class.field_welcome, None) + + self.assertNotEquals(self.lang_class.command_delete_welcome, None) + + self.assertNotEquals(self.lang_class.command_edit_admin, None) + self.assertNotEquals(self.lang_class.command_edit_admin_1_description, None) + self.assertNotEquals(self.lang_class.field_admin_jids, None) + + self.assertNotEquals(self.lang_class.command_restart, None) + self.assertNotEquals(self.lang_class.command_restart_1_description, None) + self.assertNotEquals(self.lang_class.field_restart_delay, None) + + self.assertNotEquals(self.lang_class.command_shutdown, None) + self.assertNotEquals(self.lang_class.command_shutdown_1_description, None) + self.assertNotEquals(self.lang_class.field_shutdown_delay, None) + + self.assertNotEquals(self.lang_class.field_30_sec, None) + self.assertNotEquals(self.lang_class.field_60_sec, None) + self.assertNotEquals(self.lang_class.field_90_sec, None) + self.assertNotEquals(self.lang_class.field_120_sec, None) + self.assertNotEquals(self.lang_class.field_180_sec, None) + self.assertNotEquals(self.lang_class.field_240_sec, None) + self.assertNotEquals(self.lang_class.field_300_sec, None) + + self.assertNotEquals(self.lang_class.welcome_message_subject, None) + + self.assertNotEquals(self.lang_class.account_disabled, None) + self.assertNotEquals(self.lang_class.account_error, None) + + self.assertNotEquals(self.lang_class.help_message_subject, None) + self.assertNotEquals(self.lang_class.help_message_body, None) + + self.assertNotEquals(self.lang_class.field_last_error, None) + self.assertNotEquals(self.lang_class.account_no_error, None) + +class Language_fr_TestCase(Language_TestCase): + def setUp(self): + self.lang_class = Lang.fr + +class Language_nl_TestCase(Language_TestCase): + def setUp(self): + self.lang_class = Lang.nl + +class Language_es_TestCase(Language_TestCase): + def setUp(self): + self.lang_class = Lang.es + +class Language_pl_TestCase(Language_TestCase): + def setUp(self): + self.lang_class = Lang.pl + +def suite(): + test_suite = unittest.TestSuite() + test_suite.addTest(unittest.makeSuite(Lang_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(Language_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(Language_fr_TestCase, 'test')) +# suite.addTest(unittest.makeSuite(Language_nl_TestCase, 'test')) +# suite.addTest(unittest.makeSuite(Language_es_TestCase, 'test')) +# suite.addTest(unittest.makeSuite(Language_pl_TestCase, 'test')) +# suite.addTest(unittest.makeSuite(Language_cs_TestCase, 'test')) +# suite.addTest(unittest.makeSuite(Language_ru_TestCase, 'test')) + return test_suite + +if __name__ == '__main__': + unittest.main(defaultTest='suite') --- /dev/null +++ jcl-0.1b2/src/jcl/tests/uncomplete_jcl.conf @@ -0,0 +1,19 @@ +[jabber] +server: test_localhost +port: 42 +secret: test_secret +service_jid: test_jcl.localhost +#supported language: en, fr (See src/jmc/lang.py to add more) +language: test_en + +[db] +#type: mysql +type: test_sqlite +#host: root@localhost +host: root@localhost +name: /var/spool/jabber/test_jcl.db +#url: %(type)%(host)%(name)?debug=1&debugThreading=1 +db_url: %(type)s://%(host)s%(name)s + +[component] +log_file: /tmp/jcl.log --- /dev/null +++ jcl-0.1b2/src/jcl/model/tests/account.py @@ -0,0 +1,326 @@ +## +## test_account.py +## Login : David Rousselie +## Started on Wed Nov 22 19:32:53 2006 David Rousselie +## $Id$ +## +## Copyright (C) 2006 David Rousselie +## This program is free software; you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation; either version 2 of the License, or +## (at your option) any later version. +## +## This program is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with this program; if not, write to the Free Software +## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +## + +import unittest +import sys + +from sqlobject import * + +from jcl.error import FieldError +import jcl.model as model +from jcl.model import account +from jcl.model.account import Account, PresenceAccount, User + +from jcl.tests import JCLTestCase + +if sys.platform == "win32": + DB_DIR = "/c|/temp/" +else: + DB_DIR = "/tmp/" + +class ExampleAccount(Account): + login = StringCol(default="") + password = StringCol(default=None) + store_password = BoolCol(default=True) + waiting_password_reply = BoolCol(default=False) + + test_enum = EnumCol(default="choice1", enumValues=["choice1", "choice2", "choice3"]) + test_int = IntCol(default=42) + + def _get_register_fields(cls, real_class=None): + def password_post_func(password): + if password is None or password == "": + return None + return password + + if real_class is None: + real_class = cls + return Account.get_register_fields(real_class) + \ + [("login", "text-single", None, + lambda field_value, default_func, bare_from_jid: \ + account.mandatory_field("login", field_value), + lambda bare_from_jid: ""), + ("password", "text-private", None, + lambda field_value, default_func, bare_from_jid: \ + password_post_func(field_value), + lambda bare_from_jid: ""), + ("store_password", "boolean", None, account.default_post_func, + lambda bare_from_jid: True), + ("test_enum", "list-single", ["choice1", "choice2", "choice3"], + account.default_post_func, + lambda bare_from_jid: "choice2"), + ("test_int", "text-single", None, account.int_post_func, + lambda bare_from_jid: 44)] + + get_register_fields = classmethod(_get_register_fields) + +class Example2Account(Account): + test_new_int = IntCol(default=42) + + def _get_register_fields(cls, real_class=None): + if real_class is None: + real_class = cls + return Account.get_register_fields(real_class) + \ + [("test_new_int", "text-single", None, account.int_post_func, + lambda bare_from_jid: 43)] + get_register_fields = classmethod(_get_register_fields) + +class PresenceAccountExample(PresenceAccount): + DO_SOMETHING_ELSE = 2 + possibles_actions = [PresenceAccount.DO_NOTHING, + PresenceAccount.DO_SOMETHING, + DO_SOMETHING_ELSE] + + def _get_presence_actions_fields(cls): + """See PresenceAccount._get_presence_actions_fields + """ + return {'chat_action': (cls.possibles_actions, + PresenceAccountExample.DO_SOMETHING_ELSE), + 'online_action': (cls.possibles_actions, + PresenceAccountExample.DO_SOMETHING_ELSE), + 'away_action': (cls.possibles_actions, + PresenceAccountExample.DO_SOMETHING_ELSE), + 'xa_action': (cls.possibles_actions, + PresenceAccountExample.DO_SOMETHING_ELSE), + 'dnd_action': (cls.possibles_actions, + PresenceAccountExample.DO_SOMETHING_ELSE), + 'offline_action': (cls.possibles_actions, + PresenceAccountExample.DO_SOMETHING_ELSE)} + + get_presence_actions_fields = classmethod(_get_presence_actions_fields) + + test_new_int = IntCol(default=42) + + def _get_register_fields(cls, real_class=None): + if real_class is None: + real_class = cls + return PresenceAccount.get_register_fields(real_class) + \ + [("test_new_int", "text-single", None, account.int_post_func, + lambda bare_from_jid: 43)] + get_register_fields = classmethod(_get_register_fields) + +class AccountModule_TestCase(JCLTestCase): + def setUp(self): + JCLTestCase.setUp(self, tables=[User, Account, ExampleAccount]) + + def test_default_post_func(self): + result = account.default_post_func("test", None, "user1@jcl.test.com") + self.assertEquals(result, "test") + + def test_default_post_func_default_value(self): + result = account.default_post_func("", + lambda bare_from_jid: "test", \ + "user1@jcl.test.com") + self.assertEquals(result, "test") + + def test_default_post_func_default_value2(self): + result = account.default_post_func(None, lambda bare_from_jid: "test", \ + "user1@jcl.test.com") + self.assertEquals(result, "test") + + def test_int_post_func(self): + result = account.int_post_func("42", None, "user1@jcl.test.com") + self.assertEquals(result, 42) + + def test_int_post_func_default_value(self): + result = account.int_post_func("", lambda bare_from_jid: 42, \ + "user1@jcl.test.com") + self.assertEquals(result, 42) + + def test_int_post_func_default_value(self): + result = account.int_post_func(None, lambda bare_from_jid: 42, \ + "user1@jcl.test.com") + self.assertEquals(result, 42) + + def test_mandatory_field_empty(self): + self.assertRaises(FieldError, + account.mandatory_field, + "test", "") + + def test_mandatory_field_none(self): + self.assertRaises(FieldError, + account.mandatory_field, + "test", None) + + def test_mandatory_field_empty(self): + self.assertEquals(account.mandatory_field("test", "value"), + "value") + + def test_get_accounts(self): + user1 = User(jid="user1@test.com") + Account(user=user1, + name="account11", + jid="accout11@jcl.test.com") + Account(user=user1, + name="account12", + jid="accout12@jcl.test.com") + Account(user=User(jid="test2@test.com"), + name="account11", + jid="accout11@jcl.test.com") + accounts = account.get_accounts("user1@test.com") + i = 0 + for _account in accounts: + i += 1 + self.assertEquals(_account.user.jid, "user1@test.com") + self.assertEquals(i, 2) + + def test_get_accounts_type(self): + user1 = User(jid="user1@test.com") + Account(user=user1, + name="account11", + jid="accout11@jcl.test.com") + ExampleAccount(user=user1, + name="account12", + jid="accout12@jcl.test.com") + ExampleAccount(user=User(jid="test2@test.com"), + name="account11", + jid="accout11@jcl.test.com") + accounts = account.get_accounts("user1@test.com", ExampleAccount) + i = 0 + for _account in accounts: + i += 1 + self.assertEquals(_account.user.jid, "user1@test.com") + self.assertEquals(_account.name, "account12") + self.assertEquals(i, 1) + + def test_get_account(self): + user1 = User(jid="user1@test.com") + ExampleAccount(user=user1, + name="account11", + jid="accout11@jcl.test.com") + ExampleAccount(user=user1, + name="account12", + jid="accout12@jcl.test.com") + ExampleAccount(user=User(jid="test2@test.com"), + name="account11", + jid="accout11@jcl.test.com") + _account = account.get_account("user1@test.com", "account11") + self.assertEquals(_account.user.jid, "user1@test.com") + self.assertEquals(_account.name, "account11") + +class InheritableAccount_TestCase(JCLTestCase): + + def test_get_register_fields(self): + """ + Check if post functions and default functions execute correctly. + To be validated this test only need to be executed without any + exception. + """ + model.db_connect() + for (field_name, + field_type, + field_options, + field_post_func, + field_default_func) in self.account_class.get_register_fields(): + if field_name is not None: + try: + field_post_func(field_default_func("user1@jcl.test.com"), + field_default_func, "user1@jcl.test.com") + except FieldError, error: + # this type of error is OK + pass + model.db_disconnect() + +class Account_TestCase(InheritableAccount_TestCase): + def setUp(self): + JCLTestCase.setUp(self, tables=[User, Account, ExampleAccount]) + self.account_class = Account + + def test_set_status(self): + model.db_connect() + account11 = Account(user=User(jid="test1@test.com"), + name="account11", + jid="account11@jcl.test.com") + account11.status = account.OFFLINE + self.assertEquals(account11.status, account.OFFLINE) + model.db_disconnect() + + def test_set_status_live_password(self): + model.db_connect() + account11 = ExampleAccount(user=User(jid="test1@test.com"), + name="account11", + jid="account11@jcl.test.com", + login="mylogin", + password="mypassword", + store_password=False, + test_enum="choice3", + test_int=21) + account11.waiting_password_reply = True + account11.status = account.OFFLINE + self.assertEquals(account11.status, account.OFFLINE) + self.assertEquals(account11.waiting_password_reply, False) + self.assertEquals(account11.password, None) + model.db_disconnect() + +class PresenceAccount_TestCase(InheritableAccount_TestCase): + def setUp(self, tables=[]): + JCLTestCase.setUp(self, tables=[User, Account, PresenceAccount, + PresenceAccountExample] + tables) + model.db_connect() + self.account = PresenceAccountExample(\ + user=User(jid="test1@test.com"), + name="account11", + jid="account11@jcl.test.com") + model.db_disconnect() + self.account_class = PresenceAccount + + def test_get_presence_actions_fields(self): + fields = self.account_class.get_presence_actions_fields() + self.assertEquals(len(fields), 6) + (possibles_actions, chat_default_action) = fields["chat_action"] + self.assertEquals(possibles_actions, + self.account_class.possibles_actions) + (possibles_actions, online_default_action) = fields["online_action"] + self.assertEquals(possibles_actions, + self.account_class.possibles_actions) + + def test_possibles_actions(self): + for (field_name, + field_type, + possibles_actions, + post_func, + default_func) in self.account_class.get_register_fields()[1:]: + if possibles_actions is not None: + for possible_action in possibles_actions: + self.assertEquals(post_func(possible_action, default_func, + "user1@jcl.test.com"), + int(possible_action)) + self.assertTrue(str(default_func("user1@jcl.test.com")) \ + in possibles_actions) + else: + try: + post_func("42", default_func, "user1@jcl.test.com") + default_func("user1@jcl.test.com") + except FieldError, error: + pass + except Exception, exception: + self.fail("Unexcepted exception: " + str(exception)) + +def suite(): + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite(AccountModule_TestCase, 'test')) + suite.addTest(unittest.makeSuite(Account_TestCase, 'test')) + suite.addTest(unittest.makeSuite(PresenceAccount_TestCase, 'test')) + return suite + +if __name__ == '__main__': + unittest.main(defaultTest='suite') --- /dev/null +++ jcl-0.1b2/src/jcl/model/tests/__init__.py @@ -0,0 +1,84 @@ +"""JCL test module""" +__revision__ = "" + +import unittest +import threading +import os +import tempfile +import sys + +from sqlobject import SQLObject +from sqlobject.col import StringCol +from sqlobject.dbconnection import TheURIOpener + +import jcl.model as model + +if sys.platform == "win32": + DB_DIR = "/c|/temp/" +else: + DB_DIR = "/tmp/" + +class MyMockSQLObject(SQLObject): + _connection = model.hub + string_attr = StringCol() + +class ModelModule_TestCase(unittest.TestCase): + def setUp(self): + self.db_path = tempfile.mktemp("db", "jcltest", DB_DIR) + if os.path.exists(self.db_path): + os.unlink(self.db_path) + self.db_url = "sqlite://" + self.db_path + model.db_connection_str = self.db_url + model.db_connect() + MyMockSQLObject.createTable(ifNotExists=True) + model.db_disconnect() + + def tearDown(self): + model.db_connect() + MyMockSQLObject.dropTable(ifExists=True) + del TheURIOpener.cachedURIs[self.db_url] + model.hub.threadConnection.close() + model.db_disconnect() + if os.path.exists(self.db_path): + os.unlink(self.db_path) + + def test_multiple_db_connection(self): + def create_account_thread(): + for i in xrange(100): + string_attr = "obj2" + str(i) + model.db_connect() + obj = MyMockSQLObject(string_attr=string_attr) + model.db_disconnect() + model.db_connect() + obj2 = MyMockSQLObject.select(MyMockSQLObject.q.string_attr == string_attr) + model.db_disconnect() + self.assertEquals(obj, obj2[0]) + timer_thread = threading.Thread(target=create_account_thread, + name="CreateAccountThread") + timer_thread.start() + for i in xrange(100): + string_attr = "obj1" + str(i) + model.db_connect() + obj = MyMockSQLObject(string_attr=string_attr) + model.db_disconnect() + model.db_connect() + obj2 = MyMockSQLObject.select(MyMockSQLObject.q.string_attr == string_attr) + model.db_disconnect() + self.assertEquals(obj, obj2[0]) + timer_thread.join(2) + threads = threading.enumerate() + self.assertEquals(len(threads), 1) + model.db_connect() + objs = MyMockSQLObject.select() + self.assertEquals(objs.count(), 200) + model.db_disconnect() + +def suite(): + suite = unittest.TestSuite() + suite.addTest(unittest.makeSuite(ModelModule_TestCase, 'test')) + from jcl.model.tests import account + suite.addTest(account.suite()) + return suite + +if __name__ == '__main__': + unittest.main(defaultTest='suite') --- /dev/null +++ jcl-0.1b2/src/jcl/jabber/tests/disco.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- +## +## disco.py +## Login : David Rousselie +## Started on Fri Jul 6 21:40:55 2007 David Rousselie +## $Id$ +## +## Copyright (C) 2007 David Rousselie +## This program is free software; you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation; either version 2 of the License, or +## (at your option) any later version. +## +## This program is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with this program; if not, write to the Free Software +## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +## + +import unittest + +from pyxmpp.message import Message + +from jcl.tests import JCLTestCase +from jcl.model.tests.account import ExampleAccount + +from jcl.model.account import User, Account +from jcl.jabber.component import JCLComponent +from jcl.jabber.disco import DiscoHandler, AccountTypeDiscoGetItemsHandler + +class DiscoHandler_TestCase(JCLTestCase): + def setUp(self): + JCLTestCase.setUp(self, tables=[User, Account, ExampleAccount]) + self.comp = JCLComponent("jcl.test.com", + "password", + "localhost", + "5347", + self.db_url) + self.handler = DiscoHandler(self.comp) + + def test_default_filter(self): + """Test default filter behavior""" + self.assertFalse(self.handler.filter(None, None, None)) + + def test_default_handler(self): + """Test default handler: do nothing""" + self.assertEquals(self.handler.handle(None, None, None, None, None), + None) + +class AccountTypeDiscoGetItemsHandler_TestCase (JCLTestCase): + """Test AccountTypeDiscoGetItemsHandler class""" + def setUp(self): + JCLTestCase.setUp(self, tables=[User, Account, ExampleAccount]) + self.comp = JCLComponent("jcl.test.com", + "password", + "localhost", + "5347", + self.db_url) + self.comp.account_manager.account_classes = (ExampleAccount,) + self.handler = AccountTypeDiscoGetItemsHandler(self.comp) + + def test_handler_unknown_account_type(self): + """Test handler with an unknown account type""" + self.assertEquals(self.handler.handle(Message(from_jid="from@test.com"), + None, None, None, + "Unknown"), []) + +def suite(): + test_suite = unittest.TestSuite() + test_suite.addTest(unittest.makeSuite(DiscoHandler_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(AccountTypeDiscoGetItemsHandler_TestCase, + 'test')) + return test_suite + +if __name__ == '__main__': + unittest.main(defaultTest='suite') --- /dev/null +++ jcl-0.1b2/src/jcl/jabber/tests/component.py @@ -0,0 +1,3405 @@ +# -*- coding: utf-8 -*- +## +## test_component.py +## Login : David Rousselie +## Started on Wed Aug 9 21:34:26 2006 David Rousselie +## $Id$ +## +## Copyright (C) 2006 David Rousselie +## This program is free software; you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation; either version 2 of the License, or +## (at your option) any later version. +## +## This program is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with this program; if not, write to the Free Software +## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +## + +import unittest +import logging +import sys + +import threading +import time +import re +from ConfigParser import ConfigParser +import tempfile +import os +import socket + +from pyxmpp.jid import JID +from pyxmpp.iq import Iq +from pyxmpp.presence import Presence +from pyxmpp.message import Message +from pyxmpp.jabber.dataforms import Form +import pyxmpp.jabber.vcard as vcard + +import jcl.tests +from jcl.jabber import Handler +from jcl.jabber.component import JCLComponent, AccountManager +from jcl.jabber.presence import DefaultSubscribeHandler, \ + DefaultUnsubscribeHandler, DefaultPresenceHandler +import jcl.model as model +import jcl.model.account as account +from jcl.model.account import Account, LegacyJID, User +from jcl.lang import Lang +import jcl.jabber.command as command + +from jcl.model.tests.account import ExampleAccount, Example2Account +from jcl.tests import JCLTestCase + +logger = logging.getLogger() + +class MockStream(object): + def __init__(self, + jid="", + secret="", + server="", + port=1, + keepalive=None, + owner=None): + self.sent = [] + self.connection_started = False + self.connection_stopped = False + self.eof = False + self.socket = [] + + def send(self, iq): + self.sent.append(iq) + + def set_iq_set_handler(self, iq_type, ns, handler): + if not iq_type in ["query", "command", "vCard"]: + raise Exception("IQ type unknown: " + iq_type) + if not ns in ["jabber:iq:version", + "jabber:iq:register", + "jabber:iq:gateway", + "jabber:iq:last", + vcard.VCARD_NS, + "http://jabber.org/protocol/disco#items", + "http://jabber.org/protocol/disco#info", + "http://jabber.org/protocol/commands"]: + raise Exception("Unknown namespace: " + ns) + if handler is None: + raise Exception("Handler must not be None") + + set_iq_get_handler = set_iq_set_handler + + def set_presence_handler(self, status, handler): + if not status in ["available", + "unavailable", + "probe", + "subscribe", + "subscribed", + "unsubscribe", + "unsubscribed"]: + raise Exception("Status unknown: " + status) + if handler is None: + raise Exception("Handler must not be None") + + def set_message_handler(self, msg_type, handler): + if not msg_type in ["normal"]: + raise Exception("Message type unknown: " + msg_type) + if handler is None: + raise Exception("Handler must not be None") + + def connect(self): + self.connection_started = True + + def disconnect(self): + self.connection_stopped = True + + def loop_iter(self, timeout): + return + + def close(self): + pass + +class MockStreamNoConnect(MockStream): + def connect(self): + self.connection_started = True + + def loop_iter(self, timeout): + return + +class MockStreamRaiseException(MockStream): + def loop_iter(self, timeout): + raise Exception("in loop error") + +class LangExample(Lang): + class en(Lang.en): + type_example_name = "Type Example" + +class TestSubscribeHandler(DefaultSubscribeHandler): + def filter(self, message, lang_class): + if re.compile(".*%.*").match(message.get_to().node): + # return no account because self.handle does not need an account + return [] + else: + return None + +class ErrorHandler(Handler): + def filter(self, stanza, lang_class): + raise Exception("test error") + +class TestUnsubscribeHandler(DefaultUnsubscribeHandler): + def filter(self, message, lang_class): + if re.compile(".*%.*").match(message.get_to().node): + # return no account because self.handle does not need an account + return [] + else: + return None + +class HandlerMock(object): + def __init__(self): + self.handled = [] + + def filter(self, stanza, lang_class): + return True + + def handle(self, stanza, lang_class, data): + self.handled.append((stanza, lang_class, data)) + return [(stanza, lang_class, data)] + +class JCLComponent_TestCase(JCLTestCase): + def _handle_tick_test_time_handler(self): + self.max_tick_count -= 1 + if self.max_tick_count == 0: + self.comp.running = False + + def setUp(self): + JCLTestCase.setUp(self, tables=[Account, LegacyJID, ExampleAccount, + Example2Account, User]) + self.comp = JCLComponent("jcl.test.com", + "password", + "localhost", + "5347", + None) + self.max_tick_count = 1 + self.comp.time_unit = 0 + self.saved_time_handler = None + +class JCLComponent_constructor_TestCase(JCLComponent_TestCase): + """Constructor tests""" + + def test_constructor(self): + model.db_connect() + self.assertTrue(Account._connection.tableExists("account")) + model.db_disconnect() + +class JCLComponent_apply_registered_behavior_TestCase(JCLComponent_TestCase): + """apply_registered_behavior tests""" + + def test_apply_registered_behavior(self): + self.comp.stream = MockStreamNoConnect() + self.comp.stream_class = MockStreamNoConnect + message = Message(from_jid="user1@test.com", + to_jid="account11@jcl.test.com") + result = self.comp.apply_registered_behavior([[ErrorHandler(None)]], message) + self.assertEquals(len(result), 1) + self.assertEquals(result[0].get_type(), "error") + self.assertEquals(len(self.comp.stream.sent), 1) + self.assertEquals(result[0], self.comp.stream.sent[0]) + + def test_apply_all_registered_behavior(self): + self.comp.stream = MockStreamNoConnect() + self.comp.stream_class = MockStreamNoConnect + message = Message(from_jid="user1@test.com", + to_jid="account11@jcl.test.com") + handler1 = HandlerMock() + handler2 = HandlerMock() + result = self.comp.apply_registered_behavior([[handler1], [handler2]], + message) + self.assertEquals(len(result), 2) + self.assertEquals(result[0][0], message) + self.assertEquals(result[1][0], message) + + def test_apply_one_registered_behavior_return_none(self): + self.comp.stream = MockStreamNoConnect() + self.comp.stream_class = MockStreamNoConnect + message = Message(from_jid="user1@test.com", + to_jid="account11@jcl.test.com") + handler1 = HandlerMock() + handler1.filter = lambda stanza, lang_class: None + handler2 = HandlerMock() + result = self.comp.apply_registered_behavior([[handler1], [handler2]], + message) + self.assertEquals(len(result), 1) + self.assertEquals(result[0][0], message) + + def test_apply_one_registered_behavior_return_false(self): + self.comp.stream = MockStreamNoConnect() + self.comp.stream_class = MockStreamNoConnect + message = Message(from_jid="user1@test.com", + to_jid="account11@jcl.test.com") + handler1 = HandlerMock() + handler1.filter = lambda stanza, lang_class: False + handler2 = HandlerMock() + result = self.comp.apply_registered_behavior([[handler1], [handler2]], + message) + self.assertEquals(len(result), 1) + self.assertEquals(result[0][0], message) + + def test_apply_one_registered_behavior_return_empty_str(self): + self.comp.stream = MockStreamNoConnect() + self.comp.stream_class = MockStreamNoConnect + message = Message(from_jid="user1@test.com", + to_jid="account11@jcl.test.com") + handler1 = HandlerMock() + handler1.filter = lambda stanza, lang_class: "" + handler2 = HandlerMock() + result = self.comp.apply_registered_behavior([[handler1], [handler2]], + message) + self.assertEquals(len(result), 1) + self.assertEquals(result[0][0], message) + + def test_apply_one_registered_behavior(self): + self.comp.stream = MockStreamNoConnect() + self.comp.stream_class = MockStreamNoConnect + message = Message(from_jid="user1@test.com", + to_jid="account11@jcl.test.com") + handler1 = HandlerMock() + handler2 = HandlerMock() + result = self.comp.apply_registered_behavior([[handler1, handler2]], + message) + self.assertEquals(len(result), 1) + self.assertEquals(result[0][0], message) + self.assertEquals(len(handler1.handled), 1) + self.assertEquals(len(handler2.handled), 0) + +class JCLComponent_time_handler_TestCase(JCLComponent_TestCase): + """time_handler' tests""" + + def test_time_handler(self): + self.comp.time_unit = 1 + self.max_tick_count = 1 + self.comp.handle_tick = self._handle_tick_test_time_handler + self.comp.stream = MockStream() + self.comp.running = True + self.comp.time_handler() + self.assertEquals(self.max_tick_count, 0) + self.assertFalse(self.comp.running) + +class JCLComponent_authenticated_handler_TestCase(JCLComponent_TestCase): + """authenticated handler' tests""" + + def test_authenticated_handler(self): + self.comp.stream = MockStream() + self.comp.authenticated() + self.assertTrue(True) + + def test_authenticated_send_probe(self): + model.db_connect() + user1 = User(jid="test1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="test2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.stream = MockStream() + self.comp.authenticated() + self.assertEqual(len(self.comp.stream.sent), 5) + presence = self.comp.stream.sent[0] + self.assertTrue(isinstance(presence, Presence)) + self.assertEquals(presence.get_from(), "jcl.test.com") + self.assertEquals(presence.get_to(), "test1@test.com") + self.assertEquals(presence.get_node().prop("type"), "probe") + presence = self.comp.stream.sent[1] + self.assertTrue(isinstance(presence, Presence)) + self.assertEquals(presence.get_from(), "jcl.test.com") + self.assertEquals(presence.get_to(), "test2@test.com") + self.assertEquals(presence.get_node().prop("type"), "probe") + presence = self.comp.stream.sent[2] + self.assertTrue(isinstance(presence, Presence)) + self.assertEquals(presence.get_from(), "account11@jcl.test.com") + self.assertEquals(presence.get_to(), "test1@test.com") + self.assertEquals(presence.get_node().prop("type"), "probe") + presence = self.comp.stream.sent[3] + self.assertTrue(isinstance(presence, Presence)) + self.assertEquals(presence.get_from(), "account12@jcl.test.com") + self.assertEquals(presence.get_to(), "test1@test.com") + self.assertEquals(presence.get_node().prop("type"), "probe") + presence = self.comp.stream.sent[4] + self.assertTrue(isinstance(presence, Presence)) + self.assertEquals(presence.get_from(), "account2@jcl.test.com") + self.assertEquals(presence.get_to(), "test2@test.com") + self.assertEquals(presence.get_node().prop("type"), "probe") + +class JCLComponent_signal_handler_TestCase(JCLComponent_TestCase): + """signal_handler' tests""" + + def test_signal_handler(self): + self.comp.running = True + self.comp.signal_handler(42, None) + self.assertFalse(self.comp.running) + +class JCLComponent_handle_get_gateway_TestCase(JCLComponent_TestCase): + """handle_get_gateway' tests""" + + def test_handle_get_gateway(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + info_query = Iq(stanza_type="get", + from_jid="user1@test.com") + info_query.new_query("jabber:iq:gateway") + self.comp.handle_get_gateway(info_query) + self.assertEquals(len(self.comp.stream.sent), 1) + iq_sent = self.comp.stream.sent[0] + self.assertEquals(iq_sent.get_to(), "user1@test.com") + self.assertEquals(len(iq_sent.xpath_eval("*/*")), 2) + desc_nodes = iq_sent.xpath_eval("jig:query/jig:desc", + {"jig" : "jabber:iq:gateway"}) + self.assertEquals(len(desc_nodes), 1) + self.assertEquals(desc_nodes[0].content, Lang.en.get_gateway_desc) + prompt_nodes = iq_sent.xpath_eval("jig:query/jig:prompt", + {"jig" : "jabber:iq:gateway"}) + self.assertEquals(len(prompt_nodes), 1) + self.assertEquals(prompt_nodes[0].content, Lang.en.get_gateway_prompt) + +class JCLComponent_handle_set_gateway_TestCase(JCLComponent_TestCase): + """handle_set_gateway' tests""" + + def test_handle_set_gateway(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + info_query = Iq(stanza_type="get", + from_jid="user1@test.com") + query = info_query.new_query("jabber:iq:gateway") + prompt = query.newChild(None, "prompt", None) + prompt.addContent("user@test.com") + self.comp.handle_set_gateway(info_query) + self.assertEquals(len(self.comp.stream.sent), 1) + iq_sent = self.comp.stream.sent[0] + self.assertEquals(iq_sent.get_to(), "user1@test.com") + self.assertEquals(len(iq_sent.xpath_eval("*/*")), 2) + jid_nodes = iq_sent.xpath_eval("jig:query/jig:jid", + {"jig" : "jabber:iq:gateway"}) + self.assertEquals(len(jid_nodes), 1) + self.assertEquals(jid_nodes[0].content, "user%test.com@jcl.test.com") + +class JCLComponent_disco_get_info_TestCase(JCLComponent_TestCase): + """disco_get_info' tests""" + + def test_disco_get_info(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + info_query = Iq(stanza_type="get", + from_jid="user1@test.com", + to_jid="jcl.test.com") + disco_info = self.comp.disco_get_info(None, info_query) + self.assertEquals(disco_info.get_node(), None) + self.assertEquals(len(self.comp.stream.sent), 0) + self.assertEquals(disco_info.get_identities()[0].get_name(), self.comp.name) + self.assertTrue(disco_info.has_feature("jabber:iq:version")) + self.assertTrue(disco_info.has_feature(vcard.VCARD_NS)) + self.assertTrue(disco_info.has_feature("jabber:iq:last")) + self.assertTrue(disco_info.has_feature("jabber:iq:register")) + + def test_disco_get_info_multiple_account_type(self): + self.comp.account_manager.account_classes = (ExampleAccount, Example2Account) + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + info_query = Iq(stanza_type="get", + from_jid="user1@test.com", + to_jid="jcl.test.com") + disco_info = self.comp.disco_get_info(None, info_query) + self.assertEquals(disco_info.get_node(), None) + self.assertEquals(len(self.comp.stream.sent), 0) + self.assertEquals(disco_info.get_identities()[0].get_name(), + self.comp.name) + self.assertTrue(disco_info.has_feature("jabber:iq:version")) + self.assertTrue(disco_info.has_feature(vcard.VCARD_NS)) + self.assertTrue(disco_info.has_feature("jabber:iq:last")) + self.assertFalse(disco_info.has_feature("jabber:iq:register")) + + def test_disco_get_info_node(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + info_query = Iq(stanza_type="get", + from_jid="user1@test.com", + to_jid="node_test@jcl.test.com") + disco_info = self.comp.disco_get_info("node_test", info_query) + self.assertEquals(disco_info.get_node(), "node_test") + self.assertEquals(len(self.comp.stream.sent), 0) + self.assertTrue(disco_info.has_feature(vcard.VCARD_NS)) + self.assertTrue(disco_info.has_feature("jabber:iq:last")) + self.assertTrue(disco_info.has_feature("jabber:iq:register")) + + def test_disco_get_info_long_node(self): + self.comp.account_manager.account_classes = (ExampleAccount, Example2Account) + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + info_query = Iq(stanza_type="get", + from_jid="user1@test.com", + to_jid="node_test@jcl.test.com/node_type") + disco_info = self.comp.disco_get_info("node_type/node_test", + info_query) + self.assertEquals(disco_info.get_node(), "node_type/node_test") + self.assertEquals(len(self.comp.stream.sent), 0) + self.assertTrue(disco_info.has_feature(vcard.VCARD_NS)) + self.assertTrue(disco_info.has_feature("jabber:iq:last")) + self.assertTrue(disco_info.has_feature("jabber:iq:register")) + + def test_disco_get_info_root_unknown_node(self): + info_query = Iq(stanza_type="get", + from_jid="user1@test.com", + to_jid="jcl.test.com") + disco_info = self.comp.disco_get_info("unknown", info_query) + self.assertEquals(disco_info, None) + + def test_disco_get_info_command_list(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + info_query = Iq(stanza_type="get", + from_jid="user1@test.com", + to_jid="jcl.test.com") + disco_info = self.comp.disco_get_info(\ + "http://jabber.org/protocol/admin#get-disabled-users-num", + info_query) + self.assertEquals(len(self.comp.stream.sent), 0) + self.assertEquals(\ + disco_info.get_node(), + "http://jabber.org/protocol/admin#get-disabled-users-num") + self.assertTrue(disco_info.has_feature("http://jabber.org/protocol/commands")) + self.assertEquals(len(disco_info.get_identities()), 1) + self.assertEquals(disco_info.get_identities()[0].get_category(), + "automation") + self.assertEquals(disco_info.get_identities()[0].get_type(), + "command-node") + self.assertEquals(disco_info.get_identities()[0].get_name(), + Lang.en.command_get_disabled_users_num) + +class JCLComponent_disco_get_items_TestCase(JCLComponent_TestCase): + """disco_get_items' tests""" + + def test_disco_get_items_1type_no_node(self): + """get_items on main entity. Must list accounts""" + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + account1 = Account(user=User(jid="user1@test.com"), + name="account1", + jid="account1@jcl.test.com") + info_query = Iq(stanza_type="get", + from_jid="user1@test.com", + to_jid="jcl.test.com") + disco_items = self.comp.disco_get_items(None, info_query) + self.assertEquals(disco_items.get_node(), None) + self.assertEquals(len(disco_items.get_items()), 1) + disco_item = disco_items.get_items()[0] + self.assertEquals(disco_item.get_jid(), account1.jid) + self.assertEquals(disco_item.get_node(), account1.name) + self.assertEquals(disco_item.get_name(), account1.long_name) + + def test_disco_get_items_unknown_node(self): + self.comp.account_manager.account_classes = (ExampleAccount, ) + account11 = ExampleAccount(user=User(jid="user1@test.com"), + name="account11", + jid="account11@jcl.test.com") + info_query = Iq(stanza_type="get", + from_jid="user1@test.com", + to_jid="jcl.test.com") + disco_items = self.comp.disco_get_items("unknown", info_query) + self.assertEquals(disco_items, None) + + def test_disco_get_items_unknown_node_multiple_account_types(self): + self.comp.account_manager.account_classes = (ExampleAccount, Example2Account) + user1 = User(jid="user1@test.com") + account11 = ExampleAccount(user=user1, + name="account11", + jid="account11@jcl.test.com") + account21 = Example2Account(user=user1, + name="account21", + jid="account21@jcl.test.com") + info_query = Iq(stanza_type="get", + from_jid="user1@test.com", + to_jid="jcl.test.com") + self.comp.account_manager.has_multiple_account_type = True + disco_items = self.comp.disco_get_items("unknown", info_query) + self.assertEquals(disco_items, None) + + def test_disco_get_items_1type_with_node(self): + """get_items on an account. Must return nothing""" + account1 = Account(user=User(jid="user1@test.com"), + name="account1", + jid="account1@jcl.test.com") + info_query = Iq(stanza_type="get", + from_jid="user1@test.com", + to_jid="account1@jcl.test.com") + disco_items = self.comp.disco_get_items("account1", info_query) + self.assertEquals(disco_items, None) + + def test_disco_get_items_2types_no_node(self): + """get_items on main entity. Must account types""" + self.comp.lang = LangExample() + self.comp.account_manager.account_classes = (ExampleAccount, Example2Account) + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + user1 = User(jid="user1@test.com") + account11 = ExampleAccount(user=user1, + name="account11", + jid="account11@jcl.test.com") + account21 = Example2Account(user=user1, + name="account21", + jid="account21@jcl.test.com") + info_query = Iq(stanza_type="get", + from_jid="user1@test.com", + to_jid="jcl.test.com") + disco_items = self.comp.disco_get_items(None, info_query) + self.assertEquals(disco_items.get_node(), None) + self.assertEquals(len(disco_items.get_items()), 2) + disco_item = disco_items.get_items()[0] + self.assertEquals(unicode(disco_item.get_jid()), + unicode(self.comp.jid) + "/Example") + self.assertEquals(disco_item.get_node(), "Example") + self.assertEquals(disco_item.get_name(), + LangExample.en.type_example_name) + disco_item = disco_items.get_items()[1] + self.assertEquals(unicode(disco_item.get_jid()), + unicode(self.comp.jid) + "/Example2") + self.assertEquals(disco_item.get_node(), "Example2") + # no name in language class for type Example2, so fallback on type name + self.assertEquals(disco_item.get_name(), "Example2") + + # Be careful, account_classes cannot contains parent classes + # + def test_disco_get_items_2types_with_node(self): + """get_items on the first account type node. Must return account list of + that type for the current user""" + self.comp.account_manager.account_classes = (ExampleAccount, Example2Account) + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + user1 = User(jid="user1@test.com") + user2 = User(jid="user2@test.com") + account11 = ExampleAccount(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = ExampleAccount(user=user2, + name="account12", + jid="account12@jcl.test.com") + account21 = Example2Account(user=user1, + name="account21", + jid="account21@jcl.test.com") + account22 = Example2Account(user=user2, + name="account22", + jid="account22@jcl.test.com") + info_query = Iq(stanza_type="get", + from_jid="user1@test.com", + to_jid="jcl.test.com/Example") + disco_items = self.comp.disco_get_items("Example", info_query) + self.assertEquals(disco_items.get_node(), "Example") + self.assertEquals(len(disco_items.get_items()), 1) + disco_item = disco_items.get_items()[0] + self.assertEquals(unicode(disco_item.get_jid()), unicode(account11.jid) + "/Example") + self.assertEquals(disco_item.get_node(), "Example/" + account11.name) + self.assertEquals(disco_item.get_name(), account11.long_name) + + def test_disco_get_items_2types_with_node2(self): + """get_items on the second account type node. Must return account list of + that type for the current user""" + self.comp.account_manager.account_classes = (ExampleAccount, Example2Account) + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + user1 = User(jid="user1@test.com") + user2 = User(jid="user2@test.com") + account11 = ExampleAccount(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = ExampleAccount(user=user2, + name="account12", + jid="account12@jcl.test.com") + account21 = Example2Account(user=user1, + name="account21", + jid="account21@jcl.test.com") + account22 = Example2Account(user=user2, + name="account22", + jid="account22@jcl.test.com") + info_query = Iq(stanza_type="get", + from_jid="user2@test.com", + to_jid="jcl.test.com/Example2") + disco_items = self.comp.disco_get_items("Example2", info_query) + self.assertEquals(len(disco_items.get_items()), 1) + self.assertEquals(disco_items.get_node(), "Example2") + disco_item = disco_items.get_items()[0] + self.assertEquals(unicode(disco_item.get_jid()), unicode(account22.jid) + "/Example2") + self.assertEquals(disco_item.get_node(), "Example2/" + account22.name) + self.assertEquals(disco_item.get_name(), account22.long_name) + + def test_disco_get_items_2types_with_long_node(self): + """get_items on a first type account. Must return nothing""" + self.comp.account_manager.account_classes = (ExampleAccount, Example2Account) + account1 = ExampleAccount(user=User(jid="user1@test.com"), + name="account1", + jid="account1@jcl.test.com") + info_query = Iq(stanza_type="get", + from_jid="user1@test.com", + to_jid="account1@jcl.test.com/Example") + disco_items = self.comp.disco_get_items("Example/account1", info_query) + self.assertEquals(disco_items, None) + + def test_disco_get_items_2types_with_long_node2(self): + """get_items on a second type account. Must return nothing""" + self.comp.account_manager.account_classes = (ExampleAccount, Example2Account) + account1 = Example2Account(user=User(jid="user1@test.com"), + name="account1", + jid="account1@jcl.test.com") + info_query = Iq(stanza_type="get", + from_jid="user1@test.com", + to_jid="account1@jcl.test.com/Example2") + disco_items = self.comp.disco_get_items("Example2/account1", + info_query) + self.assertEquals(disco_items, None) + + def test_disco_root_get_items_list_commands(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.comp.config = ConfigParser() + self.comp.config_file = config_file + self.comp.config.read(config_file) + self.comp.set_admins(["admin@test.com"]) + command.command_manager.commands["accounttype_command"] = \ + (True, command.account_type_node_re) + command.command_manager.commands["account_command"] = \ + (True, command.account_node_re) + info_query = Iq(stanza_type="get", + from_jid="admin@test.com", + to_jid="jcl.test.com") + disco_items = self.comp.disco_get_items(\ + "http://jabber.org/protocol/commands", + info_query) + self.assertEquals(disco_items.get_node(), + "http://jabber.org/protocol/commands") + self.assertEquals(len(disco_items.get_items()), 22) + +class JCLComponent_handle_get_version_TestCase(JCLComponent_TestCase): + """handle_get_version' tests""" + + def test_handle_get_version(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.handle_get_version(Iq(stanza_type = "get", \ + from_jid = "user1@test.com")) + self.assertEquals(len(self.comp.stream.sent), 1) + iq_sent = self.comp.stream.sent[0] + self.assertEquals(iq_sent.get_to(), "user1@test.com") + self.assertEquals(len(iq_sent.xpath_eval("*/*")), 2) + name_nodes = iq_sent.xpath_eval("jiv:query/jiv:name", \ + {"jiv" : "jabber:iq:version"}) + self.assertEquals(len(name_nodes), 1) + self.assertEquals(name_nodes[0].content, self.comp.name) + version_nodes = iq_sent.xpath_eval("jiv:query/jiv:version", \ + {"jiv" : "jabber:iq:version"}) + self.assertEquals(len(version_nodes), 1) + self.assertEquals(version_nodes[0].content, self.comp.version) + +class JCLComponent_handle_get_register_TestCase(JCLComponent_TestCase): + """handle_get_register' tests""" + + def test_handle_get_register_new(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.handle_get_register(Iq(stanza_type = "get", \ + from_jid = "user1@test.com", \ + to_jid = "jcl.test.com")) + self.assertEquals(len(self.comp.stream.sent), 1) + iq_sent = self.comp.stream.sent[0] + self.assertEquals(iq_sent.get_to(), "user1@test.com") + titles = iq_sent.xpath_eval("jir:query/jxd:x/jxd:title", \ + {"jir" : "jabber:iq:register", \ + "jxd" : "jabber:x:data"}) + self.assertEquals(len(titles), 1) + self.assertEquals(titles[0].content, \ + Lang.en.register_title) + instructions = iq_sent.xpath_eval("jir:query/jxd:x/jxd:instructions", \ + {"jir" : "jabber:iq:register", \ + "jxd" : "jabber:x:data"}) + self.assertEquals(len(instructions), 1) + self.assertEquals(instructions[0].content, \ + Lang.en.register_instructions) + fields = iq_sent.xpath_eval("jir:query/jxd:x/jxd:field", \ + {"jir" : "jabber:iq:register", \ + "jxd" : "jabber:x:data"}) + self.assertEquals(len(fields), 1) + self.assertEquals(fields[0].prop("type"), "text-single") + self.assertEquals(fields[0].prop("var"), "name") + self.assertEquals(fields[0].prop("label"), Lang.en.account_name) + self.assertEquals(fields[0].children.name, "required") + + def __check_get_register_new_type(self): + self.assertEquals(len(self.comp.stream.sent), 1) + iq_sent = self.comp.stream.sent[0] + self.assertEquals(iq_sent.get_to(), "user1@test.com") + titles = iq_sent.xpath_eval("jir:query/jxd:x/jxd:title", \ + {"jir" : "jabber:iq:register", \ + "jxd" : "jabber:x:data"}) + self.assertEquals(len(titles), 1) + self.assertEquals(titles[0].content, \ + Lang.en.register_title) + instructions = iq_sent.xpath_eval("jir:query/jxd:x/jxd:instructions", \ + {"jir" : "jabber:iq:register", \ + "jxd" : "jabber:x:data"}) + self.assertEquals(len(instructions), 1) + self.assertEquals(instructions[0].content, \ + Lang.en.register_instructions) + fields = iq_sent.xpath_eval("jir:query/jxd:x/jxd:field", \ + {"jir" : "jabber:iq:register", \ + "jxd" : "jabber:x:data"}) + self.assertEquals(len(fields), 6) + self.assertEquals(fields[0].prop("type"), "text-single") + self.assertEquals(fields[0].prop("var"), "name") + self.assertEquals(fields[0].prop("label"), Lang.en.account_name) + self.assertEquals(fields[0].children.name, "required") + + self.assertEquals(fields[1].prop("type"), "text-single") + self.assertEquals(fields[1].prop("var"), "login") + self.assertEquals(fields[1].prop("label"), "login") + self.assertEquals(fields[0].children.name, "required") + + self.assertEquals(fields[2].prop("type"), "text-private") + self.assertEquals(fields[2].prop("var"), "password") + self.assertEquals(fields[2].prop("label"), Lang.en.field_password) + + self.assertEquals(fields[3].prop("type"), "boolean") + self.assertEquals(fields[3].prop("var"), "store_password") + self.assertEquals(fields[3].prop("label"), "store_password") + + self.assertEquals(fields[4].prop("type"), "list-single") + self.assertEquals(fields[4].prop("var"), "test_enum") + self.assertEquals(fields[4].prop("label"), "test_enum") + options = iq_sent.xpath_eval("jir:query/jxd:x/jxd:field/jxd:option", \ + {"jir" : "jabber:iq:register", \ + "jxd" : "jabber:x:data"}) + + self.assertEquals(options[0].prop("label"), "choice1") + self.assertEquals(options[0].children.content, "choice1") + self.assertEquals(options[0].children.name, "value") + self.assertEquals(options[1].prop("label"), "choice2") + self.assertEquals(options[1].children.content, "choice2") + self.assertEquals(options[1].children.name, "value") + self.assertEquals(options[2].prop("label"), "choice3") + self.assertEquals(options[2].children.content, "choice3") + self.assertEquals(options[2].children.name, "value") + + self.assertEquals(fields[5].prop("type"), "text-single") + self.assertEquals(fields[5].prop("var"), "test_int") + self.assertEquals(fields[5].prop("label"), "test_int") + + def test_handle_get_register_new_complex(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.account_manager.account_classes = (ExampleAccount,) + self.comp.handle_get_register(Iq(stanza_type = "get", \ + from_jid = "user1@test.com", \ + to_jid = "jcl.test.com")) + self.__check_get_register_new_type() + + def test_handle_get_register_exist(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account21 = Account(user=User(jid="user2@test.com"), + name="account21", + jid="account21@jcl.test.com") + model.db_disconnect() + self.comp.handle_get_register(Iq(stanza_type="get", + from_jid="user1@test.com", + to_jid="account11@jcl.test.com")) + self.assertEquals(len(self.comp.stream.sent), 1) + iq_sent = self.comp.stream.sent[0] + self.assertEquals(iq_sent.get_to(), "user1@test.com") + titles = iq_sent.xpath_eval("jir:query/jxd:x/jxd:title", + {"jir" : "jabber:iq:register", + "jxd" : "jabber:x:data"}) + self.assertEquals(len(titles), 1) + self.assertEquals(titles[0].content, + Lang.en.register_title) + instructions = iq_sent.xpath_eval("jir:query/jxd:x/jxd:instructions", + {"jir" : "jabber:iq:register", + "jxd" : "jabber:x:data"}) + self.assertEquals(len(instructions), 1) + self.assertEquals(instructions[0].content, + Lang.en.register_instructions) + fields = iq_sent.xpath_eval("jir:query/jxd:x/jxd:field", + {"jir" : "jabber:iq:register", + "jxd" : "jabber:x:data"}) + self.assertEquals(len(fields), 1) + self.assertEquals(fields[0].prop("type"), "hidden") + self.assertEquals(fields[0].prop("var"), "name") + self.assertEquals(fields[0].prop("label"), Lang.en.account_name) + self.assertEquals(fields[0].children.next.name, "required") + value = iq_sent.xpath_eval("jir:query/jxd:x/jxd:field/jxd:value", + {"jir" : "jabber:iq:register", + "jxd" : "jabber:x:data"}) + self.assertEquals(len(value), 1) + self.assertEquals(value[0].content, "account11") + + def test_handle_get_register_exist_complex(self): + model.db_connect() + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + user1 = User(jid="user1@test.com") + account1 = ExampleAccount(user=user1, + name="account1", + jid="account1@jcl.test.com", + login="mylogin", + password="mypassword", + store_password=False, + test_enum="choice3", + test_int=1) + account11 = ExampleAccount(user=user1, + name="account11", + jid="account11@jcl.test.com", + login="mylogin11", + password="mypassword11", + store_password=False, + test_enum="choice2", + test_int=11) + account21 = ExampleAccount(user=User(jid="user2@test.com"), + name="account21", + jid="account21@jcl.test.com", + login="mylogin21", + password="mypassword21", + store_password=False, + test_enum="choice1", + test_int=21) + model.db_disconnect() + self.comp.handle_get_register(Iq(stanza_type="get", + from_jid="user1@test.com", + to_jid="account1@jcl.test.com")) + self.assertEquals(len(self.comp.stream.sent), 1) + iq_sent = self.comp.stream.sent[0] + self.assertEquals(iq_sent.get_to(), "user1@test.com") + titles = iq_sent.xpath_eval("jir:query/jxd:x/jxd:title", + {"jir" : "jabber:iq:register", + "jxd" : "jabber:x:data"}) + self.assertEquals(len(titles), 1) + self.assertEquals(titles[0].content, + Lang.en.register_title) + instructions = iq_sent.xpath_eval("jir:query/jxd:x/jxd:instructions", + {"jir" : "jabber:iq:register", + "jxd" : "jabber:x:data"}) + self.assertEquals(len(instructions), 1) + self.assertEquals(instructions[0].content, + Lang.en.register_instructions) + fields = iq_sent.xpath_eval("jir:query/jxd:x/jxd:field", + {"jir" : "jabber:iq:register", + "jxd" : "jabber:x:data"}) + self.assertEquals(len(fields), 6) + field = fields[0] + self.assertEquals(field.prop("type"), "hidden") + self.assertEquals(field.prop("var"), "name") + self.assertEquals(field.prop("label"), Lang.en.account_name) + self.assertEquals(field.children.name, "value") + self.assertEquals(field.children.content, "account1") + self.assertEquals(field.children.next.name, "required") + field = fields[1] + self.assertEquals(field.prop("type"), "text-single") + self.assertEquals(field.prop("var"), "login") + self.assertEquals(field.prop("label"), "login") + self.assertEquals(field.children.name, "value") + self.assertEquals(field.children.content, "mylogin") + self.assertEquals(field.children.next.name, "required") + field = fields[2] + self.assertEquals(field.prop("type"), "text-private") + self.assertEquals(field.prop("var"), "password") + self.assertEquals(field.prop("label"), Lang.en.field_password) + self.assertEquals(field.children.name, "value") + self.assertEquals(field.children.content, "mypassword") + field = fields[3] + self.assertEquals(field.prop("type"), "boolean") + self.assertEquals(field.prop("var"), "store_password") + self.assertEquals(field.prop("label"), "store_password") + self.assertEquals(field.children.name, "value") + self.assertEquals(field.children.content, "0") + field = fields[4] + self.assertEquals(field.prop("type"), "list-single") + self.assertEquals(field.prop("var"), "test_enum") + self.assertEquals(field.prop("label"), "test_enum") + self.assertEquals(field.children.name, "value") + self.assertEquals(field.children.content, "choice3") + options = iq_sent.xpath_eval("jir:query/jxd:x/jxd:field/jxd:option", + {"jir" : "jabber:iq:register", + "jxd" : "jabber:x:data"}) + + self.assertEquals(options[0].prop("label"), "choice1") + self.assertEquals(options[0].children.name, "value") + self.assertEquals(options[0].children.content, "choice1") + self.assertEquals(options[1].prop("label"), "choice2") + self.assertEquals(options[1].children.content, "choice2") + self.assertEquals(options[1].children.name, "value") + self.assertEquals(options[2].prop("label"), "choice3") + self.assertEquals(options[2].children.content, "choice3") + self.assertEquals(options[2].children.name, "value") + + field = fields[5] + self.assertEquals(field.prop("type"), "text-single") + self.assertEquals(field.prop("var"), "test_int") + self.assertEquals(field.prop("label"), "test_int") + self.assertEquals(field.children.name, "value") + self.assertEquals(field.children.content, "1") + + def test_handle_get_register_new_type1(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.account_manager.account_classes = (ExampleAccount, Example2Account) + self.comp.handle_get_register(Iq(stanza_type="get", + from_jid="user1@test.com", + to_jid="jcl.test.com/example")) + self.__check_get_register_new_type() + + def test_handle_get_register_new_type2(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.account_manager.account_classes = (ExampleAccount, Example2Account) + self.comp.handle_get_register(Iq(stanza_type="get", + from_jid=JID("user1@test.com"), + to_jid=JID("jcl.test.com/example2"))) + self.assertEquals(len(self.comp.stream.sent), 1) + iq_sent = self.comp.stream.sent[0] + self.assertEquals(iq_sent.get_to(), "user1@test.com") + titles = iq_sent.xpath_eval("jir:query/jxd:x/jxd:title", + {"jir" : "jabber:iq:register", + "jxd" : "jabber:x:data"}) + self.assertEquals(len(titles), 1) + self.assertEquals(titles[0].content, + Lang.en.register_title) + instructions = iq_sent.xpath_eval("jir:query/jxd:x/jxd:instructions", + {"jir" : "jabber:iq:register", + "jxd" : "jabber:x:data"}) + self.assertEquals(len(instructions), 1) + self.assertEquals(instructions[0].content, + Lang.en.register_instructions) + fields = iq_sent.xpath_eval("jir:query/jxd:x/jxd:field", + {"jir" : "jabber:iq:register", + "jxd" : "jabber:x:data"}) + self.assertEquals(len(fields), 2) + self.assertEquals(fields[0].prop("type"), "text-single") + self.assertEquals(fields[0].prop("var"), "name") + self.assertEquals(fields[0].prop("label"), Lang.en.account_name) + self.assertEquals(fields[0].children.name, "required") + + self.assertEquals(fields[1].prop("type"), "text-single") + self.assertEquals(fields[1].prop("var"), "test_new_int") + self.assertEquals(fields[1].prop("label"), "test_new_int") + +class JCLComponent_handle_set_register_TestCase(JCLComponent_TestCase): + """handle_set_register' tests""" + + def test_handle_set_register_new(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + x_data = Form("submit") + x_data.add_field(name="name", + value="account1", + field_type="text-single") + iq_set = Iq(stanza_type="set", + from_jid="user1@test.com/res", + to_jid="jcl.test.com") + query = iq_set.new_query("jabber:iq:register") + x_data.as_xml(query, None) + self.comp.handle_set_register(iq_set) + + model.db_connect() + _account = account.get_account("user1@test.com", "account1") + self.assertNotEquals(_account, None) + self.assertEquals(_account.user.jid, "user1@test.com") + self.assertEquals(_account.name, "account1") + self.assertEquals(_account.jid, "account1@jcl.test.com") + model.db_disconnect() + + stanza_sent = self.comp.stream.sent + self.assertEquals(len(stanza_sent), 4) + iq_result = stanza_sent[0] + self.assertTrue(isinstance(iq_result, Iq)) + self.assertEquals(iq_result.get_node().prop("type"), "result") + self.assertEquals(iq_result.get_from(), "jcl.test.com") + self.assertEquals(iq_result.get_to(), "user1@test.com/res") + + presence_component = stanza_sent[1] + self.assertTrue(isinstance(presence_component, Presence)) + self.assertEquals(presence_component.get_from(), "jcl.test.com") + self.assertEquals(presence_component.get_to(), "user1@test.com") + self.assertEquals(presence_component.get_node().prop("type"), + "subscribe") + + message = stanza_sent[2] + self.assertTrue(isinstance(message, Message)) + self.assertEquals(message.get_from(), "jcl.test.com") + self.assertEquals(message.get_to(), "user1@test.com/res") + self.assertEquals(message.get_subject(), + _account.get_new_message_subject(Lang.en)) + self.assertEquals(message.get_body(), + _account.get_new_message_body(Lang.en)) + + presence_account = stanza_sent[3] + self.assertTrue(isinstance(presence_account, Presence)) + self.assertEquals(presence_account.get_from(), "account1@jcl.test.com") + self.assertEquals(presence_account.get_to(), "user1@test.com") + self.assertEquals(presence_account.get_node().prop("type"), + "subscribe") + + def test_handle_set_register_new_with_welcome_message(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.comp.config_file = config_file + self.comp.config = ConfigParser() + self.comp.config.read(self.comp.config_file) + self.comp.config.add_section("component") + self.comp.config.set("component", "welcome_message", + "Welcome Message") + self.comp.config.write(open(self.comp.config_file, "w")) + x_data = Form("submit") + x_data.add_field(name="name", + value="account1", + field_type="text-single") + iq_set = Iq(stanza_type="set", + from_jid="user1@test.com/res", + to_jid="jcl.test.com") + query = iq_set.new_query("jabber:iq:register") + x_data.as_xml(query, None) + self.comp.handle_set_register(iq_set) + + model.db_connect() + _account = account.get_account("user1@test.com", "account1") + self.assertNotEquals(_account, None) + self.assertEquals(_account.user.jid, "user1@test.com") + self.assertEquals(_account.name, "account1") + self.assertEquals(_account.jid, "account1@jcl.test.com") + model.db_disconnect() + + stanza_sent = self.comp.stream.sent + self.assertEquals(len(stanza_sent), 5) + iq_result = stanza_sent[0] + self.assertTrue(isinstance(iq_result, Iq)) + self.assertEquals(iq_result.get_node().prop("type"), "result") + self.assertEquals(iq_result.get_from(), "jcl.test.com") + self.assertEquals(iq_result.get_to(), "user1@test.com/res") + + presence_component = stanza_sent[1] + self.assertTrue(isinstance(presence_component, Presence)) + self.assertEquals(presence_component.get_from(), "jcl.test.com") + self.assertEquals(presence_component.get_to(), "user1@test.com") + self.assertEquals(presence_component.get_node().prop("type"), + "subscribe") + + message = stanza_sent[2] + self.assertTrue(isinstance(message, Message)) + self.assertEquals(message.get_from(), "jcl.test.com") + self.assertEquals(message.get_to(), "user1@test.com/res") + self.assertEquals(message.get_subject(), + Lang.en.welcome_message_subject) + self.assertEquals(message.get_body(), + "Welcome Message") + + message = stanza_sent[3] + self.assertTrue(isinstance(message, Message)) + self.assertEquals(message.get_from(), "jcl.test.com") + self.assertEquals(message.get_to(), "user1@test.com/res") + self.assertEquals(message.get_subject(), + _account.get_new_message_subject(Lang.en)) + self.assertEquals(message.get_body(), + _account.get_new_message_body(Lang.en)) + + presence_account = stanza_sent[4] + self.assertTrue(isinstance(presence_account, Presence)) + self.assertEquals(presence_account.get_from(), "account1@jcl.test.com") + self.assertEquals(presence_account.get_to(), "user1@test.com") + self.assertEquals(presence_account.get_node().prop("type"), + "subscribe") + os.unlink(config_file) + + def test_handle_set_register_new_multiple_types(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.account_manager.account_classes = (ExampleAccount, Example2Account) + x_data = Form("submit") + x_data.add_field(name="name", + value="account1", + field_type="text-single") + iq_set = Iq(stanza_type="set", + from_jid="user1@test.com/res", + to_jid="jcl.test.com/Example2") + query = iq_set.new_query("jabber:iq:register") + x_data.as_xml(query, None) + self.comp.handle_set_register(iq_set) + + model.db_connect() + _account = account.get_account("user1@test.com", "account1") + self.assertNotEquals(_account, None) + self.assertEquals(_account.user.jid, "user1@test.com") + self.assertEquals(_account.name, "account1") + self.assertEquals(_account.jid, "account1@jcl.test.com") + model.db_disconnect() + + stanza_sent = self.comp.stream.sent + self.assertEquals(len(stanza_sent), 4) + iq_result = stanza_sent[0] + self.assertTrue(isinstance(iq_result, Iq)) + self.assertEquals(iq_result.get_node().prop("type"), "result") + self.assertEquals(iq_result.get_from(), "jcl.test.com/Example2") + self.assertEquals(iq_result.get_to(), "user1@test.com/res") + + presence_component = stanza_sent[1] + self.assertTrue(isinstance(presence_component, Presence)) + self.assertEquals(presence_component.get_from(), "jcl.test.com") + self.assertEquals(presence_component.get_to(), "user1@test.com") + self.assertEquals(presence_component.get_node().prop("type"), + "subscribe") + + message = stanza_sent[2] + self.assertTrue(isinstance(message, Message)) + self.assertEquals(message.get_from(), "jcl.test.com") + self.assertEquals(message.get_to(), "user1@test.com/res") + self.assertEquals(message.get_subject(), + _account.get_new_message_subject(Lang.en)) + self.assertEquals(message.get_body(), + _account.get_new_message_body(Lang.en)) + + presence_account = stanza_sent[3] + self.assertTrue(isinstance(presence_account, Presence)) + self.assertEquals(presence_account.get_from(), "account1@jcl.test.com") + self.assertEquals(presence_account.get_to(), "user1@test.com") + self.assertEquals(presence_account.get_node().prop("type"), + "subscribe") + + def test_handle_set_register_new_complex(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.account_manager.account_classes = (ExampleAccount,) + x_data = Form("submit") + x_data.add_field(name="name", + value="account1", + field_type="text-single") + x_data.add_field(name="login", + value="mylogin", + field_type="text-single") + x_data.add_field(name="password", + value="mypassword", + field_type="text-private") + x_data.add_field(name="store_password", + value=False, + field_type="boolean") + x_data.add_field(name="test_enum", + value="choice3", + field_type="list-single") + x_data.add_field(name="test_int", + value=43, + field_type="text-single") + iq_set = Iq(stanza_type="set", + from_jid="user1@test.com/resource", + to_jid="jcl.test.com") + query = iq_set.new_query("jabber:iq:register") + x_data.as_xml(query, None) + self.comp.handle_set_register(iq_set) + + model.db_connect() + _account = account.get_account("user1@test.com", "account1") + self.assertNotEquals(_account, None) + self.assertEquals(_account.user.jid, "user1@test.com") + self.assertEquals(_account.name, "account1") + self.assertEquals(_account.jid, "account1@jcl.test.com") + self.assertEquals(_account.login, "mylogin") + self.assertEquals(_account.password, "mypassword") + self.assertFalse(_account.store_password) + self.assertEquals(_account.test_enum, "choice3") + self.assertEquals(_account.test_int, 43) + model.db_disconnect() + + stanza_sent = self.comp.stream.sent + self.assertEquals(len(stanza_sent), 4) + iq_result = stanza_sent[0] + self.assertTrue(isinstance(iq_result, Iq)) + self.assertEquals(iq_result.get_node().prop("type"), "result") + self.assertEquals(iq_result.get_from(), "jcl.test.com") + self.assertEquals(iq_result.get_to(), "user1@test.com/resource") + + presence_component = stanza_sent[1] + self.assertTrue(isinstance(presence_component, Presence)) + self.assertEquals(presence_component.get_from(), "jcl.test.com") + self.assertEquals(presence_component.get_to(), "user1@test.com") + self.assertEquals(presence_component.get_node().prop("type"), + "subscribe") + + message = stanza_sent[2] + self.assertTrue(isinstance(message, Message)) + self.assertEquals(message.get_from(), "jcl.test.com") + self.assertEquals(message.get_to(), "user1@test.com/resource") + self.assertEquals(message.get_subject(), + _account.get_new_message_subject(Lang.en)) + self.assertEquals(message.get_body(), + _account.get_new_message_body(Lang.en)) + + presence_account = stanza_sent[3] + self.assertTrue(isinstance(presence_account, Presence)) + self.assertEquals(presence_account.get_from(), "account1@jcl.test.com") + self.assertEquals(presence_account.get_to(), "user1@test.com") + self.assertEquals(presence_account.get_node().prop("type"), + "subscribe") + + def test_handle_set_register_new_default_values(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.account_manager.account_classes = (ExampleAccount,) + x_data = Form("submit") + x_data.add_field(name="name", + value="account1", + field_type="text-single") + x_data.add_field(name="login", + value="mylogin", + field_type="text-single") + iq_set = Iq(stanza_type="set", + from_jid="user1@test.com/res", + to_jid="jcl.test.com") + query = iq_set.new_query("jabber:iq:register") + x_data.as_xml(query) + self.comp.handle_set_register(iq_set) + + model.db_connect() + _account = account.get_account("user1@test.com", "account1") + self.assertNotEquals(_account, None) + self.assertEquals(_account.user.jid, "user1@test.com") + self.assertEquals(_account.name, "account1") + self.assertEquals(_account.jid, "account1@jcl.test.com") + self.assertEquals(_account.login, "mylogin") + self.assertEquals(_account.password, None) + self.assertTrue(_account.store_password) + self.assertEquals(_account.test_enum, "choice2") + self.assertEquals(_account.test_int, 44) + model.db_disconnect() + + def test_handle_set_register_user_already_exists(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.account_manager.account_classes = (ExampleAccount,) + x_data = Form("submit") + x_data.add_field(name="name", + value="account1", + field_type="text-single") + x_data.add_field(name="login", + value="mylogin1", + field_type="text-single") + iq_set = Iq(stanza_type="set", + from_jid="user1@test.com/res", + to_jid="jcl.test.com") + query = iq_set.new_query("jabber:iq:register") + x_data.as_xml(query) + self.comp.handle_set_register(iq_set) + + model.db_connect() + _account = account.get_account("user1@test.com", "account1") + self.assertNotEquals(_account, None) + self.assertEquals(_account.user.jid, "user1@test.com") + self.assertEquals(_account.name, "account1") + self.assertEquals(_account.jid, "account1@jcl.test.com") + self.assertEquals(_account.login, "mylogin1") + self.assertEquals(_account.password, None) + self.assertTrue(_account.store_password) + self.assertEquals(_account.test_enum, "choice2") + self.assertEquals(_account.test_int, 44) + model.db_disconnect() + + x_data = Form("submit") + x_data.add_field(name="name", + value="account2", + field_type="text-single") + x_data.add_field(name="login", + value="mylogin2", + field_type="text-single") + iq_set = Iq(stanza_type="set", + from_jid="user1@test.com/res", + to_jid="jcl.test.com") + query = iq_set.new_query("jabber:iq:register") + x_data.as_xml(query) + self.comp.handle_set_register(iq_set) + + model.db_connect() + _account = account.get_account("user1@test.com", "account2") + self.assertNotEquals(_account, None) + self.assertEquals(_account.user.jid, "user1@test.com") + self.assertEquals(_account.name, "account2") + self.assertEquals(_account.jid, "account2@jcl.test.com") + self.assertEquals(_account.login, "mylogin2") + self.assertEquals(_account.password, None) + self.assertTrue(_account.store_password) + self.assertEquals(_account.test_enum, "choice2") + self.assertEquals(_account.test_int, 44) + + users = account.get_all_users(filter=(User.q.jid == "user1@test.com")) + self.assertEquals(users.count(), 1) + model.db_disconnect() + + def test_handle_set_register_new_name_mandatory(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + x_data = Form("submit") + iq_set = Iq(stanza_type="set", + from_jid="user1@test.com/res", + to_jid="jcl.test.com") + query = iq_set.new_query("jabber:iq:register") + x_data.as_xml(query) + self.comp.handle_set_register(iq_set) + + model.db_connect() + _account = account.get_account("user1@test.com", "account1") + self.assertEquals(_account, None) + model.db_disconnect() + + stanza_sent = self.comp.stream.sent + self.assertEquals(len(stanza_sent), 1) + self.assertTrue(isinstance(stanza_sent[0], Iq)) + self.assertEquals(stanza_sent[0].get_node().prop("type"), "error") + self.assertEquals(stanza_sent[0].get_to(), "user1@test.com/res") + stanza_error = stanza_sent[0].get_error() + self.assertEquals(stanza_error.get_condition().name, + "not-acceptable") + self.assertEquals(stanza_error.get_text(), + Lang.en.field_error % ("name", Lang.en.mandatory_field)) + + def test_handle_set_register_new_field_mandatory(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.account_manager.account_classes = (ExampleAccount,) + x_data = Form("submit") + x_data.add_field(name="name", + value="account1", + field_type="text-single") + iq_set = Iq(stanza_type="set", + from_jid="user1@test.com/res", + to_jid="jcl.test.com") + query = iq_set.new_query("jabber:iq:register") + x_data.as_xml(query) + self.comp.handle_set_register(iq_set) + + model.db_connect() + _account = account.get_account("user1@test.com", "account1") + self.assertEquals(_account, None) + model.db_disconnect() + + stanza_sent = self.comp.stream.sent + self.assertEquals(len(stanza_sent), 1) + self.assertTrue(isinstance(stanza_sent[0], Iq)) + self.assertEquals(stanza_sent[0].get_node().prop("type"), "error") + self.assertEquals(stanza_sent[0].get_to(), "user1@test.com/res") + stanza_error = stanza_sent[0].get_error() + self.assertEquals(stanza_error.get_condition().name, + "not-acceptable") + self.assertEquals(stanza_error.get_text(), + Lang.en.field_error % ("login", Lang.en.mandatory_field)) + + def test_handle_set_register_update_not_existing(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + x_data = Form("submit") + x_data.add_field(name="name", + value="account1", + field_type="text-single") + iq_set = Iq(stanza_type="set", + from_jid="user1@test.com/res", + to_jid="account1@jcl.test.com") + query = iq_set.new_query("jabber:iq:register") + x_data.as_xml(query, None) + self.comp.handle_set_register(iq_set) + + model.db_connect() + _account = account.get_account("user1@test.com", "account1") + self.assertNotEquals(_account, None) + self.assertEquals(_account.user.jid, "user1@test.com") + self.assertEquals(_account.name, "account1") + self.assertEquals(_account.jid, "account1@jcl.test.com") + model.db_disconnect() + + stanza_sent = self.comp.stream.sent + self.assertEquals(len(stanza_sent), 4) + iq_result = stanza_sent[0] + self.assertTrue(isinstance(iq_result, Iq)) + self.assertEquals(iq_result.get_node().prop("type"), "result") + self.assertEquals(iq_result.get_from(), "account1@jcl.test.com") + self.assertEquals(iq_result.get_to(), "user1@test.com/res") + + presence_component = stanza_sent[1] + self.assertTrue(isinstance(presence_component, Presence)) + self.assertEquals(presence_component.get_from(), "jcl.test.com") + self.assertEquals(presence_component.get_to(), "user1@test.com") + self.assertEquals(presence_component.get_node().prop("type"), + "subscribe") + + message = stanza_sent[2] + self.assertTrue(isinstance(message, Message)) + self.assertEquals(message.get_from(), "jcl.test.com") + self.assertEquals(message.get_to(), "user1@test.com/res") + self.assertEquals(message.get_subject(), + _account.get_new_message_subject(Lang.en)) + self.assertEquals(message.get_body(), + _account.get_new_message_body(Lang.en)) + + presence_account = stanza_sent[3] + self.assertTrue(isinstance(presence_account, Presence)) + self.assertEquals(presence_account.get_from(), "account1@jcl.test.com") + self.assertEquals(presence_account.get_to(), "user1@test.com") + self.assertEquals(presence_account.get_node().prop("type"), + "subscribe") + + def test_handle_set_register_update_complex(self): + model.db_connect() + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.account_manager.account_classes = (Example2Account, ExampleAccount) + user1 = User(jid="user1@test.com") + existing_account = ExampleAccount(user=user1, + name="account1", + jid="account1@jcl.test.com", + login="mylogin", + password="mypassword", + store_password=True, + test_enum="choice1", + test_int=21) + another_account = ExampleAccount(user=user1, + name="account2", + jid="account2@jcl.test.com", + login="mylogin", + password="mypassword", + store_password=True, + test_enum="choice1", + test_int=21) + model.db_disconnect() + x_data = Form("submit") + x_data.add_field(name="name", + value="account1", + field_type="text-single") + x_data.add_field(name="login", + value="mylogin2", + field_type="text-single") + x_data.add_field(name="password", + value="mypassword2", + field_type="text-private") + x_data.add_field(name="store_password", + value=False, + field_type="boolean") + x_data.add_field(name="test_enum", + value="choice3", + field_type="list-single") + x_data.add_field(name="test_int", + value=43, + field_type="text-single") + iq_set = Iq(stanza_type="set", + from_jid="user1@test.com/res", + to_jid="account1@jcl.test.com/Example") + query = iq_set.new_query("jabber:iq:register") + x_data.as_xml(query) + self.comp.handle_set_register(iq_set) + + model.db_connect() + _account = account.get_account("user1@test.com", "account1") + self.assertNotEquals(_account, None) + self.assertEquals(_account.__class__.__name__, "ExampleAccount") + self.assertEquals(_account.user.jid, "user1@test.com") + self.assertEquals(_account.name, "account1") + self.assertEquals(_account.jid, "account1@jcl.test.com") + self.assertEquals(_account.login, "mylogin2") + self.assertEquals(_account.password, "mypassword2") + self.assertFalse(_account.store_password) + self.assertEquals(_account.test_enum, "choice3") + self.assertEquals(_account.test_int, 43) + model.db_disconnect() + + stanza_sent = self.comp.stream.sent + self.assertEquals(len(stanza_sent), 2) + iq_result = stanza_sent[0] + self.assertTrue(isinstance(iq_result, Iq)) + self.assertEquals(iq_result.get_node().prop("type"), "result") + self.assertEquals(iq_result.get_from(), "account1@jcl.test.com/Example") + self.assertEquals(iq_result.get_to(), "user1@test.com/res") + + message = stanza_sent[1] + self.assertTrue(isinstance(message, Message)) + self.assertEquals(message.get_from(), "jcl.test.com") + self.assertEquals(message.get_to(), "user1@test.com/res") + self.assertEquals(message.get_subject(), \ + _account.get_update_message_subject(Lang.en)) + self.assertEquals(message.get_body(), \ + _account.get_update_message_body(Lang.en)) + + def test_handle_set_register_remove(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account1", + jid="account1@jcl.test.com") + account12 = Account(user=user1, + name="account2", + jid="account2@jcl.test.com") + account21 = Account(user=User(jid="user2@test.com"), + name="account1", + jid="account1@jcl.test.com") + model.db_disconnect() + iq_set = Iq(stanza_type="set", + from_jid="user1@test.com/res", + to_jid="jcl.test.com") + query = iq_set.new_query("jabber:iq:register") + query.newChild(None, "remove", None) + self.comp.handle_set_register(iq_set) + + model.db_connect() + self.assertEquals(account.get_accounts_count("user1@test.com"), + 0) + self.assertEquals(account.get_all_users(filter=(User.q.jid == "user1@test.com")).count(), + 0) + accounts = account.get_accounts("user2@test.com") + i = 0 + for _account in accounts: + i = i + 1 + self.assertEquals(i, 1) + self.assertEquals(_account.user.jid, "user2@test.com") + self.assertEquals(_account.name, "account1") + self.assertEquals(_account.jid, "account1@jcl.test.com") + model.db_disconnect() + + stanza_sent = self.comp.stream.sent + self.assertEquals(len(stanza_sent), 6) + presence = stanza_sent[0] + self.assertTrue(isinstance(presence, Presence)) + self.assertEquals(presence.get_node().prop("type"), "unsubscribe") + self.assertEquals(presence.get_from(), "account1@jcl.test.com") + self.assertEquals(presence.get_to(), "user1@test.com") + presence = stanza_sent[1] + self.assertTrue(isinstance(presence, Presence)) + self.assertEquals(presence.get_node().prop("type"), "unsubscribed") + self.assertEquals(presence.get_from(), "account1@jcl.test.com") + self.assertEquals(presence.get_to(), "user1@test.com") + presence = stanza_sent[2] + self.assertTrue(isinstance(presence, Presence)) + self.assertEquals(presence.get_node().prop("type"), "unsubscribe") + self.assertEquals(presence.get_from(), "account2@jcl.test.com") + self.assertEquals(presence.get_to(), "user1@test.com") + presence = stanza_sent[3] + self.assertTrue(isinstance(presence, Presence)) + self.assertEquals(presence.get_node().prop("type"), "unsubscribed") + self.assertEquals(presence.get_from(), "account2@jcl.test.com") + self.assertEquals(presence.get_to(), "user1@test.com") + presence = stanza_sent[4] + self.assertTrue(isinstance(presence, Presence)) + self.assertEquals(presence.get_node().prop("type"), "unsubscribe") + self.assertEquals(presence.get_from(), "jcl.test.com") + self.assertEquals(presence.get_to(), "user1@test.com") + presence = stanza_sent[5] + self.assertTrue(isinstance(presence, Presence)) + self.assertEquals(presence.get_node().prop("type"), "unsubscribed") + self.assertEquals(presence.get_from(), "jcl.test.com") + self.assertEquals(presence.get_to(), "user1@test.com") + +class JCLComponent_handle_presence_available_TestCase(JCLComponent_TestCase): + def test_handle_presence_available_to_component(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_available(Presence(\ + stanza_type="available", + from_jid="user1@test.com/resource", + to_jid="jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 3) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_to_jid() == "user1@test.com/resource" \ + and presence.get_type() is None]), + 3) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "jcl.test.com" \ + and isinstance(presence, Presence) \ + and presence.get_type() is None]), + 1) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "account11@jcl.test.com" \ + and isinstance(presence, Presence) \ + and presence.get_type() is None]), + 1) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "account12@jcl.test.com" \ + and isinstance(presence, Presence) \ + and presence.get_type() is None]), + 1) + + def test_handle_presence_available_to_component_legacy_users(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + legacy_jid111 = LegacyJID(legacy_address="u111@test.com", + jid="u111%test.com@jcl.test.com", + account=account11) + legacy_jid112 = LegacyJID(legacy_address="u112@test.com", + jid="u112%test.com@jcl.test.com", + account=account11) + legacy_jid121 = LegacyJID(legacy_address="u121@test.com", + jid="u121%test.com@jcl.test.com", + account=account12) + legacy_jid122 = LegacyJID(legacy_address="u122@test.com", + jid="u122%test.com@jcl.test.com", + account=account12) + legacy_jid21 = LegacyJID(legacy_address="u21@test.com", + jid="u21%test.com@jcl.test.com", + account=account2) + model.db_disconnect() + self.comp.handle_presence_available(Presence(\ + stanza_type="available", + from_jid="user1@test.com/resource", + to_jid="jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 7) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_to_jid() == "user1@test.com/resource" \ + and presence.get_type() is None]), + 7) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "jcl.test.com" + and isinstance(presence, Presence) \ + and presence.get_type() is None]), + 1) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "account11@jcl.test.com" + and isinstance(presence, Presence) \ + and presence.get_type() is None]), + 1) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "account12@jcl.test.com" + and isinstance(presence, Presence) \ + and presence.get_type() is None]), + 1) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "u111%test.com@jcl.test.com" + and isinstance(presence, Presence) \ + and presence.get_type() is None]), + 1) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "u112%test.com@jcl.test.com" + and isinstance(presence, Presence) \ + and presence.get_type() is None]), + 1) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "u121%test.com@jcl.test.com" + and isinstance(presence, Presence) \ + and presence.get_type() is None]), + 1) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "u122%test.com@jcl.test.com" + and isinstance(presence, Presence) \ + and presence.get_type() is None]), + 1) + + def test_handle_presence_available_to_component_unknown_user(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_available(Presence(\ + stanza_type="available", + from_jid="unknown@test.com", + to_jid="jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 0) + + def test_handle_presence_available_to_account(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_available(Presence(\ + stanza_type="available", + from_jid="user1@test.com/resource", + to_jid="account11@jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 1) + self.assertEqual(presence_sent[0].get_to(), "user1@test.com/resource") + self.assertEqual(presence_sent[0].get_from(), "account11@jcl.test.com") + self.assertTrue(isinstance(presence_sent[0], Presence)) + self.assertEqual(presence_sent[0].get_type(), None) + + def test_handle_presence_available_to_registered_handlers(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.presence_available_handlers += [(DefaultPresenceHandler(self.comp),)] + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_available(Presence(\ + stanza_type="available", + from_jid="user1@test.com/resource", + to_jid="user1%test.com@jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 1) + self.assertEqual(presence_sent[0].get_to(), "user1@test.com/resource") + self.assertEqual(presence_sent[0].get_from(), + "user1%test.com@jcl.test.com") + self.assertTrue(isinstance(presence_sent[0], Presence)) + self.assertEqual(presence_sent[0].get_type(), None) + + def test_handle_presence_available_to_account_unknown_user(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_available(Presence(\ + stanza_type="available", + from_jid="unknown@test.com", + to_jid="account11@jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 0) + + def test_handle_presence_available_to_unknown_account(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_available(Presence(\ + stanza_type="available", + from_jid="user1@test.com", + to_jid="unknown@jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 0) + + def test_handle_presence_available_to_account_live_password(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account11.store_password = False + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_available(Presence(\ + stanza_type="available", + from_jid="user1@test.com/resource", + to_jid="account11@jcl.test.com")) + messages_sent = self.comp.stream.sent + self.assertEqual(len(messages_sent), 1) + presence = messages_sent[0] + self.assertTrue(presence is not None) + self.assertTrue(isinstance(presence, Presence)) + self.assertEqual(presence.get_from_jid(), "account11@jcl.test.com") + self.assertEqual(presence.get_to_jid(), "user1@test.com/resource") + self.assertEqual(presence.get_type(), None) + + def test_handle_presence_available_to_account_live_password_complex(self): + model.db_connect() + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + user1 = User(jid="user1@test.com") + account11 = ExampleAccount(user=user1, + name="account11", + jid="account11@jcl.test.com") + account11.store_password = False + account12 = ExampleAccount(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = ExampleAccount(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_available(Presence(\ + stanza_type="available", + from_jid="user1@test.com/resource", + to_jid="account11@jcl.test.com")) + messages_sent = self.comp.stream.sent + self.assertEqual(len(messages_sent), 2) + password_message = None + presence = None + for message in messages_sent: + if isinstance(message, Message): + password_message = message + elif isinstance(message, Presence): + presence = message + self.assertTrue(password_message is not None) + self.assertTrue(presence is not None) + self.assertTrue(isinstance(presence, Presence)) + self.assertEqual(presence.get_from_jid(), "account11@jcl.test.com") + self.assertEqual(presence.get_to_jid(), "user1@test.com/resource") + self.assertEqual(presence.get_type(), None) + + self.assertEqual(unicode(password_message.get_from_jid()), \ + "account11@jcl.test.com") + self.assertEqual(unicode(password_message.get_to_jid()), \ + "user1@test.com/resource") + self.assertEqual(password_message.get_subject(), \ + "[PASSWORD] Password request") + self.assertEqual(password_message.get_body(), \ + Lang.en.ask_password_body % ("account11")) + +class JCLComponent_handle_presence_unavailable_TestCase(JCLComponent_TestCase): + def test_handle_presence_unavailable_to_component(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_unavailable(Presence(\ + stanza_type="unavailable", + from_jid="user1@test.com/resource", + to_jid="jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 3) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_to_jid() == "user1@test.com/resource" \ + and presence.get_type() == "unavailable"]), + 3) + self.assertEqual(\ + len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "jcl.test.com" \ + and presence.xpath_eval("@type")[0].get_content() \ + == "unavailable"]), + 1) + self.assertEqual(\ + len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "account11@jcl.test.com" \ + and presence.xpath_eval("@type")[0].get_content() \ + == "unavailable"]), + 1) + self.assertEqual(\ + len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "account12@jcl.test.com" \ + and presence.xpath_eval("@type")[0].get_content() \ + == "unavailable"]), + 1) + + def test_handle_presence_unavailable_to_component_legacy_users(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + legacy_jid111 = LegacyJID(legacy_address="u111@test.com", + jid="u111%test.com@jcl.test.com", + account=account11) + legacy_jid112 = LegacyJID(legacy_address="u112@test.com", + jid="u112%test.com@jcl.test.com", + account=account11) + legacy_jid121 = LegacyJID(legacy_address="u121@test.com", + jid="u121%test.com@jcl.test.com", + account=account12) + legacy_jid122 = LegacyJID(legacy_address="u122@test.com", + jid="u122%test.com@jcl.test.com", + account=account12) + legacy_jid21 = LegacyJID(legacy_address="u21@test.com", + jid="u21%test.com@jcl.test.com", + account=account2) + model.db_disconnect() + self.comp.handle_presence_unavailable(Presence(\ + stanza_type="unavailable", + from_jid="user1@test.com/resource", + to_jid="jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 7) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_to_jid() == "user1@test.com/resource" \ + and presence.get_type() == "unavailable"]), + 7) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "jcl.test.com" + and isinstance(presence, Presence) \ + and presence.get_type() == "unavailable"]), + 1) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "account11@jcl.test.com" + and isinstance(presence, Presence) \ + and presence.get_type() == "unavailable"]), + 1) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "account12@jcl.test.com" + and isinstance(presence, Presence) \ + and presence.get_type() == "unavailable"]), + 1) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "u111%test.com@jcl.test.com" + and isinstance(presence, Presence) \ + and presence.get_type() == "unavailable"]), + 1) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "u112%test.com@jcl.test.com" + and isinstance(presence, Presence) \ + and presence.get_type() == "unavailable"]), + 1) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "u121%test.com@jcl.test.com" + and isinstance(presence, Presence) \ + and presence.get_type() == "unavailable"]), + 1) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "u122%test.com@jcl.test.com" + and isinstance(presence, Presence) \ + and presence.get_type() == "unavailable"]), + 1) + + def test_handle_presence_unavailable_to_component_unknown_user(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_unavailable(Presence(\ + stanza_type="unavailable", + from_jid="unknown@test.com", + to_jid="jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 0) + + def test_handle_presence_unavailable_to_account(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_unavailable(Presence(\ + stanza_type="unavailable", + from_jid="user1@test.com/resource", + to_jid="account11@jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 1) + self.assertEqual(presence_sent[0].get_to(), "user1@test.com/resource") + self.assertEqual(presence_sent[0].get_from(), "account11@jcl.test.com") + self.assertEqual(\ + presence_sent[0].xpath_eval("@type")[0].get_content(), + "unavailable") + + def test_handle_presence_unavailable_to_registered_handlers(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.presence_unavailable_handlers += [(DefaultPresenceHandler(self.comp),)] + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_unavailable(Presence(\ + stanza_type="unavailable", + from_jid="user1@test.com/resource", + to_jid="user1%test.com@jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 1) + self.assertEqual(presence_sent[0].get_to(), "user1@test.com/resource") + self.assertEqual(presence_sent[0].get_from(), + "user1%test.com@jcl.test.com") + self.assertEqual(\ + presence_sent[0].xpath_eval("@type")[0].get_content(), + "unavailable") + + def test_handle_presence_unavailable_to_account_unknown_user(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_unavailable(Presence(\ + stanza_type="unavailable", + from_jid="unknown@test.com", + to_jid="account11@jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 0) + + def test_handle_presence_unavailable_to_unknown_account(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_unavailable(Presence(\ + stanza_type="unavailable", + from_jid="user1@test.com", + to_jid="unknown@jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 0) + +class JCLComponent_handle_presence_subscribe_TestCase(JCLComponent_TestCase): + def test_handle_presence_subscribe_to_component(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_subscribe(Presence(\ + stanza_type="subscribe", + from_jid="user1@test.com", + to_jid="jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 1) + self.assertEqual(presence_sent[0].get_to(), "user1@test.com") + self.assertEqual(presence_sent[0].get_from(), "jcl.test.com") + self.assertEqual(\ + presence_sent[0].xpath_eval("@type")[0].get_content(), + "subscribed") + + def test_handle_presence_subscribe_to_component_unknown_user(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_subscribe(Presence(\ + stanza_type="subscribe", + from_jid="unknown@test.com", + to_jid="jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 0) + + def test_handle_presence_subscribe_to_account(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_subscribe(Presence(\ + stanza_type="subscribe", + from_jid="user1@test.com", + to_jid="account11@jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 1) + self.assertEqual(presence_sent[0].get_to(), "user1@test.com") + self.assertEqual(presence_sent[0].get_from(), "account11@jcl.test.com") + self.assertEqual(\ + presence_sent[0].xpath_eval("@type")[0].get_content(), + "subscribed") + + def test_handle_presence_subscribe_to_account_unknown_user(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_subscribe(Presence(\ + stanza_type="subscribe", + from_jid="unknown@test.com", + to_jid="account11@jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 0) + + def test_handle_presence_subscribe_to_unknown_account(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_subscribe(Presence(\ + stanza_type="subscribe", + from_jid="user1@test.com", + to_jid="unknown@jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 0) + + def test_handle_presence_subscribe_to_registered_handlers(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.presence_subscribe_handlers += [(DefaultSubscribeHandler(self.comp),)] + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + result = self.comp.handle_presence_subscribe(Presence(\ + stanza_type="subscribe", + from_jid="user1@test.com", + to_jid="user1%test.com@jcl.test.com")) + sent = self.comp.stream.sent + self.assertEqual(len(sent), 2) + self.assertTrue(type(sent[0]), Presence) + self.assertEquals(sent[0].get_type(), "subscribe") + self.assertTrue(type(sent[1]), Presence) + self.assertEquals(sent[1].get_type(), "subscribed") + +class JCLComponent_handle_presence_subscribed_TestCase(JCLComponent_TestCase): + def test_handle_presence_subscribed(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.handle_presence_subscribed(None) + self.assertEqual(len(self.comp.stream.sent), 0) + +class JCLComponent_handle_presence_unsubscribe_TestCase(JCLComponent_TestCase): + def test_handle_presence_unsubscribe_to_account(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_unsubscribe(Presence(\ + stanza_type="unsubscribe", + from_jid="user1@test.com", + to_jid="account11@jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 2) + presence = presence_sent[0] + self.assertEqual(presence.get_from(), "account11@jcl.test.com") + self.assertEqual(presence.get_to(), "user1@test.com") + self.assertEqual(presence.xpath_eval("@type")[0].get_content(), + "unsubscribe") + presence = presence_sent[1] + self.assertEqual(presence.get_from(), "account11@jcl.test.com") + self.assertEqual(presence.get_to(), "user1@test.com") + self.assertEqual(presence.xpath_eval("@type")[0].get_content(), + "unsubscribed") + model.db_connect() + self.assertEquals(account.get_account("user1@test.com", "account11"), + None) + self.assertEquals(account.get_accounts_count("user1@test.com"), + 1) + self.assertEquals(account.get_all_accounts_count(), + 2) + self.assertEquals(account.get_all_users(filter=(User.q.jid == "user1@test.com")).count(), + 1) + model.db_disconnect() + + def test_handle_presence_unsubscribe_to_last_account(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_unsubscribe(Presence(\ + stanza_type="unsubscribe", + from_jid="user1@test.com", + to_jid="account11@jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 2) + presence = presence_sent[0] + self.assertEqual(presence.get_from(), "account11@jcl.test.com") + self.assertEqual(presence.get_to(), "user1@test.com") + self.assertEqual(presence.xpath_eval("@type")[0].get_content(), + "unsubscribe") + presence = presence_sent[1] + self.assertEqual(presence.get_from(), "account11@jcl.test.com") + self.assertEqual(presence.get_to(), "user1@test.com") + self.assertEqual(presence.xpath_eval("@type")[0].get_content(), + "unsubscribed") + model.db_connect() + self.assertEquals(account.get_account("user1@test.com", "account11"), + None) + self.assertEquals(account.get_accounts_count("user1@test.com"), + 0) + self.assertEquals(account.get_all_accounts_count(), + 1) + self.assertEquals(account.get_all_users(filter=(User.q.jid == "user1@test.com")).count(), + 0) + model.db_disconnect() + + def test_handle_presence_unsubscribe_to_root(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_unsubscribe(Presence(\ + stanza_type="unsubscribe", + from_jid="user1@test.com", + to_jid="jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 6) + presence = presence_sent[0] + self.assertEqual(presence.get_from(), "account11@jcl.test.com") + self.assertEqual(presence.get_to(), "user1@test.com") + self.assertEqual(presence.xpath_eval("@type")[0].get_content(), + "unsubscribe") + presence = presence_sent[1] + self.assertEqual(presence.get_from(), "account11@jcl.test.com") + self.assertEqual(presence.get_to(), "user1@test.com") + self.assertEqual(presence.xpath_eval("@type")[0].get_content(), + "unsubscribed") + presence = presence_sent[2] + self.assertEqual(presence.get_from(), "account12@jcl.test.com") + self.assertEqual(presence.get_to(), "user1@test.com") + self.assertEqual(presence.xpath_eval("@type")[0].get_content(), + "unsubscribe") + presence = presence_sent[3] + self.assertEqual(presence.get_from(), "account12@jcl.test.com") + self.assertEqual(presence.get_to(), "user1@test.com") + self.assertEqual(presence.xpath_eval("@type")[0].get_content(), + "unsubscribed") + presence = presence_sent[4] + self.assertEqual(presence.get_from(), "jcl.test.com") + self.assertEqual(presence.get_to(), "user1@test.com") + self.assertEqual(presence.xpath_eval("@type")[0].get_content(), + "unsubscribe") + presence = presence_sent[5] + self.assertEqual(presence.get_from(), "jcl.test.com") + self.assertEqual(presence.get_to(), "user1@test.com") + self.assertEqual(presence.xpath_eval("@type")[0].get_content(), + "unsubscribed") + model.db_connect() + self.assertEquals(account.get_account("user1@test.com", "account11"), + None) + self.assertEquals(account.get_account("user1@test.com", "account12"), + None) + self.assertEquals(account.get_accounts_count("user1@test.com"), + 0) + self.assertEquals(account.get_all_accounts_count(), + 1) + self.assertEquals(account.get_all_users(filter=(User.q.jid == "user1@test.com")).count(), + 0) + model.db_disconnect() + + def test_handle_presence_unsubscribe_to_registered_handlers(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.presence_unsubscribe_handlers += [(DefaultUnsubscribeHandler(self.comp),)] + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_unsubscribe(Presence(\ + stanza_type="unsubscribe", + from_jid="user1@test.com", + to_jid="user1%test.com@jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 2) + presence = presence_sent[0] + self.assertEqual(presence.get_from(), "user1%test.com@jcl.test.com") + self.assertEqual(presence.get_to(), "user1@test.com") + self.assertEqual(presence.xpath_eval("@type")[0].get_content(), + "unsubscribe") + presence = presence_sent[1] + self.assertEqual(presence.get_from(), "user1%test.com@jcl.test.com") + self.assertEqual(presence.get_to(), "user1@test.com") + self.assertEqual(presence.xpath_eval("@type")[0].get_content(), + "unsubscribed") + + def test_handle_presence_unsubscribe_to_account_unknown_user(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_unsubscribe(Presence(\ + stanza_type="unsubscribe", + from_jid="unknown@test.com", + to_jid="account11@jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 0) + model.db_connect() + self.assertEquals(account.get_all_accounts_count(), + 3) + model.db_disconnect() + + def test_handle_presence_unsubscribe_to_unknown_account(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid ="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_presence_unsubscribe(Presence(\ + stanza_type="unsubscribe", + from_jid="user1@test.com", + to_jid="unknown@jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 0) + model.db_connect() + self.assertEquals(account.get_all_accounts_count(), + 3) + model.db_disconnect() + +class JCLComponent_handle_presence_unsubscribed_TestCase(JCLComponent_TestCase): + def test_handle_presence_unsubscribed(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.handle_presence_unsubscribed(Presence(\ + stanza_type = "unsubscribed", \ + from_jid = "user1@test.com",\ + to_jid = "jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 1) + self.assertEqual(presence_sent[0].get_to(), "user1@test.com") + self.assertEqual(presence_sent[0].get_from(), "jcl.test.com") + self.assertEqual(\ + presence_sent[0].xpath_eval("@type")[0].get_content(), \ + "unavailable") + + def test_handle_presence_unsubscribed_to_registered_handler(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.handle_presence_unsubscribed(Presence(\ + stanza_type = "unsubscribed", \ + from_jid = "user1@test.com",\ + to_jid = "user1%test.com@jcl.test.com")) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 1) + self.assertEqual(presence_sent[0].get_to(), "user1@test.com") + self.assertEqual(presence_sent[0].get_from(), "user1%test.com@jcl.test.com") + self.assertEqual(\ + presence_sent[0].xpath_eval("@type")[0].get_content(), \ + "unavailable") + +class JCLComponent_handle_message_TestCase(JCLComponent_TestCase): + def test_handle_message_password(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.authenticated() + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account11.waiting_password_reply = True + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_message(Message(\ + from_jid="user1@test.com", + to_jid="account11@jcl.test.com", + subject="[PASSWORD]", + body="secret")) + messages_sent = self.comp.stream.sent + self.assertEqual(len(messages_sent), 0) + + def test_handle_message_password_complex(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.authenticated() + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = ExampleAccount(user=user1, + name="account11", + jid="account11@jcl.test.com") + account11.waiting_password_reply = True + account12 = ExampleAccount(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = ExampleAccount(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.handle_message(Message(\ + from_jid="user1@test.com", + to_jid="account11@jcl.test.com", + subject="[PASSWORD]", + body="secret")) + messages_sent = self.comp.stream.sent + self.assertEqual(len(messages_sent), 1) + self.assertEqual(messages_sent[0].get_to(), "user1@test.com") + self.assertEqual(messages_sent[0].get_from(), "account11@jcl.test.com") + self.assertEqual(account11.password, "secret") + self.assertEqual(account11.waiting_password_reply, False) + self.assertEqual(messages_sent[0].get_subject(), \ + "Password will be kept during your Jabber session") + self.assertEqual(messages_sent[0].get_body(), \ + "Password will be kept during your Jabber session") + +class JCLComponent_handle_tick_TestCase(JCLComponent_TestCase): + def test_handle_tick(self): + self.assertRaises(NotImplementedError, self.comp.handle_tick) + +class JCLComponent_send_error_TestCase(JCLComponent_TestCase): + def test_send_error_first(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + _account = Account(user=User(jid="user1@test.com"), + name="account11", + jid="account11@jcl.test.com") + exception = Exception("test exception") + self.assertEqual(_account.error, None) + self.comp.send_error(_account, exception) + self.assertEqual(len(self.comp.stream.sent), 2) + error_sent = self.comp.stream.sent[0] + self.assertEqual(error_sent.get_to(), _account.user.jid) + self.assertEqual(error_sent.get_from(), _account.jid) + self.assertEqual(error_sent.get_type(), "error") + self.assertEqual(error_sent.get_subject(), + _account.default_lang_class.error_subject) + self.assertEqual(error_sent.get_body(), + _account.default_lang_class.error_body % (exception)) + new_presence = self.comp.stream.sent[1].xmlnode + self.assertEquals(new_presence.prop("to"), _account.user.jid) + self.assertEquals(new_presence.prop("from"), _account.jid) + self.assertEquals(new_presence.children.name, "show") + self.assertEquals(new_presence.children.content, "dnd") + self.assertEqual(_account.error, "test exception") + + def test_send_error_second(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + _account = Account(user=User(jid="user1@test.com"), + name="account11", + jid="account11@jcl.test.com") + _account.error = "test exception" + exception = Exception("test exception") + self.comp.send_error(_account, exception) + self.assertEqual(_account.error, "test exception") + self.assertEqual(len(self.comp.stream.sent), 0) + +class JCLComponent_send_stanzas_TestCase(JCLComponent_TestCase): + def test_send_stanzas(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + msg1 = Message() + msg2 = Message() + self.comp.send_stanzas([msg1, msg2]) + self.assertEquals(len(self.comp.stream.sent), 2) + self.assertEquals(self.comp.stream.sent[0], msg1) + self.assertEquals(self.comp.stream.sent[1], msg2) + + def test_send_stanzas_none(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.send_stanzas(None) + self.assertEquals(len(self.comp.stream.sent), 0) + + def test_send_stanzas_closed_connection(self): + self.comp.stream = None + self.comp.send_stanzas([Message()]) + +class JCLComponent_get_motd_TestCase(JCLComponent_TestCase): + def test_get_motd(self): + config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.comp.config_file = config_file + self.comp.config = ConfigParser() + self.comp.config.read(self.comp.config_file) + self.comp.config.add_section("component") + self.comp.config.set("component", "motd", "test motd") + self.comp.config.write(open(self.comp.config_file, "w")) + motd = self.comp.get_motd() + self.assertEquals(motd, "test motd") + os.unlink(config_file) + + def test_get_no_motd(self): + config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.comp.config_file = config_file + self.comp.config = ConfigParser() + self.comp.config.read(self.comp.config_file) + self.comp.config.write(open(self.comp.config_file, "w")) + motd = self.comp.get_motd() + self.assertEquals(motd, None) + os.unlink(config_file) + +class JCLComponent_set_motd_TestCase(JCLComponent_TestCase): + def test_set_new_motd(self): + config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.comp.config_file = config_file + self.comp.config = ConfigParser() + self.comp.set_motd("test motd") + self.comp.config.read(self.comp.config_file) + self.assertTrue(self.comp.config.has_option("component", "motd")) + self.assertEquals(self.comp.config.get("component", "motd"), "test motd") + os.unlink(config_file) + + def test_set_motd(self): + config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.comp.config_file = config_file + self.comp.config = ConfigParser() + self.comp.config.add_section("component") + self.comp.config.set("component", "motd", "test motd") + self.comp.config.write(open(self.comp.config_file, "w")) + self.comp.set_motd("test new motd") + self.comp.config.read(self.comp.config_file) + self.assertTrue(self.comp.config.has_option("component", "motd")) + self.assertEquals(self.comp.config.get("component", "motd"), "test new motd") + os.unlink(config_file) + +class JCLComponent_del_motd_TestCase(JCLComponent_TestCase): + def test_del_motd(self): + config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.comp.config_file = config_file + self.comp.config = ConfigParser() + self.comp.config.add_section("component") + self.comp.config.set("component", "motd", "test motd") + self.comp.config.write(open(self.comp.config_file, "w")) + self.comp.del_motd() + self.comp.config.read(self.comp.config_file) + self.assertFalse(self.comp.config.has_option("component", "motd")) + os.unlink(config_file) + +class JCLComponent_get_welcome_message_TestCase(JCLComponent_TestCase): + def test_get_welcome_message(self): + config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.comp.config_file = config_file + self.comp.config = ConfigParser() + self.comp.config.read(self.comp.config_file) + self.comp.config.add_section("component") + self.comp.config.set("component", "welcome_message", "Welcome Message") + self.comp.config.write(open(self.comp.config_file, "w")) + motd = self.comp.get_welcome_message() + self.assertEquals(motd, "Welcome Message") + os.unlink(config_file) + + def test_get_no_welcome_message(self): + config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.comp.config_file = config_file + self.comp.config = ConfigParser() + self.comp.config.read(self.comp.config_file) + self.comp.config.write(open(self.comp.config_file, "w")) + motd = self.comp.get_welcome_message() + self.assertEquals(motd, None) + os.unlink(config_file) + +class JCLComponent_set_welcome_message_TestCase(JCLComponent_TestCase): + def test_set_new_welcome_message(self): + config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.comp.config_file = config_file + self.comp.config = ConfigParser() + self.comp.set_welcome_message("Welcome Message") + self.comp.config.read(self.comp.config_file) + self.assertTrue(self.comp.config.has_option("component", + "welcome_message")) + self.assertEquals(self.comp.config.get("component", "welcome_message"), + "Welcome Message") + os.unlink(config_file) + + def test_set_welcome_message(self): + config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.comp.config_file = config_file + self.comp.config = ConfigParser() + self.comp.config.add_section("component") + self.comp.config.set("component", "welcome_message", "Welcome Message") + self.comp.config.write(open(self.comp.config_file, "w")) + self.comp.set_welcome_message("New Welcome Message") + self.comp.config.read(self.comp.config_file) + self.assertTrue(self.comp.config.has_option("component", + "welcome_message")) + self.assertEquals(self.comp.config.get("component", "welcome_message"), + "New Welcome Message") + os.unlink(config_file) + +class JCLComponent_del_welcome_message_TestCase(JCLComponent_TestCase): + def test_del_welcome_message(self): + config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.comp.config_file = config_file + self.comp.config = ConfigParser() + self.comp.config.add_section("component") + self.comp.config.set("component", "welcome_message", "Welcome Message") + self.comp.config.write(open(self.comp.config_file, "w")) + self.comp.del_welcome_message() + self.comp.config.read(self.comp.config_file) + self.assertFalse(self.comp.config.has_option("component", + "welcome_message")) + os.unlink(config_file) + +class JCLComponent_get_admins_TestCase(JCLComponent_TestCase): + def test_get_admins(self): + config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.comp.config_file = config_file + self.comp.config = ConfigParser() + self.comp.config.read(self.comp.config_file) + self.comp.config.add_section("component") + self.comp.config.set("component", "admins", "admin1@test.com, admin2@test.com") + self.comp.config.write(open(self.comp.config_file, "w")) + admins = self.comp.get_admins() + self.assertEquals(len(admins), 2) + self.assertEquals(admins[0], "admin1@test.com") + self.assertEquals(admins[1], "admin2@test.com") + os.unlink(config_file) + + def test_get_no_admins(self): + config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.comp.config_file = config_file + self.comp.config = ConfigParser() + self.comp.config.read(self.comp.config_file) + self.comp.config.write(open(self.comp.config_file, "w")) + admins = self.comp.get_admins() + self.assertEquals(admins, []) + os.unlink(config_file) + +class JCLComponent_set_admins_TestCase(JCLComponent_TestCase): + def test_set_new_admins(self): + config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.comp.config_file = config_file + self.comp.config = ConfigParser() + self.comp.set_admins(["admin1@test.com", "admin2@test.com"]) + self.comp.config.read(self.comp.config_file) + self.assertTrue(self.comp.config.has_option("component", + "admins")) + self.assertEquals(self.comp.config.get("component", "admins"), + "admin1@test.com,admin2@test.com") + os.unlink(config_file) + + def test_set_admins(self): + config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.comp.config_file = config_file + self.comp.config = ConfigParser() + self.comp.config.add_section("component") + self.comp.config.set("component", "admins", + "admin1@test.com, admin2@test.com") + self.comp.config.write(open(self.comp.config_file, "w")) + self.comp.set_admins(["admin3@test.com", "admin4@test.com"]) + self.comp.config.read(self.comp.config_file) + self.assertTrue(self.comp.config.has_option("component", + "admins")) + self.assertEquals(self.comp.config.get("component", "admins"), + "admin3@test.com,admin4@test.com") + os.unlink(config_file) + +class JCLComponent_handle_command_TestCase(JCLComponent_TestCase): + """handle_command' tests""" + + def test_handle_command_execute_list(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.comp.config = ConfigParser() + self.comp.config_file = config_file + self.comp.config.read(config_file) + self.comp.set_admins(["admin@test.com"]) + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = ExampleAccount(user=user1, + name="account11", + jid="account11@jcl.test.com") + account11.enabled = False + account12 = Example2Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = ExampleAccount(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + info_query = Iq(stanza_type="set", + from_jid="admin@test.com", + to_jid="jcl.test.com") + command_node = info_query.set_new_content("http://jabber.org/protocol/commands", + "command") + command_node.setProp("node", "http://jabber.org/protocol/admin#get-disabled-users-num") + command_node.setProp("action", "execute") + self.comp.handle_command(info_query) + result = self.comp.stream.sent + self.assertNotEquals(result, None) + self.assertEquals(len(result), 1) + command_result = result[0].xpath_eval("c:command", + {"c": "http://jabber.org/protocol/commands"}) + self.assertEquals(len(command_result), 1) + self.assertEquals(command_result[0].prop("status"), "completed") + fields = result[0].xpath_eval("c:command/data:x/data:field", + {"c": "http://jabber.org/protocol/commands", + "data": "jabber:x:data"}) + self.assertEquals(len(fields), 2) + self.assertEquals(fields[1].prop("var"), "disabledusersnum") + self.assertEquals(fields[1].children.name, "value") + self.assertEquals(fields[1].children.content, "1") + + +class JCLComponent_run_TestCase(JCLComponent_TestCase): + """run tests""" + + def __comp_run(self): + try: + self.comp.run() + except: + # Ignore exception, might be obtain from self.comp.queue + pass + + def __comp_time_handler(self): + try: + self.saved_time_handler() + except: + # Ignore exception, might be obtain from self.comp.queue + pass + + def test_run(self): + """Test basic main loop execution""" + def end_run(): + self.comp.running = False + return + self.comp.handle_tick = end_run + self.comp.stream = MockStreamNoConnect() + self.comp.stream_class = MockStreamNoConnect + (result, time_to_wait) = self.comp.run() + self.assertEquals(time_to_wait, 0) + self.assertFalse(result) + self.assertTrue(self.comp.stream.connection_started) + threads = threading.enumerate() + self.assertEquals(len(threads), 1) + self.assertTrue(self.comp.stream.connection_stopped) + if self.comp.queue.qsize(): + raise self.comp.queue.get(0) + + def test_run_restart(self): + """Test main loop execution with restart""" + def end_stream(): + self.comp.stream.eof = True + return + self.comp.handle_tick = end_stream + self.comp.stream = MockStreamNoConnect() + self.comp.stream_class = MockStreamNoConnect + self.comp.restart = True + (result, time_to_wait) = self.comp.run() + self.assertEquals(time_to_wait, 5) + self.assertTrue(result) + self.assertTrue(self.comp.stream.connection_started) + threads = threading.enumerate() + self.assertEquals(len(threads), 1) + if self.comp.queue.qsize(): + raise self.comp.queue.get(0) + + def test_run_connection_failed(self): + """Test when connection to Jabber server fails""" + class MockStreamLoopFailed(MockStream): + def loop_iter(self, timeout): + self.socket = None + raise socket.error + # Do not loop, handle_tick is virtual + self.comp.stream = MockStreamLoopFailed() + self.comp.stream_class = MockStreamLoopFailed + self.comp.restart = False + self.comp.time_unit = 10 + (result, time_to_wait) = self.comp.run() + self.assertEquals(time_to_wait, 5) + self.assertTrue(result) + self.assertFalse(self.comp.running) + self.assertTrue(self.comp.stream.connection_started) + threads = threading.enumerate() + self.assertEquals(len(threads), 1) + self.assertFalse(self.comp.stream.connection_stopped) + if self.comp.queue.qsize(): + raise self.comp.queue.get(0) + + def test_run_startconnection_socketerror(self): + """Test when connection to Jabber server fails when starting""" + class MockStreamConnectFail(MockStream): + def connect(self): + self.socket = None + raise socket.error + # Do not loop, handle_tick is virtual + self.comp.stream = MockStreamConnectFail() + self.comp.stream_class = MockStreamConnectFail + self.comp.restart = False + (result, time_to_wait) = self.comp.run() + self.assertEquals(time_to_wait, 5) + self.assertTrue(result) + self.assertFalse(self.comp.running) + threads = threading.enumerate() + self.assertEquals(len(threads), 1) + if self.comp.queue.qsize(): + raise self.comp.queue.get(0) + + def test_run_connection_closed(self): + """Test when connection to Jabber server is closed""" + def end_stream(): + self.comp.stream.eof = True + return + self.comp.handle_tick = end_stream + self.comp.stream = MockStreamNoConnect() + self.comp.stream_class = MockStreamNoConnect + self.comp.restart = False + (result, time_to_wait) = self.comp.run() + self.assertEquals(time_to_wait, 5) + self.assertTrue(result) + self.assertFalse(self.comp.running) + self.assertTrue(self.comp.stream.connection_started) + threads = threading.enumerate() + self.assertEquals(len(threads), 1) + self.assertFalse(self.comp.stream.connection_stopped) + if self.comp.queue.qsize(): + raise self.comp.queue.get(0) + + def test_run_unhandled_error(self): + """Test main loop unhandled error from a component handler""" + def do_nothing(): + return + self.comp.stream = MockStreamRaiseException() + self.comp.stream_class = MockStreamRaiseException + self.comp.handle_tick = do_nothing + try: + self.comp.run() + except Exception, e: + threads = threading.enumerate() + self.assertEquals(len(threads), 1) + self.assertTrue(self.comp.stream.connection_stopped) + if self.comp.queue.qsize(): + raise self.comp.queue.get(0) + return + self.fail("No exception caught") + + def test_run_ni_handle_tick(self): + """Test JCLComponent 'NotImplemented' error from handle_tick method""" + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + try: + self.comp.run() + except NotImplementedError, e: + threads = threading.enumerate() + self.assertEquals(len(threads), 1) + self.assertTrue(self.comp.stream.connection_stopped) + if self.comp.queue.qsize(): + raise self.comp.queue.get(0) + return + self.fail("No exception caught") + + def test_run_go_offline(self): + """Test main loop send offline presence when exiting""" + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.max_tick_count = 1 + self.comp.handle_tick = self._handle_tick_test_time_handler + model.db_connect() + user1 = User(jid="test1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="test2@test.com"), + name="account2", + jid="account2@jcl.test.com") + model.db_disconnect() + self.comp.run() + self.assertTrue(self.comp.stream.connection_started) + threads = threading.enumerate() + self.assertEquals(len(threads), 1) + self.assertTrue(self.comp.stream.connection_stopped) + if self.comp.queue.qsize(): + raise self.comp.queue.get(0) + presence_sent = self.comp.stream.sent + self.assertEqual(len(presence_sent), 5) + self.assertEqual(len([presence + for presence in presence_sent + if presence.get_to_jid() == "test1@test.com"]), + 3) + self.assertEqual(\ + len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "jcl.test.com" + and presence.xpath_eval("@type")[0].get_content() + == "unavailable"]), + 2) + self.assertEqual(\ + len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "account11@jcl.test.com" + and presence.xpath_eval("@type")[0].get_content() \ + == "unavailable"]), + 1) + self.assertEqual(\ + len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "account12@jcl.test.com" + and presence.xpath_eval("@type")[0].get_content() \ + == "unavailable"]), + 1) + self.assertEqual(len([presence \ + for presence in presence_sent + if presence.get_to_jid() == "test2@test.com"]), + 2) + self.assertEqual(\ + len([presence + for presence in presence_sent + if presence.get_from_jid() == \ + "account2@jcl.test.com" + and presence.xpath_eval("@type")[0].get_content() \ + == "unavailable"]), + 1) + +class Handler_TestCase(JCLTestCase): + def setUp(self): + self.handler = Handler(None) + JCLTestCase.setUp(self, tables=[Account, User]) + + def test_filter(self): + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + accounts = self.handler.filter(None, None) + accounts_count = 0 + for account in accounts: + accounts_count += 1 + self.assertEquals(accounts_count, 2) + model.db_disconnect() + + def test_handle(self): + self.assertEquals(self.handler.handle(None, None, None), []) + +class AccountManager_TestCase(JCLTestCase): + def setUp(self): + JCLTestCase.setUp(self, tables=[User, Account, LegacyJID]) + self.comp = JCLComponent("jcl.test.com", + "password", + "localhost", + "5347", + None) + self.account_manager = self.comp.account_manager + + def test_get_presence_all(self): + user1 = User(jid="test1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + user2 = User(jid="test2@test.com") + account21 = Account(user=user2, + name="account21", + jid="account21@jcl.test.com") + account22 = Account(user=user2, + name="account22", + jid="account22@jcl.test.com") + result = self.account_manager.get_presence_all("unavailable") + self.assertEquals(len(result), 6) + self.assertEquals(result[0].get_from(), "jcl.test.com") + self.assertEquals(result[0].get_to(), "test1@test.com") + self.assertEquals(result[0].get_type(), "unavailable") + self.assertEquals(result[1].get_from(), "jcl.test.com") + self.assertEquals(result[1].get_to(), "test2@test.com") + self.assertEquals(result[1].get_type(), "unavailable") + self.assertEquals(result[2].get_from(), "account11@jcl.test.com") + self.assertEquals(result[2].get_to(), "test1@test.com") + self.assertEquals(result[2].get_type(), "unavailable") + self.assertEquals(result[3].get_from(), "account12@jcl.test.com") + self.assertEquals(result[3].get_to(), "test1@test.com") + self.assertEquals(result[3].get_type(), "unavailable") + self.assertEquals(result[4].get_from(), "account21@jcl.test.com") + self.assertEquals(result[4].get_to(), "test2@test.com") + self.assertEquals(result[4].get_type(), "unavailable") + self.assertEquals(result[5].get_from(), "account22@jcl.test.com") + self.assertEquals(result[5].get_to(), "test2@test.com") + self.assertEquals(result[5].get_type(), "unavailable") + + def test_populate_account_handler(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + x_data = Form("submit") + x_data.add_field(name="name", + value="account1", + field_type="text-single") + class AccountPopulateHandlerMock(Account): + def _init(self, *args, **kw): + Account._init(self, *args, **kw) + self.populate_handler_called = False + + def populate_handler(self): + self.populate_handler_called = True + + AccountPopulateHandlerMock.createTable(ifNotExists=True) + user1 = User(jid="test1@test.com") + account11 = AccountPopulateHandlerMock(user=user1, + name="account11", + jid="account11@jcl.test.com") + self.assertFalse(account11.populate_handler_called) + self.account_manager.populate_account(account11, Lang.en, x_data, + False, False) + self.assertTrue(account11.populate_handler_called) + AccountPopulateHandlerMock.dropTable(ifExists=True) + + def test_populate_account_handler_error(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + x_data = Form("submit") + x_data.add_field(name="name", + value="account1", + field_type="text-single") + class AccountPopulateHandlerErrorMock(Account): + def _init(self, *args, **kw): + Account._init(self, *args, **kw) + self.populate_handler_called = False + + def populate_handler(self): + self.populate_handler_called = True + raise Exception() + + AccountPopulateHandlerErrorMock.createTable(ifNotExists=True) + user1 = User(jid="test1@test.com") + account11 = AccountPopulateHandlerErrorMock(\ + user=user1, name="account11", jid="account11@jcl.test.com") + self.assertFalse(account11.populate_handler_called) + result = self.account_manager.populate_account(account11, Lang.en, + x_data, False, False) + self.assertEquals(len(result), 3) + self.assertEquals(result[0].get_type(), "error") + self.assertEquals(result[0].get_from(), "account11@jcl.test.com") + self.assertEquals(result[0].get_to(), "test1@test.com") + self.assertEquals(result[1].xmlnode.name, "presence") + self.assertEquals(result[1].get_from(), "account11@jcl.test.com") + self.assertEquals(result[1].get_to(), "test1@test.com") + self.assertEquals(result[1].xmlnode.children.name, "show") + self.assertEquals(result[1].xmlnode.children.content, "dnd") + self.assertEquals(result[2].get_type(), None) + self.assertEquals(result[2].get_from(), "jcl.test.com") + self.assertEquals(result[2].get_to(), "test1@test.com") + self.assertTrue(account11.populate_handler_called) + + def test_cancel_account_error(self): + """Test Account error reset""" + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + _account = Account(user=User(jid="user1@test.com"), + name="account11", + jid="account11@jcl.test.com") + _account.error = "test exception" + self.account_manager.cancel_account_error(_account) + self.assertEquals(len(self.comp.stream.sent), 1) + presence = self.comp.stream.sent[0].xmlnode + self.assertEquals(presence.name, "presence") + self.assertEquals(presence.prop("type"), None) + self.assertEquals(presence.prop("from"), _account.jid) + self.assertEquals(presence.prop("to"), _account.user.jid) + self.assertEquals(presence.children.name, "show") + self.assertEquals(presence.children.content, "online") + + def test_cancel_account_error_no_error(self): + """Test Account error reset""" + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + _account = Account(user=User(jid="user1@test.com"), + name="account11", + jid="account11@jcl.test.com") + _account.error = None + _account.status = account.ONLINE + self.account_manager.cancel_account_error(_account) + self.assertEquals(len(self.comp.stream.sent), 0) + + def test_get_account_presence_available_no_change(self): + """Test when presence status does not change""" + _account = Account(user=User(jid="user1@test.com"), + name="account11", + jid="account11@jcl.test.com") + _account.status = account.ONLINE + result = self.account_manager.get_account_presence_available(\ + _account.user.jid, _account, _account.default_lang_class, True) + self.assertEquals(len(result), 0) + +def suite(): + test_suite = unittest.TestSuite() + test_suite.addTest(unittest.makeSuite(JCLComponent_constructor_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_apply_registered_behavior_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_time_handler_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_authenticated_handler_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_signal_handler_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_handle_get_gateway_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_handle_set_gateway_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_disco_get_info_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_disco_get_items_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_handle_get_version_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_handle_get_register_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_handle_set_register_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_handle_presence_available_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_handle_presence_unavailable_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_handle_presence_subscribe_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_handle_presence_subscribed_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_handle_presence_unsubscribe_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_handle_presence_unsubscribed_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_handle_message_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_handle_tick_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_send_error_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_send_stanzas_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_get_motd_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_set_motd_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_del_motd_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_get_welcome_message_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_set_welcome_message_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_del_welcome_message_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_get_admins_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_set_admins_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_handle_command_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLComponent_run_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(Handler_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(AccountManager_TestCase, 'test')) + return test_suite + +if __name__ == '__main__': + logger.addHandler(logging.StreamHandler()) + if '-v' in sys.argv: + logger.setLevel(logging.DEBUG) + unittest.main(defaultTest='suite') --- /dev/null +++ jcl-0.1b2/src/jcl/jabber/tests/feeder.py @@ -0,0 +1,325 @@ +# -*- coding: utf-8 -*- +## +## test_feeder.py +## Login : David Rousselie +## Started on Wed Aug 9 21:34:26 2006 David Rousselie +## $Id$ +## +## Copyright (C) 2006 David Rousselie +## This program is free software; you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation; either version 2 of the License, or +## (at your option) any later version. +## +## This program is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with this program; if not, write to the Free Software +## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +## + +import unittest +import threading + +from sqlobject import * + +from jcl.jabber.component import JCLComponent +from jcl.jabber.feeder import FeederComponent, Feeder, Sender, MessageSender, \ + HeadlineSender, FeederHandler +from jcl.model.account import Account, LegacyJID, User +import jcl.model as model + +from jcl.model.tests.account import ExampleAccount, Example2Account +from jcl.jabber.tests.component import JCLComponent_TestCase, MockStream + +from jcl.tests import JCLTestCase + +class FeederMock(object): + def feed(self, _account): + return [("subject", "body")] + +class SenderMock(object): + def __init__(self): + self.sent = [] + + def send(self, _account, data): + self.sent.append((_account, data)) + +class FeederComponent_TestCase(JCLComponent_TestCase): + def setUp(self): + JCLTestCase.setUp(self, tables=[Account, LegacyJID, ExampleAccount, + Example2Account, User]) + self.comp = FeederComponent("jcl.test.com", + "password", + "localhost", + "5347", + None, + None) + self.comp.time_unit = 0 + + def test_run(self): + def end_run(): + self.comp.running = False + return + self.comp.handle_tick = end_run + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + self.comp.disable_signals() + run_thread = threading.Thread(target=self.comp.run, + name="run_thread") + run_thread.start() + self.comp.wait_event.wait(JCLComponent.timeout) + run_thread.join(JCLComponent.timeout) + self.assertTrue(self.comp.stream.connection_started) + threads = threading.enumerate() + self.assertEquals(len(threads), 1) + self.assertTrue(self.comp.stream.connection_stopped) + if self.comp.queue.qsize(): + raise self.comp.queue.get(0) + + def test_run_ni_handle_tick(self): + # handle_tick is implemented in FeederComponent + # so no need to check for NotImplemented raise assertion + self.assertTrue(True) + + def test_handle_tick(self): + class AccountFeeder(Feeder): + def feed(self, _account): + return [("Simple Message for account " + _account.name, + "user_jid: " + _account.user.jid), + ("Simple Message for account " + _account.name, + "jid: " + _account.jid)] + + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + account2 = Account(user=User(jid="user2@test.com"), + name="account2", + jid="account2@jcl.test.com") + self.comp.tick_handlers = [FeederHandler(AccountFeeder(self.comp), + MessageSender(self.comp)), + FeederHandler(AccountFeeder(self.comp), + MessageSender(self.comp))] + self.comp.handle_tick() + + messages_sent = self.comp.stream.sent + self.assertEquals(len(messages_sent), 12) + self.assertEquals(messages_sent[0].get_from(), "account11@jcl.test.com") + self.assertEquals(messages_sent[0].get_to(), "user1@test.com") + self.assertEquals(messages_sent[0].get_subject(), + "Simple Message for account account11") + self.assertEquals(messages_sent[0].get_body(), + "user_jid: user1@test.com") + self.assertEquals(messages_sent[1].get_from(), "account11@jcl.test.com") + self.assertEquals(messages_sent[1].get_to(), "user1@test.com") + self.assertEquals(messages_sent[1].get_subject(), + "Simple Message for account account11") + self.assertEquals(messages_sent[1].get_body(), + "jid: account11@jcl.test.com") + + self.assertEquals(messages_sent[2].get_from(), "account12@jcl.test.com") + self.assertEquals(messages_sent[2].get_to(), "user1@test.com") + self.assertEquals(messages_sent[2].get_subject(), + "Simple Message for account account12") + self.assertEquals(messages_sent[2].get_body(), + "user_jid: user1@test.com") + self.assertEquals(messages_sent[3].get_from(), "account12@jcl.test.com") + self.assertEquals(messages_sent[3].get_to(), "user1@test.com") + self.assertEquals(messages_sent[3].get_subject(), + "Simple Message for account account12") + self.assertEquals(messages_sent[3].get_body(), + "jid: account12@jcl.test.com") + + self.assertEquals(messages_sent[4].get_from(), "account2@jcl.test.com") + self.assertEquals(messages_sent[4].get_to(), "user2@test.com") + self.assertEquals(messages_sent[4].get_subject(), + "Simple Message for account account2") + self.assertEquals(messages_sent[4].get_body(), + "user_jid: user2@test.com") + self.assertEquals(messages_sent[5].get_from(), "account2@jcl.test.com") + self.assertEquals(messages_sent[5].get_to(), "user2@test.com") + self.assertEquals(messages_sent[5].get_subject(), + "Simple Message for account account2") + self.assertEquals(messages_sent[5].get_body(), + "jid: account2@jcl.test.com") + + self.assertEquals(messages_sent[6].get_from(), "account11@jcl.test.com") + self.assertEquals(messages_sent[6].get_to(), "user1@test.com") + self.assertEquals(messages_sent[6].get_subject(), + "Simple Message for account account11") + self.assertEquals(messages_sent[6].get_body(), + "user_jid: user1@test.com") + self.assertEquals(messages_sent[7].get_from(), "account11@jcl.test.com") + self.assertEquals(messages_sent[7].get_to(), "user1@test.com") + self.assertEquals(messages_sent[7].get_subject(), + "Simple Message for account account11") + self.assertEquals(messages_sent[7].get_body(), + "jid: account11@jcl.test.com") + + self.assertEquals(messages_sent[8].get_from(), "account12@jcl.test.com") + self.assertEquals(messages_sent[8].get_to(), "user1@test.com") + self.assertEquals(messages_sent[8].get_subject(), + "Simple Message for account account12") + self.assertEquals(messages_sent[8].get_body(), + "user_jid: user1@test.com") + self.assertEquals(messages_sent[9].get_from(), "account12@jcl.test.com") + self.assertEquals(messages_sent[9].get_to(), "user1@test.com") + self.assertEquals(messages_sent[9].get_subject(), + "Simple Message for account account12") + self.assertEquals(messages_sent[9].get_body(), + "jid: account12@jcl.test.com") + + self.assertEquals(messages_sent[10].get_from(), "account2@jcl.test.com") + self.assertEquals(messages_sent[10].get_to(), "user2@test.com") + self.assertEquals(messages_sent[10].get_subject(), + "Simple Message for account account2") + self.assertEquals(messages_sent[10].get_body(), + "user_jid: user2@test.com") + self.assertEquals(messages_sent[11].get_from(), "account2@jcl.test.com") + self.assertEquals(messages_sent[11].get_to(), "user2@test.com") + self.assertEquals(messages_sent[11].get_subject(), + "Simple Message for account account2") + self.assertEquals(messages_sent[11].get_body(), + "jid: account2@jcl.test.com") + +class Feeder_TestCase(unittest.TestCase): + def test_feed_exist(self): + feeder = Feeder() + self.assertRaises(NotImplementedError, feeder.feed, None) + +class Sender_TestCase(unittest.TestCase): + def test_send_exist(self): + sender = Sender() + self.assertRaises(NotImplementedError, sender.send, None, None, None) + +class MessageSender_TestCase(JCLTestCase): + def setUp(self): + JCLTestCase.setUp(self, tables=[Account, User]) + self.comp = FeederComponent("jcl.test.com", + "password", + "localhost", + "5347", + None, + None) + self.sender = MessageSender(self.comp) + self.message_type = None + + def test_send(self): + self.comp.stream = MockStream() + self.comp.stream_class = MockStream + model.db_connect() + account11 = Account(user=User(jid="user1@test.com"), + name="account11", + jid="account11@jcl.test.com") + self.sender.send(account11, ("subject", "Body message")) + self.assertEquals(len(self.comp.stream.sent), 1) + message = self.comp.stream.sent[0] + self.assertEquals(message.get_from(), account11.jid) + self.assertEquals(message.get_to(), account11.user.jid) + self.assertEquals(message.get_subject(), "subject") + self.assertEquals(message.get_body(), "Body message") + self.assertEquals(message.get_type(), self.message_type) + model.db_disconnect() + + def test_send_closed_connection(self): + self.comp.stream = None + model.db_connect() + account11 = Account(user=User(jid="user1@test.com"), + name="account11", + jid="account11@jcl.test.com") + self.sender.send(account11, ("subject", "Body message")) + +class HeadlineSender_TestCase(MessageSender_TestCase): + def setUp(self): + MessageSender_TestCase.setUp(self) + self.sender = HeadlineSender(self.comp) + self.message_type = "headline" + +class FeederHandler_TestCase(JCLTestCase): + def setUp(self): + JCLTestCase.setUp(self, tables=[Account, ExampleAccount, User]) + self.tick_handlers = [FeederHandler(FeederMock(), SenderMock())] + + def test_filter(self): + account12 = ExampleAccount(user=User(jid="user2@test.com"), + name="account12", + jid="account12@jcl.test.com") + account11 = ExampleAccount(user=User(jid="user1@test.com"), + name="account11", + jid="account11@jcl.test.com") + accounts = self.tick_handlers[0].filter(None, None) + i = 0 + for _account in accounts: + i += 1 + if i == 1: + self.assertEquals(_account.name, "account12") + else: + self.assertEquals(_account.name, "account11") + self.assertEquals(i, 2) + + def test_handle(self): + account11 = ExampleAccount(user=User(jid="user1@test.com"), + name="account11", + jid="account11@jcl.test.com") + account12 = ExampleAccount(user=User(jid="user2@test.com"), + name="account12", + jid="account12@jcl.test.com") + accounts = self.tick_handlers[0].handle(None, None, [account11, account12]) + sent = self.tick_handlers[0].sender.sent + self.assertEquals(len(sent), 2) + self.assertEquals(sent[0], (account11, ("subject", "body"))) + self.assertEquals(sent[1], (account12, ("subject", "body"))) + + def test_handle_disabled_account(self): + account11 = ExampleAccount(user=User(jid="user1@test.com"), + name="account11", + jid="account11@jcl.test.com") + account11.enabled = False + account12 = ExampleAccount(user=User(jid="user2@test.com"), + name="account12", + jid="account12@jcl.test.com") + accounts = self.tick_handlers[0].handle(None, None, [account11, account12]) + sent = self.tick_handlers[0].sender.sent + self.assertEquals(len(sent), 1) + self.assertEquals(sent[0], (account12, ("subject", "body"))) + + def test_handle_no_sender(self): + self.tick_handlers[0].sender = None + class FeederIncMock(object): + def __init__ (self): + self.called = 0 + def feed(self, _account): + self.called = self.called + 1 + return [self.called] + self.tick_handlers[0].feeder = FeederIncMock() + account11 = ExampleAccount(user=User(jid="user1@test.com"), + name="account11", + jid="account11@jcl.test.com") + account12 = ExampleAccount(user=User(jid="user2@test.com"), + name="account12", + jid="account12@jcl.test.com") + accounts = self.tick_handlers[0].handle(None, None, [account11, account12]) + self.assertEquals(self.tick_handlers[0].feeder.called, 2) + +def suite(): + test_suite = unittest.TestSuite() + test_suite.addTest(unittest.makeSuite(FeederComponent_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(Feeder_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(Sender_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(MessageSender_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(HeadlineSender_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(FeederHandler_TestCase, 'test')) + return test_suite + +if __name__ == '__main__': + unittest.main(defaultTest='suite') --- /dev/null +++ jcl-0.1b2/src/jcl/jabber/tests/presence.py @@ -0,0 +1,402 @@ +## +## presence.py +## Login : David Rousselie +## Started on Fri Jul 6 21:45:43 2007 David Rousselie +## $Id$ +## +## Copyright (C) 2007 David Rousselie +## This program is free software; you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation; either version 2 of the License, or +## (at your option) any later version. +## +## This program is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with this program; if not, write to the Free Software +## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +## + +import unittest +import tempfile +import os +from ConfigParser import ConfigParser +import time + +from pyxmpp.presence import Presence +from pyxmpp.message import Message +from pyxmpp.iq import Iq + +from jcl.jabber.component import JCLComponent +from jcl.jabber.presence import DefaultSubscribeHandler, \ + DefaultUnsubscribeHandler, DefaultPresenceHandler, \ + RootPresenceAvailableHandler, AccountPresenceAvailableHandler, \ + AccountPresenceUnavailableHandler, DefaultIQLastHandler +from jcl.model.account import User, LegacyJID, Account +from jcl.lang import Lang + +from jcl.tests import JCLTestCase + +class DefaultIQLastHandler_TestCase(JCLTestCase): + def setUp(self): + JCLTestCase.setUp(self, tables=[User, LegacyJID, Account]) + self.comp = JCLComponent("jcl.test.com", + "password", + "localhost", + "5347", + None) + self.handler = DefaultIQLastHandler(self.comp) + + def test_handle(self): + info_query = Iq(from_jid="user1@test.com", + to_jid="jcl.test.com", + stanza_type="get") + self.comp.last_activity = int(time.time()) + time.sleep(1) + result = self.handler.handle(info_query, None, []) + self.assertEquals(len(result), 1) + self.assertEquals(result[0].get_to(), "user1@test.com") + self.assertEquals(result[0].get_from(), "jcl.test.com") + self.assertEquals(result[0].get_type(), "result") + self.assertNotEquals(result[0].xmlnode.children, None) + self.assertEquals(result[0].xmlnode.children.name, "query") + self.assertEquals(int(result[0].xmlnode.children.prop("seconds")), 1) + +class DefaultSubscribeHandler_TestCase(unittest.TestCase): + def setUp(self): + self.handler = DefaultSubscribeHandler(None) + + def test_handle(self): + presence = Presence(from_jid="user1@test.com", + to_jid="user1%test.com@jcl.test.com", + stanza_type="subscribe") + result = self.handler.handle(presence, None, []) + self.assertEquals(len(result), 2) + self.assertEquals(result[0].get_to(), "user1@test.com") + self.assertEquals(result[0].get_from(), "user1%test.com@jcl.test.com") + self.assertEquals(result[0].get_type(), "subscribe") + self.assertEquals(result[1].get_to(), "user1@test.com") + self.assertEquals(result[1].get_from(), "user1%test.com@jcl.test.com") + self.assertEquals(result[1].get_type(), "subscribed") + +class DefaultUnsubscribeHandler_TestCase(unittest.TestCase): + def setUp(self): + self.handler = DefaultUnsubscribeHandler(None) + + def test_handle(self): + presence = Presence(from_jid="user1@test.com", + to_jid="user1%test.com@jcl.test.com", + stanza_type="unsubscribe") + result = self.handler.handle(presence, None, []) + self.assertEquals(len(result), 2) + self.assertEquals(result[0].get_to(), "user1@test.com") + self.assertEquals(result[0].get_from(), "user1%test.com@jcl.test.com") + self.assertEquals(result[0].get_type(), "unsubscribe") + self.assertEquals(result[1].get_to(), "user1@test.com") + self.assertEquals(result[1].get_from(), "user1%test.com@jcl.test.com") + self.assertEquals(result[1].get_type(), "unsubscribed") + +class DefaultPresenceHandler_TestCase(unittest.TestCase): + def setUp(self): + self.handler = DefaultPresenceHandler(None) + + def test_handle_away(self): + presence = Presence(from_jid="user1@test.com", + to_jid="user1%test.com@jcl.test.com", + stanza_type="available", + show="away") + result = self.handler.handle(presence, None, []) + self.assertEquals(len(result), 1) + self.assertEquals(result[0].get_to(), "user1@test.com") + self.assertEquals(result[0].get_from(), "user1%test.com@jcl.test.com") + self.assertEquals(result[0].get_type(), None) + self.assertEquals(result[0].get_show(), "away") + + def test_handle_offline(self): + presence = Presence(from_jid="user1@test.com", + to_jid="user1%test.com@jcl.test.com", + stanza_type="unavailable") + result = self.handler.handle(presence, None, []) + self.assertEquals(len(result), 1) + self.assertEquals(result[0].get_to(), "user1@test.com") + self.assertEquals(result[0].get_from(), "user1%test.com@jcl.test.com") + self.assertEquals(result[0].get_type(), "unavailable") + +class RootPresenceAvailableHandler_TestCase(JCLTestCase): + def setUp(self): + JCLTestCase.setUp(self, tables=[User, LegacyJID, Account]) + self.config = ConfigParser() + self.config_file = tempfile.mktemp(".conf", "jcltest", "/tmp") + self.config.read(self.config_file) + self.config.add_section("component") + self.config.set("component", "motd", "Message Of The Day") + self.comp = JCLComponent("jcl.test.com", + "password", + "localhost", + "5347", + self.config) + self.handler = RootPresenceAvailableHandler(self.comp) + + def tearDown(self): + JCLTestCase.tearDown(self) + if os.path.exists(self.config_file): + os.unlink(self.config_file) + + def test_get_root_presence(self): + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + presence = Presence(stanza_type="available", + from_jid="user1@test.com", + to_jid="jcl.test.com") + self.assertFalse(user1.has_received_motd) + result = self.handler.get_root_presence(presence, Lang.en, 2) + self.assertTrue(user1.has_received_motd) + self.assertEquals(len(result), 2) + self.assertTrue(isinstance(result[0], Presence)) + self.assertEquals(result[0].get_to(), "user1@test.com") + self.assertEquals(result[0].get_from(), "jcl.test.com") + self.assertTrue(isinstance(result[1], Message)) + self.assertEquals(result[1].get_to(), "user1@test.com") + self.assertEquals(result[1].get_from(), "jcl.test.com") + self.assertEquals(result[1].get_body(), "Message Of The Day") + + def test_get_root_presence_with_resource(self): + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + presence = Presence(stanza_type="available", + from_jid="user1@test.com/resource", + to_jid="jcl.test.com") + self.assertFalse(user1.has_received_motd) + result = self.handler.get_root_presence(presence, Lang.en, 2) + self.assertTrue(user1.has_received_motd) + self.assertEquals(len(result), 2) + self.assertTrue(isinstance(result[0], Presence)) + self.assertEquals(result[0].get_to(), "user1@test.com/resource") + self.assertEquals(result[0].get_from(), "jcl.test.com") + self.assertTrue(isinstance(result[1], Message)) + self.assertEquals(result[1].get_to(), "user1@test.com/resource") + self.assertEquals(result[1].get_from(), "jcl.test.com") + self.assertEquals(result[1].get_body(), "Message Of The Day") + + def test_get_root_presence_already_received_motd(self): + user1 = User(jid="user1@test.com") + user1.has_received_motd = True + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + presence = Presence(stanza_type="available", + from_jid="user1@test.com", + to_jid="jcl.test.com") + self.assertTrue(user1.has_received_motd) + result = self.handler.get_root_presence(presence, Lang.en, 2) + self.assertTrue(user1.has_received_motd) + self.assertEquals(len(result), 1) + self.assertTrue(isinstance(result[0], Presence)) + self.assertEquals(result[0].get_to(), "user1@test.com") + self.assertEquals(result[0].get_from(), "jcl.test.com") + + def test_get_root_presence_no_motd(self): + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + presence = Presence(stanza_type="available", + from_jid="user1@test.com", + to_jid="jcl.test.com") + self.assertFalse(user1.has_received_motd) + self.config.remove_option("component", "motd") + result = self.handler.get_root_presence(presence, Lang.en, 2) + self.assertTrue(user1.has_received_motd) + self.assertEquals(len(result), 1) + self.assertTrue(isinstance(result[0], Presence)) + self.assertEquals(result[0].get_to(), "user1@test.com") + self.assertEquals(result[0].get_from(), "jcl.test.com") + self.assertEquals(result[0].get_show(), "online") + self.assertEquals(result[0].get_status(), "2" + Lang.en.message_status) + +class AccountPresenceAvailableHandler_TestCase(JCLTestCase): + def setUp(self): + JCLTestCase.setUp(self, tables=[User, LegacyJID, Account]) + self.config = ConfigParser() + self.config_file = tempfile.mktemp(".conf", "jcltest", "/tmp") + self.config.read(self.config_file) + self.config.add_section("component") + self.config.set("component", "motd", "Message Of The Day") + self.comp = JCLComponent("jcl.test.com", + "password", + "localhost", + "5347", + self.config) + self.handler = AccountPresenceAvailableHandler(self.comp) + + def tearDown(self): + JCLTestCase.tearDown(self) + if os.path.exists(self.config_file): + os.unlink(self.config_file) + + def test_get_account_presence(self): + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + presence = Presence(stanza_type="available", + from_jid="user1@test.com", + to_jid="account11@jcl.test.com") + result = self.handler.get_account_presence(presence, Lang.en, account11) + self.assertEquals(len(result), 1) + self.assertTrue(isinstance(result[0], Presence)) + self.assertEquals(result[0].get_to(), "user1@test.com") + self.assertEquals(result[0].get_from(), "account11@jcl.test.com") + self.assertEquals(result[0].get_show(), "online") + self.assertEquals(result[0].get_status(), "account11") + + def test_get_account_presence_with_resource(self): + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + presence = Presence(stanza_type="available", + from_jid="user1@test.com/resource", + to_jid="account11@jcl.test.com") + result = self.handler.get_account_presence(presence, Lang.en, account11) + self.assertEquals(len(result), 1) + self.assertTrue(isinstance(result[0], Presence)) + self.assertEquals(result[0].get_to(), "user1@test.com/resource") + self.assertEquals(result[0].get_from(), "account11@jcl.test.com") + self.assertEquals(result[0].get_show(), "online") + self.assertEquals(result[0].get_status(), "account11") + + def test_get_disabled_account_presence(self): + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account11.enabled = False + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + presence = Presence(stanza_type="available", + from_jid="user1@test.com", + to_jid="account11@jcl.test.com") + result = self.handler.get_account_presence(presence, Lang.en, account11) + self.assertEquals(len(result), 1) + self.assertTrue(isinstance(result[0], Presence)) + self.assertEquals(result[0].get_to(), "user1@test.com") + self.assertEquals(result[0].get_from(), "account11@jcl.test.com") + self.assertEquals(result[0].get_show(), "xa") + self.assertEquals(result[0].get_status(), Lang.en.account_disabled) + + def test_get_inerror_account_presence(self): + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account11.error = "Error" + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + presence = Presence(stanza_type="available", + from_jid="user1@test.com", + to_jid="account11@jcl.test.com") + result = self.handler.get_account_presence(presence, Lang.en, account11) + self.assertEquals(len(result), 1) + self.assertTrue(isinstance(result[0], Presence)) + self.assertEquals(result[0].get_to(), "user1@test.com") + self.assertEquals(result[0].get_from(), "account11@jcl.test.com") + self.assertEquals(result[0].get_show(), "dnd") + self.assertEquals(result[0].get_status(), Lang.en.account_error) + +class AccountPresenceUnavailableHandler_TestCase(JCLTestCase): + def setUp(self): + JCLTestCase.setUp(self, tables=[User, LegacyJID, Account]) + self.config = ConfigParser() + self.config_file = tempfile.mktemp(".conf", "jcltest", "/tmp") + self.config.read(self.config_file) + self.config.add_section("component") + self.config.set("component", "motd", "Message Of The Day") + self.comp = JCLComponent("jcl.test.com", + "password", + "localhost", + "5347", + self.config) + self.handler = AccountPresenceUnavailableHandler(self.comp) + + def tearDown(self): + JCLTestCase.tearDown(self) + if os.path.exists(self.config_file): + os.unlink(self.config_file) + + def test_get_account_presence(self): + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + presence = Presence(stanza_type="unavailable", + from_jid="user1@test.com", + to_jid="account11@jcl.test.com") + result = self.handler.get_account_presence(presence, Lang.en, account11) + self.assertEquals(len(result), 1) + self.assertTrue(isinstance(result[0], Presence)) + self.assertEquals(result[0].get_to(), "user1@test.com") + self.assertEquals(result[0].get_from(), "account11@jcl.test.com") + self.assertEquals(result[0].get_type(), "unavailable") + + def test_get_account_presence_with_resource(self): + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + presence = Presence(stanza_type="unavailable", + from_jid="user1@test.com/resource", + to_jid="account11@jcl.test.com") + result = self.handler.get_account_presence(presence, Lang.en, account11) + self.assertEquals(len(result), 1) + self.assertTrue(isinstance(result[0], Presence)) + self.assertEquals(result[0].get_to(), "user1@test.com/resource") + self.assertEquals(result[0].get_from(), "account11@jcl.test.com") + self.assertEquals(result[0].get_type(), "unavailable") + +def suite(): + test_suite = unittest.TestSuite() + test_suite.addTest(unittest.makeSuite(DefaultIQLastHandler_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(DefaultSubscribeHandler_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(DefaultUnsubscribeHandler_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(DefaultPresenceHandler_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(RootPresenceAvailableHandler_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(AccountPresenceAvailableHandler_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(AccountPresenceUnavailableHandler_TestCase, 'test')) + return test_suite + +if __name__ == '__main__': + unittest.main(defaultTest='suite') --- /dev/null +++ jcl-0.1b2/src/jcl/jabber/tests/__init__.py @@ -0,0 +1,46 @@ +"""JCL test module""" +__revision__ = "" + +import unittest + +import jcl.jabber as jabber + +from jcl.jabber.tests import component, feeder, command, message, presence, \ + disco, vcard, register + +class HandlerType1: + pass + +class HandlerType2: + pass + +class HandlerType3: + pass + +class JabberModule_TestCase(unittest.TestCase): + def test_replace_handlers(self): + handlers = [[HandlerType1(), HandlerType2(), HandlerType1()], + [HandlerType2(), HandlerType1(), HandlerType2()]] + jabber.replace_handlers(handlers, HandlerType2, HandlerType3()) + self.assertEquals(handlers[0][0].__class__.__name__, "HandlerType1") + self.assertEquals(handlers[0][1].__class__.__name__, "HandlerType3") + self.assertEquals(handlers[0][2].__class__.__name__, "HandlerType1") + self.assertEquals(handlers[1][0].__class__.__name__, "HandlerType3") + self.assertEquals(handlers[1][1].__class__.__name__, "HandlerType1") + self.assertEquals(handlers[1][2].__class__.__name__, "HandlerType3") + +def suite(): + test_suite = unittest.TestSuite() + test_suite.addTest(unittest.makeSuite(JabberModule_TestCase, 'test')) + test_suite.addTest(component.suite()) + test_suite.addTest(feeder.suite()) + test_suite.addTest(command.suite()) + test_suite.addTest(message.suite()) + test_suite.addTest(presence.suite()) + test_suite.addTest(disco.suite()) + test_suite.addTest(vcard.suite()) + test_suite.addTest(register.suite()) + return test_suite + +if __name__ == '__main__': + unittest.main(defaultTest='suite') --- /dev/null +++ jcl-0.1b2/src/jcl/jabber/tests/vcard.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +## +## vcard.py +## Login : David Rousselie +## Started on Fri Jul 6 21:40:55 2007 David Rousselie +## $Id$ +## +## Copyright (C) 2007 David Rousselie +## This program is free software; you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation; either version 2 of the License, or +## (at your option) any later version. +## +## This program is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with this program; if not, write to the Free Software +## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +## + +import unittest +import logging +import sys +from ConfigParser import ConfigParser + +from pyxmpp.iq import Iq + +import jcl.tests +from jcl.lang import Lang +from jcl.jabber.component import JCLComponent +from jcl.model.account import Account, User +from jcl.jabber.vcard import DefaultVCardHandler + +from jcl.model.tests.account import ExampleAccount +from jcl.tests import JCLTestCase + +class DefaultVCardHandler_TestCase(JCLTestCase): + def setUp(self): + JCLTestCase.setUp(self, tables=[User, Account, ExampleAccount]) + self.comp = JCLComponent("jcl.test.com", + "password", + "localhost", + "5347", + self.db_url) + self.handler = DefaultVCardHandler(self.comp) + self.comp.config = ConfigParser() + self.comp.config.read("src/jcl/tests/jcl.conf") + + def test_filter(self): + """Test DefaultVCardHandler filter. Accept any stanza""" + self.assertEquals(self.handler.filter(None, None), True) + + def test_handle(self): + """Test default VCard returned""" + result = self.handler.handle(Iq(from_jid="jcl.test.com", + to_jid="user@test.com", + stanza_type="get"), + Lang.en, True) + self.assertEquals(len(result), 1) + result[0].xmlnode.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + self.comp.config.get("vcard", "url") + "" + + "" + self.comp.name + "" + + "" + + "" + + "" + + "" + + "" + self.comp.name + "" + + "", + result[0].xmlnode, True)) + +def suite(): + test_suite = unittest.TestSuite() + test_suite.addTest(unittest.makeSuite(DefaultVCardHandler_TestCase, 'test')) + return test_suite + +if __name__ == '__main__': + logger = logging.getLogger() + logger.addHandler(logging.StreamHandler()) + if '-v' in sys.argv: + logger.setLevel(logging.INFO) + unittest.main(defaultTest='suite') --- /dev/null +++ jcl-0.1b2/src/jcl/jabber/tests/message.py @@ -0,0 +1,233 @@ +# -*- coding: utf-8 -*- +## +## message.py +## Login : David Rousselie +## Started on Fri Jul 6 21:40:55 2007 David Rousselie +## $Id$ +## +## Copyright (C) 2007 David Rousselie +## This program is free software; you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation; either version 2 of the License, or +## (at your option) any later version. +## +## This program is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with this program; if not, write to the Free Software +## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +## + +import unittest + +from pyxmpp.message import Message + +from jcl.lang import Lang +from jcl.jabber.component import JCLComponent +from jcl.jabber.message import PasswordMessageHandler, HelpMessageHandler +import jcl.model.account as account +import jcl.model as model +from jcl.model.account import Account, User + +from jcl.model.tests.account import ExampleAccount +from jcl.tests import JCLTestCase + +class PasswordMessageHandler_TestCase(JCLTestCase): + def setUp(self): + JCLTestCase.setUp(self, tables=[User, Account, ExampleAccount]) + self.comp = JCLComponent("jcl.test.com", + "password", + "localhost", + "5347", + self.db_url) + self.handler = PasswordMessageHandler(self.comp) + + def test_filter_waiting_password(self): + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = ExampleAccount(user=user1, + name="account11", + jid="account11@jcl.test.com") + account11.waiting_password_reply = True + account12 = ExampleAccount(user=user1, + name="account12", + jid="account12@jcl.test.com") + message = Message(from_jid="user1@test.com/resource", + to_jid="account11@jcl.test.com", + subject="[PASSWORD]", + body="secret") + _account = self.handler.filter(message, None) + self.assertEquals(_account.name, "account11") + model.db_disconnect() + + def test_filter_not_waiting_password(self): + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = ExampleAccount(user=user1, + name="account11", + jid="account11@jcl.test.com") + account11.waiting_password_reply = False + account12 = ExampleAccount(user=user1, + name="account12", + jid="account12@jcl.test.com") + message = Message(from_jid="user1@test.com/resource", + to_jid="account11@jcl.test.com", + subject="[PASSWORD]", + body="secret") + _account = self.handler.filter(message, None) + self.assertEquals(_account, None) + model.db_disconnect() + + def test_filter_not_good_message(self): + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = ExampleAccount(user=user1, + name="account11", + jid="account11@jcl.test.com") + account11.waiting_password_reply = True + account12 = ExampleAccount(user=user1, + name="account12", + jid="account12@jcl.test.com") + message = Message(from_jid="user1@test.com", + to_jid="account11@jcl.test.com", + subject="[WRONG MESSAGE]", + body="secret") + _account = self.handler.filter(message, None) + self.assertEquals(_account, None) + model.db_disconnect() + + def test_filter_not_password_account(self): + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = Account(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = Account(user=user1, + name="account12", + jid="account12@jcl.test.com") + message = Message(from_jid="user1@test.com", + to_jid="account11@jcl.test.com", + subject="[PASSWORD]", + body="secret") + _account = self.handler.filter(message, None) + self.assertEquals(_account, None) + model.db_disconnect() + + def test_handle(self): + model.db_connect() + user1 = User(jid="user1@test.com") + account11 = ExampleAccount(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = ExampleAccount(user=user1, + name="account12", + jid="account12@jcl.test.com") + message = Message(from_jid="user1@test.com/resource", + to_jid="account11@jcl.test.com", + subject="[PASSWORD]", + body="secret") + messages = self.handler.handle(message, Lang.en, account11) + self.assertEquals(len(messages), 1) + self.assertEquals(account11.password, "secret") + model.db_disconnect() + +class HelpMessageHandler_TestCase(JCLTestCase): + def setUp(self): + JCLTestCase.setUp(self, tables=[User, Account, ExampleAccount]) + self.comp = JCLComponent("jcl.test.com", + "password", + "localhost", + "5347", + self.db_url) + self.handler = HelpMessageHandler(self.comp) + + def test_filter(self): + user1 = User(jid="user1@test.com") + account11 = ExampleAccount(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = ExampleAccount(user=user1, + name="account12", + jid="account12@jcl.test.com") + message = Message(from_jid="user1@test.com/resource", + to_jid="account11@jcl.test.com", + subject="", + body="help") + result = self.handler.filter(message, None) + self.assertNotEquals(None, result) + + def test_filter_long_help_message(self): + user1 = User(jid="user1@test.com") + account11 = ExampleAccount(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = ExampleAccount(user=user1, + name="account12", + jid="account12@jcl.test.com") + message = Message(from_jid="user1@test.com/resource", + to_jid="account11@jcl.test.com", + subject="", + body="help dalkjdjhbd") + result = self.handler.filter(message, None) + self.assertNotEquals(None, result) + + def test_filter_in_subject(self): + user1 = User(jid="user1@test.com") + account11 = ExampleAccount(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = ExampleAccount(user=user1, + name="account12", + jid="account12@jcl.test.com") + message = Message(from_jid="user1@test.com", + to_jid="account11@jcl.test.com", + subject="help dalkjdjhbd", + body="") + result = self.handler.filter(message, None) + self.assertNotEquals(None, result) + + def test_filter_wrong_message(self): + user1 = User(jid="user1@test.com") + account11 = ExampleAccount(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = ExampleAccount(user=user1, + name="account12", + jid="account12@jcl.test.com") + message = Message(from_jid="user1@test.com", + to_jid="account11@jcl.test.com", + subject="", + body="hepl") + result = self.handler.filter(message, None) + self.assertEquals(None, result) + + def test_handle(self): + user1 = User(jid="user1@test.com") + account11 = ExampleAccount(user=user1, + name="account11", + jid="account11@jcl.test.com") + account12 = ExampleAccount(user=user1, + name="account12", + jid="account12@jcl.test.com") + message = Message(from_jid="user1@test.com/resource", + to_jid="account11@jcl.test.com", + subject="", + body="help") + messages = self.handler.handle(message, Lang.en, account11) + self.assertEquals(len(messages), 1) + self.assertEquals(messages[0].get_from(), "account11@jcl.test.com") + self.assertEquals(messages[0].get_to(), "user1@test.com/resource") + self.assertEquals(messages[0].get_subject(), Lang.en.help_message_subject) + self.assertEquals(messages[0].get_body(), Lang.en.help_message_body) + +def suite(): + test_suite = unittest.TestSuite() + test_suite.addTest(unittest.makeSuite(PasswordMessageHandler_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(HelpMessageHandler_TestCase, 'test')) + return test_suite + +if __name__ == '__main__': + unittest.main(defaultTest='suite') --- /dev/null +++ jcl-0.1b2/src/jcl/jabber/tests/command.py @@ -0,0 +1,3339 @@ +## +## command.py +## Login : David Rousselie +## Started on Wed Jun 27 08:23:04 2007 David Rousselie +## $Id$ +## +## Copyright (C) 2007 David Rousselie +## This program is free software; you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation; either version 2 of the License, or +## (at your option) any later version. +## +## This program is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with this program; if not, write to the Free Software +## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +## + +import unittest +import os +import tempfile +from ConfigParser import ConfigParser +import threading +import sys +import logging + +from pyxmpp.jid import JID +from pyxmpp.jabber.dataforms import Form +from pyxmpp.iq import Iq +from pyxmpp.jabber.disco import DiscoItems +from pyxmpp.jabber.dataforms import Field +import pyxmpp.xmlextra + +import jcl.tests +from jcl.lang import Lang +from jcl.jabber.component import JCLComponent +import jcl.jabber.command as command +from jcl.jabber.command import FieldNoType, CommandManager, JCLCommandManager, \ + CommandError +import jcl.model.account as account +from jcl.model.account import Account, PresenceAccount, LegacyJID, User +from jcl.model.tests.account import ExampleAccount, Example2Account +from jcl.tests import JCLTestCase + +PYXMPP_NS = pyxmpp.xmlextra.COMMON_NS + +class FieldNoType_TestCase(unittest.TestCase): + def test_complete_xml_element(self): + fake_iq = Iq(stanza_type="get", + from_jid="user1@test.com") + field = FieldNoType(name="name", + label="Account name") + field.complete_xml_element(fake_iq.xmlnode, None) + self.assertFalse(fake_iq.xmlnode.hasProp("type")) + +class MockComponent(JCLComponent): + jid = JID("jcl.test.com") + lang = Lang() + + def __init__(self): + pass + + def get_admins(self): + return ["admin@test.com"] + +class MockCommandManager(CommandManager): + """ """ + def __init__ (self): + """ """ + CommandManager.__init__(self) + self.commands["command1"] = (False, + command.root_node_re) + self.component = MockComponent() + self.command1_step_1_called = False + + def execute_command1_1(self, info_query, session_context, + command_node, lang_class): + """ """ + self.command1_step_1_called = True + return (None, []) + +def prepare_submit(node, session_id, from_jid, to_jid="jcl.test.com", + fields=[], action="next"): + """ + Prepare IQ form to be submitted + """ + info_query = Iq(stanza_type="set", + from_jid=from_jid, + to_jid=to_jid) + command_node = info_query.set_new_content(command.COMMAND_NS, + "command") + command_node.setProp("node", node) + command_node.setProp("sessionid", session_id) + command_node.setProp("action", action) + submit_form = Form(xmlnode_or_type="submit") + submit_form.fields.extend(fields) + submit_form.as_xml(command_node) + return info_query + +class CommandManager_TestCase(unittest.TestCase): + def setUp(self): + self.command_manager = CommandManager() + self.command_manager.commands = {} + + def test_get_short_command_name_form_long_name(self): + command_name = self.command_manager.get_short_command_name("http://jabber.org/protocol/admin#test-command") + self.assertEquals(command_name, "test_command") + + def test_get_short_command_name(self): + command_name = self.command_manager.get_short_command_name("test-command") + self.assertEquals(command_name, "test_command") + + def test_list_root_commands(self): + self.command_manager.commands["command1"] = (True, + command.root_node_re) + self.command_manager.commands["command2"] = (False, + command.root_node_re) + self.command_manager.commands["command11"] = (\ + True, command.account_type_node_re) + self.command_manager.commands["command12"] = (\ + False, command.account_type_node_re) + self.command_manager.commands["command21"] = (\ + True, command.account_node_re) + self.command_manager.commands["command22"] = (\ + False, command.account_node_re) + self.command_manager.component = MockComponent() + disco_items = self.command_manager.list_commands(\ + jid=JID("user@test.com"), + to_jid=JID("jcl.test.com"), + disco_items=DiscoItems(), + lang_class=Lang.en) + self.assertEquals(disco_items.get_node(), None) + items = disco_items.get_items() + self.assertEquals(len(items), 1) + self.assertEquals(items[0].get_node(), "command2") + self.assertEquals(items[0].get_name(), "command2") + self.assertEquals(items[0].get_jid(), "jcl.test.com") + + def test_list_accounttype_commands(self): + self.command_manager.commands["command1"] = (True, + command.root_node_re) + self.command_manager.commands["command2"] = (False, + command.root_node_re) + self.command_manager.commands["command11"] = (\ + True, command.account_type_node_re) + self.command_manager.commands["command12"] = (\ + False, command.account_type_node_re) + self.command_manager.commands["command21"] = (\ + True, command.account_node_re) + self.command_manager.commands["command22"] = (\ + False, command.account_node_re) + self.command_manager.component = MockComponent() + disco_items = self.command_manager.list_commands(\ + jid=JID("user@test.com"), + to_jid=JID("jcl.test.com/Example"), + disco_items=DiscoItems("Example"), + lang_class=Lang.en) + self.assertEquals(disco_items.get_node(), "Example") + items = disco_items.get_items() + self.assertEquals(len(items), 1) + self.assertEquals(items[0].get_node(), "command12") + self.assertEquals(items[0].get_name(), "command12") + self.assertEquals(items[0].get_jid(), "jcl.test.com/Example") + + def test_list_account_commands(self): + self.command_manager.commands["command1"] = (True, + command.root_node_re) + self.command_manager.commands["command2"] = (False, + command.root_node_re) + self.command_manager.commands["command11"] = (\ + True, command.account_type_node_re) + self.command_manager.commands["command12"] = (\ + False, command.account_type_node_re) + self.command_manager.commands["command21"] = (\ + True, command.account_node_re) + self.command_manager.commands["command22"] = (\ + False, command.account_node_re) + self.command_manager.component = MockComponent() + disco_items = self.command_manager.list_commands(\ + jid=JID("user@test.com"), + to_jid=JID("account@jcl.test.com/Example"), + disco_items=DiscoItems("Example/account1"), + lang_class=Lang.en) + self.assertEquals(disco_items.get_node(), "Example/account1") + items = disco_items.get_items() + self.assertEquals(len(items), 1) + self.assertEquals(items[0].get_node(), "command22") + self.assertEquals(items[0].get_name(), "command22") + self.assertEquals(items[0].get_jid(), "account@jcl.test.com/Example") + + def test_list_commands_as_admin(self): + self.command_manager.commands["command1"] = (True, + command.root_node_re) + self.command_manager.commands["command2"] = (False, + command.root_node_re) + self.command_manager.component = MockComponent() + disco_items = self.command_manager.list_commands(\ + jid=JID("admin@test.com"), + to_jid=JID("jcl.test.com"), + disco_items=DiscoItems(), + lang_class=Lang.en) + self.assertEquals(disco_items.get_node(), None) + items = disco_items.get_items() + self.assertEquals(len(items), 2) + self.assertEquals(items[0].get_node(), "command1") + self.assertEquals(items[0].get_name(), "command1") + self.assertEquals(items[0].get_jid(), "jcl.test.com") + self.assertEquals(items[1].get_node(), "command2") + self.assertEquals(items[1].get_name(), "command2") + self.assertEquals(items[1].get_jid(), "jcl.test.com") + + def test_list_commands_as_admin_fulljid(self): + self.command_manager.commands["command1"] = (True, + command.root_node_re) + self.command_manager.commands["command2"] = (False, + command.root_node_re) + self.command_manager.component = MockComponent() + disco_items = self.command_manager.list_commands(\ + jid=JID("admin@test.com/full"), + to_jid=JID("jcl.test.com"), + disco_items=DiscoItems(), + lang_class=Lang.en) + self.assertEquals(disco_items.get_node(), None) + items = disco_items.get_items() + self.assertEquals(len(items), 2) + self.assertEquals(items[0].get_node(), "command1") + self.assertEquals(items[0].get_name(), "command1") + self.assertEquals(items[0].get_jid(), "jcl.test.com") + self.assertEquals(items[1].get_node(), "command2") + self.assertEquals(items[1].get_name(), "command2") + self.assertEquals(items[1].get_jid(), "jcl.test.com") + + def test_apply_admin_command_action_as_admin(self): + self.command_manager.commands["command1"] = (True, + command.root_node_re) + self.command_manager.apply_execute_command = \ + lambda iq, command_name: [] + self.command_manager.component = MockComponent() + info_query = Iq(stanza_type="set", + from_jid="admin@test.com", + to_jid="jcl.test.com") + result = self.command_manager.apply_command_action(info_query, + "command1", + "execute") + self.assertEquals(result, []) + + def test_apply_admin_command_action_as_admin_fulljid(self): + self.command_manager.commands["command1"] = (True, + command.root_node_re) + self.command_manager.apply_execute_command = \ + lambda iq, command_name: [] + self.command_manager.component = MockComponent() + info_query = Iq(stanza_type="set", + from_jid="admin@test.com/full", + to_jid="jcl.test.com") + result = self.command_manager.apply_command_action(info_query, + "command1", + "execute") + self.assertEquals(result, []) + + def test_apply_admin_command_action_as_user(self): + self.command_manager.commands["command1"] = (True, + command.root_node_re) + self.command_manager.apply_execute_command = \ + lambda iq, command_name: [] + self.command_manager.component = MockComponent() + info_query = Iq(stanza_type="set", + from_jid="user@test.com", + to_jid="jcl.test.com") + result = self.command_manager.apply_command_action(info_query, + "command1", + "execute") + self.assertEquals(len(result), 1) + self.assertEquals(result[0].get_type(), "error") + self.assertEquals(result[0].xmlnode.children.name, "error") + self.assertEquals(result[0].xmlnode.children.prop("type"), + "auth") + self.assertEquals(result[0].xmlnode.children.children.name, + "forbidden") + + def test_apply_non_admin_command_action_as_admin(self): + self.command_manager.commands["command1"] = (False, + command.root_node_re) + self.command_manager.apply_execute_command = \ + lambda iq, command_name: [] + self.command_manager.component = MockComponent() + info_query = Iq(stanza_type="set", + from_jid="admin@test.com", + to_jid="jcl.test.com") + result = self.command_manager.apply_command_action(info_query, + "command1", + "execute") + self.assertEquals(result, []) + + def test_apply_non_admin_command_action_as_user(self): + self.command_manager.commands["command1"] = (False, + command.root_node_re) + self.command_manager.apply_execute_command = \ + lambda iq, command_name: [] + self.command_manager.component = MockComponent() + info_query = Iq(stanza_type="set", + from_jid="user@test.com", + to_jid="jcl.test.com") + result = self.command_manager.apply_command_action(info_query, + "command1", + "execute") + self.assertEquals(result, []) + + def test_apply_command_action_to_wrong_jid(self): + self.command_manager.commands["command1"] = (False, + command.account_node_re) + self.command_manager.apply_execute_command = \ + lambda iq, command_name: [] + self.command_manager.component = MockComponent() + info_query = Iq(stanza_type="set", + from_jid="user@test.com", + to_jid="jcl.test.com") + result = self.command_manager.apply_command_action(info_query, + "command1", + "execute") + self.assertEquals(len(result), 1) + self.assertEquals(result[0].get_type(), "error") + self.assertEquals(result[0].xmlnode.children.name, "error") + self.assertEquals(result[0].xmlnode.children.prop("type"), + "auth") + self.assertEquals(result[0].xmlnode.children.children.name, + "forbidden") + + def test_apply_command_non_existing_action(self): + self.command_manager.commands["command1"] = (False, + command.root_node_re) + self.command_manager.component = MockComponent() + info_query = Iq(stanza_type="set", + from_jid="user@test.com", + to_jid="jcl.test.com") + result = self.command_manager.apply_command_action(info_query, + "command1", + "noexecute") + self.assertEquals(len(result), 1) + self.assertEquals(result[0].get_type(), "error") + self.assertEquals(result[0].xmlnode.children.name, "error") + self.assertEquals(result[0].xmlnode.children.prop("type"), + "cancel") + self.assertEquals(result[0].xmlnode.children.children.name, + "feature-not-implemented") + + def test_apply_command_unknown_command(self): + self.command_manager.component = MockComponent() + info_query = Iq(stanza_type="set", + from_jid="user@test.com", + to_jid="jcl.test.com") + result = self.command_manager.apply_command_action(info_query, + "command1", + "noexecute") + self.assertEquals(len(result), 1) + self.assertEquals(result[0].get_type(), "error") + self.assertEquals(result[0].xmlnode.children.name, "error") + self.assertEquals(result[0].xmlnode.children.prop("type"), + "cancel") + self.assertEquals(result[0].xmlnode.children.children.name, + "feature-not-implemented") + + def test_multi_step_command_unknown_step(self): + self.command_manager = MockCommandManager() + self.command_manager.sessions["session_id"] = (1, {}) + info_query = Iq(stanza_type="set", + from_jid="user@test.com", + to_jid="jcl.test.com") + command_node = info_query.set_new_content(command.COMMAND_NS, + "command") + command_node.setProp("sessionid", "session_id") + command_node.setProp("node", "command1") + result = self.command_manager.execute_multi_step_command(\ + info_query, "command1", lambda session_id: (2, {})) + self.assertEquals(result[0].get_type(), "error") + child = result[0].xmlnode.children + self.assertEquals(child.name, "command") + self.assertEquals(child.prop("node"), "command1") + child = result[0].xmlnode.children.next + self.assertEquals(child.name, "error") + self.assertEquals(child.prop("type"), "cancel") + self.assertEquals(child.children.name, + "feature-not-implemented") + + def test_multi_step_command_first_step(self): + self.command_manager = MockCommandManager() + info_query = Iq(stanza_type="set", + from_jid="user@test.com", + to_jid="jcl.test.com") + command_node = info_query.set_new_content(command.COMMAND_NS, + "command") + command_node.setProp("node", "command1") + self.command_manager.execute_multi_step_command(\ + info_query, "command1", None) + self.assertTrue(self.command_manager.command1_step_1_called) + + def test_multi_step_command_multi_step_method(self): + """ + Test if the multi steps method is called if no specific method + is implemented + """ + self.command_manager = MockCommandManager() + self.command_manager.sessions["session_id"] = (1, {}) + self.multi_step_command1_called = False + def execute_command1(info_query, session_context, + command_node, lang_class): + """ """ + self.multi_step_command1_called = True + return (None, []) + + self.command_manager.__dict__["execute_command1"] = execute_command1 + info_query = Iq(stanza_type="set", + from_jid="user@test.com", + to_jid="jcl.test.com") + command_node = info_query.set_new_content(command.COMMAND_NS, + "command") + command_node.setProp("sessionid", "session_id") + command_node.setProp("node", "command1") + self.command_manager.execute_multi_step_command(\ + info_query, "command1", lambda session_id: (2, {})) + self.assertTrue(self.multi_step_command1_called) + + def test_multi_step_command_error_in_command(self): + """ + Test if the multi steps method catch the CommandError exception + and translate it into an IQ error + """ + self.command_manager = MockCommandManager() + def execute_command1(info_query, session_context, + command_node, lang_class): + raise CommandError("feature-not-implemented") + + self.command_manager.__dict__["execute_command1_1"] = execute_command1 + info_query = Iq(stanza_type="set", + from_jid="user@test.com", + to_jid="jcl.test.com") + command_node = info_query.set_new_content(command.COMMAND_NS, + "command") + command_node.setProp("node", "command1") + result = self.command_manager.execute_multi_step_command(\ + info_query, "command1", None) + result_iq = result[0].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "", + result_iq, True)) + + def test_multi_step_command_unknown_error_in_command(self): + """ + Test if the multi steps method catch the CommandError exception + and translate it into an IQ error + """ + self.command_manager = MockCommandManager() + def execute_command1(info_query, session_context, + command_node, lang_class): + raise Exception("error") + + self.command_manager.__dict__["execute_command1_1"] = execute_command1 + info_query = Iq(stanza_type="set", + from_jid="user@test.com", + to_jid="jcl.test.com") + command_node = info_query.set_new_content(command.COMMAND_NS, + "command") + command_node.setProp("node", "command1") + result = self.command_manager.execute_multi_step_command(\ + info_query, "command1", None) + result_iq = result[0].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "", + result_iq, True)) + + def test_parse_form(self): + """ + Check if parse_form method correctly set the session variables + from given Form. + """ + session_id = "session_id" + self.command_manager.sessions[session_id] = (1, {}) + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#add-user", + session_id=session_id, + from_jid="test1@test.com", + fields=[Field(field_type="list-multi", + name="test", + values=["1", "2"])]) + self.command_manager.parse_form(info_query, session_id) + self.assertEquals(\ + self.command_manager.sessions[session_id][1]["test"], + ["1", "2"]) + + def test_parse_form_multiple_calls(self): + """ + Check if parse_form method correctly set the session variables + from given Form. It should append data to an existing session + variable. + """ + session_id = "session_id" + self.command_manager.sessions[session_id] = (1, {"test": ["1", "2"]}) + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#add-user", + session_id=session_id, + from_jid="test1@test.com", + fields=[Field(field_type="list-multi", + name="test", + values=["3", "4"])]) + self.command_manager.parse_form(info_query, session_id) + self.assertEquals(\ + self.command_manager.sessions[session_id][1]["test"], + ["1", "2", "3", "4"]) + +class JCLCommandManagerTestCase(JCLTestCase): + def setUp(self, tables=[]): + tables += [Account, PresenceAccount, ExampleAccount, + Example2Account, LegacyJID, + User] + JCLTestCase.setUp(self, tables=tables) + self.config_file = tempfile.mktemp(".conf", "jcltest", jcl.tests.DB_DIR) + self.config = ConfigParser() + self.config.read(self.config_file) + self.comp = JCLComponent("jcl.test.com", + "password", + "localhost", + "5347", + self.config, + self.config_file) + self.comp.time_unit = 0 + self.comp.set_admins(["admin@test.com"]) + self.command_manager = JCLCommandManager(self.comp, + self.comp.account_manager) + self.comp.account_manager.account_classes = (ExampleAccount, + Example2Account) + self.user1 = User(jid="test1@test.com") + self.account11 = ExampleAccount(user=self.user1, + name="account11", + jid="account11@jcl.test.com") + self.account12 = Example2Account(user=self.user1, + name="account12", + jid="account12@jcl.test.com") + self.user2 = User(jid="test2@test.com") + self.account21 = ExampleAccount(user=self.user2, + name="account21", + jid="account21@jcl.test.com") + self.account22 = ExampleAccount(user=self.user2, + name="account11", + jid="account11@jcl.test.com") + self.user3 = User(jid="test3@test.com") + self.account31 = ExampleAccount(user=self.user3, + name="account31", + jid="account31@jcl.test.com") + self.account32 = Example2Account(user=self.user3, + name="account32", + jid="account32@jcl.test.com") + self.info_query = Iq(stanza_type="set", + from_jid="admin@test.com", + to_jid=self.comp.jid) + self.command_node = self.info_query.set_new_content(command.COMMAND_NS, + "command") + + def tearDown(self): + JCLTestCase.tearDown(self) + if os.path.exists(self.config_file): + os.unlink(self.config_file) + + def _check_actions(self, info_query, expected_actions=None, action_index=0): + actions = info_query.xpath_eval("c:command/c:actions", + {"c": "http://jabber.org/protocol/commands"}) + if expected_actions is None: + self.assertEquals(len(actions), 0) + else: + self.assertEquals(len(actions), 1) + self.assertEquals(actions[0].prop("execute"), + expected_actions[action_index]) + children = actions[0].children + for action in expected_actions: + self.assertNotEquals(children, None) + self.assertEquals(children.name, action) + children = children.next + +class JCLCommandManager_TestCase(JCLCommandManagerTestCase): + def test_init(self): + command_manager = JCLCommandManager(self.comp, + self.comp.account_manager) + self.assertEquals(len(command_manager.commands), 23) + +class JCLCommandManagerAddFormSelectUserJID_TestCase(JCLCommandManagerTestCase): + """ + Test add_form_select_user_jid* method of JCLCommandManager class + """ + + def test_add_form_select_users_jids(self): + """ + test add_form_select_user_jid method which should add a field to + select multiple JIDs + """ + self.command_manager.add_form_select_users_jids(self.command_node, + "title", "description", + Lang.en.field_users_jids) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "title" + + "description" + + "" + + "", + self.command_node, True)) + + def test_add_form_select_user_jid(self): + """ + test add_form_select_users_jid method which should add a field to + select a JID + """ + self.command_manager.add_form_select_user_jid(self.command_node, + "title", "description", + Lang.en.field_user_jid) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "title" + + "description" + + "" + + "", + self.command_node, True)) + +class JCLCommandManagerAddFormSelectAccount_TestCase(JCLCommandManagerTestCase): + """ + Test add_form_select_account* method of JCLCommandManager class + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.session_context = {} + self.session_context["user_jids"] = ["test1@test.com", "test2@test.com"] + + def test_add_form_select_accounts(self): + """ + test add_form_select_accounts method which should add a field to + select accounts for given JIDs + """ + self.command_manager.add_form_select_accounts(self.session_context, + self.command_node, + Lang.en, + "title", "description") + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "title" + + "description" + + "" + + "" + + "" + + "" + + "" + + "", + self.command_node, True)) + + def test_add_form_select_accounts_without_user_jid(self): + """ + test add_form_select_accounts method which should add a field to + select accounts for given JIDs but don't show JID in labels + """ + self.command_manager.add_form_select_accounts(self.session_context, + self.command_node, + Lang.en, + "title", "description", + show_user_jid=False) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "title" + + "description" + + "" + + "" + + "" + + "" + + "" + + "", + self.command_node, True)) + + def test_add_form_select_accounts_filtered(self): + """ + test add_form_select_accounts method which should add a field to + select accounts for given JIDs with a filter + """ + self.account21.enabled = False + self.command_manager.add_form_select_accounts(self.session_context, + self.command_node, + Lang.en, + "title", "description", + Account.q.enabled==True) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "title" + + "description" + + "" + + "" + + "" + + "" + + "", + self.command_node, True)) + + def test_add_form_select_account(self): + """ + test add_form_select_account method which should add a field to + select one accounts for a given JID + """ + self.session_context["user_jid"] = ["test1@test.com"] + self.command_manager.add_form_select_account(self.session_context, + self.command_node, + Lang.en, + "title", "description") + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "title" + + "description" + + "" + + "" + + "" + + "", + self.command_node, True)) + +class JCLCommandManagerAddUserCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'add-user' ad-hoc command method. + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#add-user") + + def check_step_1(self, result, to_jid, is_admin=False): + """ + Check result of step 1 of 'add-user' ad-hoc command + """ + result_iq = result[0].xmlnode + result_iq.setNs(None) + xml_ref = u"" \ + + "" \ + + "" \ + + "" \ + + "" + Lang.en.command_add_user + "" \ + + "" + Lang.en.command_add_user_1_description \ + + "" \ + + "" \ + + "" \ + + "" + if is_admin: + xml_ref += u"" + xml_ref += "" + self.assertTrue(jcl.tests.is_xml_equal(\ + xml_ref, + result_iq, True)) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + return session_id + + def check_step_2(self, result, session_id, to_jid, new_jid): + """ + Check result of step 2 of 'add-user' ad-hoc command. + """ + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.register_title + "" + + "" + Lang.en.register_instructions + + "" + + "" + + " " + + " " + + "1" + + "choice2" + + "" + + "" + + "" + + "44" + + "", + result_iq, True)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["account_type"], ["Example"]) + self.assertEquals(context_session["user_jid"], [new_jid]) + + def check_step_3(self, result, session_id, to_jid, new_jid): + """ + """ + _account = account.get_account(new_jid, + "account1") + self.assertNotEquals(_account, None) + self.assertEquals(_account.user.jid, new_jid) + self.assertEquals(_account.name, "account1") + self.assertEquals(_account.jid, "account1@" + unicode(self.comp.jid)) + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True, test_sibling=False)) + result_iq = result[1].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"", + result_iq, True, test_sibling=False)) + result_iq = result[2].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + _account.get_new_message_subject(Lang.en) + + "" + + "" + _account.get_new_message_body(Lang.en) + + "", + result_iq, True, test_sibling=False)) + result_iq = result[3].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"", + result_iq, True, test_sibling=False)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["name"], ["account1"]) + self.assertEquals(context_session["login"], ["login1"]) + self.assertEquals(context_session["password"], ["pass1"]) + self.assertEquals(context_session["store_password"], ["1"]) + self.assertEquals(context_session["test_enum"], ["choice2"]) + self.assertEquals(context_session["test_int"], ["42"]) + + def test_execute_add_user(self): + """ + test 'add-user' ad-hoc command with an admin user. + """ + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#add-user", + "execute") + session_id = self.check_step_1(result, "admin@test.com", is_admin=True) + + # Second step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#add-user", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="list-single", + name="account_type", + value="Example"), + Field(field_type="jid-single", + name="user_jid", + value="user2@test.com")]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#add-user", + "next") + self.check_step_2(result, session_id, + "admin@test.com", "user2@test.com") + + # Third step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#add-user", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="text-single", + name="name", + value="account1"), + Field(field_type="text-single", + name="login", + value="login1"), + Field(field_type="text-private", + name="password", + value="pass1"), + Field(field_type="boolean", + name="store_password", + value="1"), + Field(field_type="list-single", + name="test_enum", + value="choice2"), + Field(field_type="text-single", + name="test_int", + value="42")], + action="complete") + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#add-user", + "execute") + self.check_step_3(result, session_id, + "admin@test.com", "user2@test.com") + + def test_execute_add_user_not_admin(self): + """ + test 'add-user' ad-hoc command without an admin user. + """ + self.info_query.set_from("test4@test.com") + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#add-user", + "execute") + session_id = self.check_step_1(result, "test4@test.com") + + # Second step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#add-user", + session_id=session_id, + from_jid="test4@test.com", + fields=[Field(field_type="list-single", + name="account_type", + value="Example")]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#add-user", + "next") + context_session = self.check_step_2(result, session_id, + "test4@test.com", "test4@test.com") + + # Third step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#add-user", + session_id=session_id, + from_jid="test4@test.com", + fields=[Field(field_type="text-single", + name="name", + value="account1"), + Field(field_type="text-single", + name="login", + value="login1"), + Field(field_type="text-private", + name="password", + value="pass1"), + Field(field_type="boolean", + name="store_password", + value="1"), + Field(field_type="list-single", + name="test_enum", + value="choice2"), + Field(field_type="text-single", + name="test_int", + value="42")], + action="complete") + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#add-user", + "execute") + self.check_step_3(result, session_id, + "test4@test.com", "test4@test.com") + + def test_execute_add_user_prev(self): + """ + test 'add-user' ad-hoc command with an admin user. Test 'prev' action. + """ + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#add-user", + "execute") + session_id = self.check_step_1(result, "admin@test.com", is_admin=True) + + # Second step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#add-user", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="list-single", + name="account_type", + value="Example"), + Field(field_type="jid-single", + name="user_jid", + value="user2@test.com")]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#add-user", + "next") + self.check_step_2(result, session_id, + "admin@test.com", "user2@test.com") + + # First step again + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#add-user", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="text-single", + name="name", + value="account1"), + Field(field_type="text-single", + name="login", + value="login1"), + Field(field_type="text-private", + name="password", + value="pass1"), + Field(field_type="boolean", + name="store_password", + value="1"), + Field(field_type="list-single", + name="test_enum", + value="choice2"), + Field(field_type="text-single", + name="test_int", + value="42")], + action="prev") + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#add-user", + "prev") + other_session_id = self.check_step_1(result, "admin@test.com", + is_admin=True) + self.assertEquals(other_session_id, session_id) + def test_execute_add_user_cancel(self): + """ + Test cancel 'add-user' ad-hoc command . + """ + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#add-user", + "execute") + session_id = self.check_step_1(result, "admin@test.com", is_admin=True) + + # Second step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#add-user", + session_id=session_id, + from_jid="admin@test.com", + action="cancel") + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#add-user", + "cancel") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True)) + +class JCLCommandManagerDeleteUserCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'delete-user' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#delete-user") + + def test_execute_delete_user(self): + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#delete-user", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_delete_user + "" + + "" + Lang.en.command_delete_user_1_description + + "" + + "" + + "", + result_iq, True)) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + + # Second step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#delete-user", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="jid-multi", + name="user_jids", + values=["test1@test.com", "test2@test.com"])]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#delete-user", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_delete_user + "" + + "" + Lang.en.command_delete_user_2_description + + "" + + "" + + "" + + "" + + "" + + "" + + "", + result_iq, True)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["user_jids"], + ["test1@test.com", "test2@test.com"]) + + # Third step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#delete-user", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="list-multi", + name="account_names", + values=["account11/test1@test.com", + "account11/test2@test.com"])], + action="complete") + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#delete-user", + "execute") + self.assertEquals(context_session["account_names"], + ["account11/test1@test.com", + "account11/test2@test.com"]) + test1_accounts = account.get_accounts("test1@test.com") + self.assertEquals(test1_accounts.count(), 1) + self.assertEquals(test1_accounts[0].name, "account12") + test2_accounts = account.get_accounts("test2@test.com") + self.assertEquals(test2_accounts.count(), 1) + self.assertEquals(test2_accounts[0].name, "account21") + test3_accounts = account.get_accounts("test3@test.com") + self.assertEquals(test3_accounts.count(), 2) + + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True, test_sibling=False)) + result_iq = result[1].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"", + result_iq, True, test_sibling=False)) + result_iq = result[2].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"", + result_iq, True, test_sibling=False)) + result_iq = result[3].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"", + result_iq, True, test_sibling=False)) + result_iq = result[4].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"", + result_iq, True, test_sibling=False)) + +class JCLCommandManagerDisableUserCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'disable-user' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.account11.enabled = True + self.account12.enabled = False + self.account21.enabled = False + self.account22.enabled = True + self.account31.enabled = False + self.account32.enabled = False + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#disable-user") + + def test_execute_disable_user(self): + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#disable-user", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_disable_user + "" + + "" + Lang.en.command_disable_user_1_description + + "" + + "" + + "", + result_iq, True)) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + + # Second step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#disable-user", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="jid-multi", + name="user_jids", + values=["test1@test.com", "test2@test.com"])]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#disable-user", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_disable_user + "" + + "" + Lang.en.command_disable_user_2_description + + "" + + "" + + "" + + "" + + "", + result_iq, True)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["user_jids"], + ["test1@test.com", "test2@test.com"]) + + # Third step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#disable-user", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="list-multi", + name="account_names", + values=["account11/test1@test.com", + "account11/test2@test.com"])], + action="complete") + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#disable-user", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True, test_sibling=False)) + self.assertEquals(context_session["account_names"], + ["account11/test1@test.com", + "account11/test2@test.com"]) + for _account in account.get_all_accounts(): + self.assertFalse(_account.enabled) + +class JCLCommandManagerReenableUserCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'reenable-user' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.account11.enabled = False + self.account12.enabled = True + self.account21.enabled = True + self.account22.enabled = False + self.account31.enabled = True + self.account32.enabled = True + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#reenable-user") + + def test_execute_reenable_user(self): + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#reenable-user", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_reenable_user + "" + + "" + Lang.en.command_reenable_user_1_description + + "" + + "" + + "", + result_iq, True)) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + + # Second step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#reenable-user", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="jid-multi", + name="user_jids", + values=["test1@test.com", "test2@test.com"])]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#reenable-user", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_reenable_user + "" + + "" + Lang.en.command_reenable_user_2_description + + "" + + "" + + "" + + "" + + "", + result_iq, True)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["user_jids"], + ["test1@test.com", "test2@test.com"]) + + # Third step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#reenable-user", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="list-multi", + name="account_names", + values=["account11/test1@test.com", + "account11/test2@test.com"])], + action="complete") + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#reenable-user", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True, test_sibling=False)) + self.assertEquals(context_session["account_names"], + ["account11/test1@test.com", + "account11/test2@test.com"]) + for _account in account.get_all_accounts(): + self.assertTrue(_account.enabled) + +class JCLCommandManagerEndUserSessionCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'end-user-session' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.account11.status = account.ONLINE + self.account22.status = account.ONLINE + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#end-user-session") + + def test_execute_end_user_session(self): + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#end-user-session", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_end_user_session + "" + + "" + Lang.en.command_end_user_session_1_description + + "" + + "" + + "", + result_iq, True)) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + + # Second step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#end-user-session", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="jid-multi", + name="user_jids", + values=["test1@test.com", "test2@test.com"])]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#end-user-session", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_end_user_session + "" + + "" + Lang.en.command_end_user_session_2_description + + "" + + "" + + "" + + "" + + "", + result_iq, True)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["user_jids"], + ["test1@test.com", "test2@test.com"]) + + # Third step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#end-user-session", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="list-multi", + name="account_names", + values=["account11/test1@test.com", + "account11/test2@test.com"])], + action="complete") + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#end-user-session", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True, test_sibling=False)) + self.assertEquals(context_session["account_names"], + ["account11/test1@test.com", + "account11/test2@test.com"]) + result_iq = result[1].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"", + result_iq, True, test_sibling=False)) + result_iq = result[2].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"", + result_iq, True, test_sibling=False)) + +# disabled command +# def test_execute_get_user_password(self): +# self.comp.account_manager.account_classes = (ExampleAccount, +# Example2Account) +# model.db_connect() +# user1 = User(jid="test1@test.com") +# user2 = User(jid="test2@test.com") +# account11 = ExampleAccount(user=user1, +# name="account11", +# jid="account11@" + unicode(self.comp.jid)) +# account11.password = "pass1" +# account12 = Example2Account(user=user1, +# name="account12", +# jid="account12@" + unicode(self.comp.jid)) +# account21 = ExampleAccount(user=user2, +# name="account21", +# jid="account21@" + unicode(self.comp.jid)) +# account22 = ExampleAccount(user=user2, +# name="account11", +# jid="account11@" + unicode(self.comp.jid)) +# model.db_disconnect() +# info_query = Iq(stanza_type="set", +# from_jid="admin@test.com", +# to_jid=self.comp.jid) +# command_node = info_query.set_new_content(command.COMMAND_NS, "command") +# command_node.setProp("node", "http://jabber.org/protocol/admin#get-user-password") +# result = self.command_manager.apply_command_action(info_query, +# "http://jabber.org/protocol/admin#get-user-password", +# "execute") +# self.assertNotEquals(result, None) +# self.assertEquals(len(result), 1) +# xml_command = result[0].xpath_eval("c:command", +# {"c": "http://jabber.org/protocol/commands"})[0] +# self.assertEquals(xml_command.prop("status"), "executing") +# self.assertNotEquals(xml_command.prop("sessionid"), None) +# self._check_actions(result[0], ["next"]) + +# # Second step +# info_query = Iq(stanza_type="set", +# from_jid="admin@test.com", +# to_jid=self.comp.jid) +# command_node = info_query.set_new_content(command.COMMAND_NS, "command") +# command_node.setProp("node", "http://jabber.org/protocol/admin#get-user-password") +# session_id = xml_command.prop("sessionid") +# command_node.setProp("sessionid", session_id) +# command_node.setProp("action", "next") +# submit_form = Form(xmlnode_or_type="submit") +# submit_form.add_field(field_type="jid-single", +# name="user_jid", +# value="test1@test.com") +# submit_form.as_xml(command_node) +# result = self.command_manager.apply_command_action(info_query, +# "http://jabber.org/protocol/admin#get-user-password", +# "execute") +# self.assertNotEquals(result, None) +# self.assertEquals(len(result), 1) +# xml_command = result[0].xpath_eval("c:command", +# {"c": "http://jabber.org/protocol/commands"})[0] +# self.assertEquals(xml_command.prop("status"), "executing") +# self.assertEquals(xml_command.prop("sessionid"), session_id) +# self._check_actions(result[0], ["prev", "complete"], 1) +# context_session = self.command_manager.sessions[session_id][1] +# self.assertEquals(context_session["user_jid"], +# ["test1@test.com"]) + +# # Third step +# info_query = Iq(stanza_type="set", +# from_jid="admin@test.com", +# to_jid=self.comp.jid) +# command_node = info_query.set_new_content(command.COMMAND_NS, "command") +# command_node.setProp("node", "http://jabber.org/protocol/admin#get-user-password") +# command_node.setProp("sessionid", session_id) +# command_node.setProp("action", "complete") +# submit_form = Form(xmlnode_or_type="submit") +# submit_form.add_field(field_type="list-single", +# name="account_name", +# value="account11/test1@test.com") +# submit_form.as_xml(command_node) +# result = self.command_manager.apply_command_action(info_query, +# "http://jabber.org/protocol/admin#get-user-password", +# "execute") +# xml_command = result[0].xpath_eval("c:command", +# {"c": "http://jabber.org/protocol/commands"})[0] +# self.assertEquals(xml_command.prop("status"), "completed") +# self.assertEquals(xml_command.prop("sessionid"), session_id) +# self._check_actions(result[0]) +# self.assertEquals(context_session["account_name"], +# ["account11/test1@test.com"]) +# stanza_sent = result +# self.assertEquals(len(stanza_sent), 1) +# iq_result = stanza_sent[0] +# self.assertTrue(isinstance(iq_result, Iq)) +# self.assertEquals(iq_result.get_node().prop("type"), "result") +# self.assertEquals(iq_result.get_from(), self.comp.jid) +# self.assertEquals(iq_result.get_to(), "admin@test.com") +# fields = iq_result.xpath_eval("c:command/data:x/data:field", +# {"c": "http://jabber.org/protocol/commands", +# "data": "jabber:x:data"}) +# self.assertEquals(len(fields), 3) +# self.assertEquals(fields[0].prop("var"), "FORM_TYPE") +# self.assertEquals(fields[0].prop("type"), "hidden") +# self.assertEquals(fields[0].children.name, "value") +# self.assertEquals(fields[0].children.content, +# "http://jabber.org/protocol/admin") +# self.assertEquals(fields[1].prop("var"), "accountjids") +# self.assertEquals(fields[1].children.name, "value") +# self.assertEquals(fields[1].children.content, +# "test1@test.com") +# self.assertEquals(fields[2].prop("var"), "password") +# self.assertEquals(fields[2].children.name, "value") +# self.assertEquals(fields[2].children.content, +# "pass1") + +# disabled command +# def test_execute_change_user_password(self): +# self.comp.account_manager.account_classes = (ExampleAccount, +# Example2Account) +# model.db_connect() +# user1 = User(jid="test1@test.com") +# account11 = ExampleAccount(user=user1, +# name="account11", +# jid="account11@" + unicode(self.comp.jid)) +# account11.password = "pass1" +# account12 = Example2Account(user=user1, +# name="account12", +# jid="account12@" + unicode(self.comp.jid)) +# user2 = User(jid="test2@test.com") +# account21 = ExampleAccount(user=user2, +# name="account21", +# jid="account21@" + unicode(self.comp.jid)) +# account22 = ExampleAccount(user=user2, +# name="account11", +# jid="account11@" + unicode(self.comp.jid)) +# model.db_disconnect() +# info_query = Iq(stanza_type="set", +# from_jid="admin@test.com", +# to_jid=self.comp.jid) +# command_node = info_query.set_new_content(command.COMMAND_NS, "command") +# command_node.setProp("node", "http://jabber.org/protocol/admin#change-user-password") +# result = self.command_manager.apply_command_action(info_query, +# "http://jabber.org/protocol/admin#change-user-password", +# "execute") +# self.assertNotEquals(result, None) +# self.assertEquals(len(result), 1) +# xml_command = result[0].xpath_eval("c:command", +# {"c": "http://jabber.org/protocol/commands"})[0] +# self.assertEquals(xml_command.prop("status"), "executing") +# self.assertNotEquals(xml_command.prop("sessionid"), None) +# self._check_actions(result[0], ["next"]) + +# # Second step +# info_query = Iq(stanza_type="set", +# from_jid="admin@test.com", +# to_jid=self.comp.jid) +# command_node = info_query.set_new_content(command.COMMAND_NS, "command") +# command_node.setProp("node", "http://jabber.org/protocol/admin#change-user-password") +# session_id = xml_command.prop("sessionid") +# command_node.setProp("sessionid", session_id) +# command_node.setProp("action", "next") +# submit_form = Form(xmlnode_or_type="submit") +# submit_form.add_field(field_type="jid-single", +# name="user_jid", +# value="test1@test.com") +# submit_form.as_xml(command_node) +# result = self.command_manager.apply_command_action(info_query, +# "http://jabber.org/protocol/admin#change-user-password", +# "execute") +# self.assertNotEquals(result, None) +# self.assertEquals(len(result), 1) +# xml_command = result[0].xpath_eval("c:command", +# {"c": "http://jabber.org/protocol/commands"})[0] +# self.assertEquals(xml_command.prop("status"), "executing") +# self.assertEquals(xml_command.prop("sessionid"), session_id) +# self._check_actions(result[0], ["prev", "complete"], 1) +# context_session = self.command_manager.sessions[session_id][1] +# self.assertEquals(context_session["user_jid"], +# ["test1@test.com"]) +# fields = result[0].xpath_eval("c:command/data:x/data:field", +# {"c": "http://jabber.org/protocol/commands", +# "data": "jabber:x:data"}) +# self.assertEquals(len(fields), 2) + +# # Third step +# info_query = Iq(stanza_type="set", +# from_jid="admin@test.com", +# to_jid=self.comp.jid) +# command_node = info_query.set_new_content(command.COMMAND_NS, "command") +# command_node.setProp("node", "http://jabber.org/protocol/admin#change-user-password") +# command_node.setProp("sessionid", session_id) +# command_node.setProp("action", "complete") +# submit_form = Form(xmlnode_or_type="submit") +# submit_form.add_field(field_type="list-single", +# name="account_name", +# value="account11/test1@test.com") +# submit_form.add_field(field_type="text-private", +# name="password", +# value="pass2") +# submit_form.as_xml(command_node) +# result = self.command_manager.apply_command_action(info_query, +# "http://jabber.org/protocol/admin#change-user-password", +# "execute") +# xml_command = result[0].xpath_eval("c:command", +# {"c": "http://jabber.org/protocol/commands"})[0] +# self.assertEquals(xml_command.prop("status"), "completed") +# self.assertEquals(xml_command.prop("sessionid"), session_id) +# self._check_actions(result[0]) +# self.assertEquals(context_session["account_name"], +# ["account11/test1@test.com"]) +# self.assertEquals(context_session["password"], +# ["pass2"]) +# self.assertEquals(account11.password, "pass2") + +class JCLCommandManagerGetUserRosterCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'get-user-roster' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#get-user-roster") + ljid111 = LegacyJID(legacy_address="test111@test.com", + jid="test111%test.com@" + unicode(self.comp.jid), + account=self.account11) + ljid112 = LegacyJID(legacy_address="test112@test.com", + jid="test112%test.com@" + unicode(self.comp.jid), + account=self.account11) + ljid121 = LegacyJID(legacy_address="test121@test.com", + jid="test121%test.com@" + unicode(self.comp.jid), + account=self.account12) + ljid211 = LegacyJID(legacy_address="test211@test.com", + jid="test211%test.com@" + unicode(self.comp.jid), + account=self.account21) + ljid212 = LegacyJID(legacy_address="test212@test.com", + jid="test212%test.com@" + unicode(self.comp.jid), + account=self.account21) + ljid221 = LegacyJID(legacy_address="test221@test.com", + jid="test221%test.com@" + unicode(self.comp.jid), + account=self.account22) + + def test_execute_get_user_roster(self): + result = self.command_manager.apply_command_action( + self.info_query, + "http://jabber.org/protocol/admin#get-user-roster", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_get_user_roster + "" + + "" + Lang.en.command_get_user_roster_1_description + + "" + + "" + + "", + result_iq, True)) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + + # Second step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#get-user-roster", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="jid-single", + name="user_jid", + value="test1@test.com")], + action="complete") + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#get-user-roster", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "http://jabber.org/protocol/admin" + + "test1@test.com" + + "" + + "" + + "" + + "" + + "" + + "" + + "", + result_iq, True)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["user_jid"], + ["test1@test.com"]) + +class JCLCommandManagerGetUserLastLoginCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'get-user-lastlogin' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#get-user-lastlogin") + + def test_execute_get_user_lastlogin(self): + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#get-user-lastlogin", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_get_user_lastlogin + "" + + "" + Lang.en.command_get_user_lastlogin_1_description + + "" + + "" + + "", + result_iq, True)) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + + # Second step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#get-user-lastlogin", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="jid-single", + name="user_jid", + value="test1@test.com")]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#get-user-lastlogin", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_get_user_lastlogin + "" + + "" + Lang.en.command_get_user_lastlogin_2_description + + "" + + "" + + "" + + "" + + "", + result_iq, True)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["user_jid"], + ["test1@test.com"]) + + # Third step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#get-user-lastlogin", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="list-single", + name="account_name", + value="account11/test1@test.com")], + action="complete") + result = self.command_manager.apply_command_action(info_query, + "http://jabber.org/protocol/admin#get-user-lastlogin", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "http://jabber.org/protocol/admin" + + "test1@test.com" + + "" + + self.account11.lastlogin.isoformat(" ") + + "", + result_iq, True)) + +class JCLCommandManagerGetRegisteredUsersNumCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'get-registered-users-num' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#get-registered-users-num") + + def test_execute_get_registered_users_num(self): + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#get-registered-users-num", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "http://jabber.org/protocol/admin" + + "6" + + "", + result_iq, True)) + +class JCLCommandManagerGetDisabledUsersNumCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'get-disabled-users-num' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.account11.enabled = False + self.account22.enabled = False + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#get-disabled-users-num") + + def test_execute_get_disabled_users_num(self): + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#get-disabled-users-num", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "http://jabber.org/protocol/admin" + + "2" + + "", + result_iq, True)) + +class JCLCommandManagerGetOnlineUsersNumCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'get-online-users-num' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.account11.status = account.ONLINE + self.account12.status = "away" + self.account22.status = "chat" + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#get-online-users-num") + + def test_execute_get_online_users_num(self): + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#get-online-users-num", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "http://jabber.org/protocol/admin" + + "3" + + "", + result_iq, True)) + +class JCLCommandManagerGetRegisteredUsersListCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'get-registered-users-list' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#get-registered-users-list") + + def test_execute_get_registered_users_list(self): + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#get-registered-users-list", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "http://jabber.org/protocol/admin" + + "" + + "test1@test.com (account11 ExampleAccount)" + + "test1@test.com (account12 Example2Account)" + + "test2@test.com (account21 ExampleAccount)" + + "test2@test.com (account11 ExampleAccount)" + + "test3@test.com (account31 ExampleAccount)" + + "test3@test.com (account32 Example2Account)" + + "", + result_iq, True)) + + def test_execute_get_registered_users_list_max(self): + user10 = User(jid="test10@test.com") + user20 = User(jid="test20@test.com") + for i in xrange(10): + ExampleAccount(user=user10, + name="account101" + str(i), + jid="account101" + str(i) + "@" + unicode(self.comp.jid)) + Example2Account(user=user10, + name="account102" + str(i), + jid="account102" + str(i) + "@" + unicode(self.comp.jid)) + ExampleAccount(user=user20, + name="account20" + str(i), + jid="account20" + str(i) + "@" + unicode(self.comp.jid)) + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#get-registered-users-list", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + + "http://jabber.org/protocol/admin" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "", + result_iq, True)) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + + # Second step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#get-registered-users-list", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="list-single", + name="max_items", + value="25")]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#get-registered-users-list", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "http://jabber.org/protocol/admin" + + "" + + "test1@test.com (account11 ExampleAccount)" + + "test1@test.com (account12 Example2Account)" + + "test2@test.com (account21 ExampleAccount)" + + "test2@test.com (account11 ExampleAccount)" + + "test3@test.com (account31 ExampleAccount)" + + "test3@test.com (account32 Example2Account)" + + "test10@test.com (account1010 ExampleAccount)" + + "test10@test.com (account1020 Example2Account)" + + "test20@test.com (account200 ExampleAccount)" + + "test10@test.com (account1011 ExampleAccount)" + + "test10@test.com (account1021 Example2Account)" + + "test20@test.com (account201 ExampleAccount)" + + "test10@test.com (account1012 ExampleAccount)" + + "test10@test.com (account1022 Example2Account)" + + "test20@test.com (account202 ExampleAccount)" + + "test10@test.com (account1013 ExampleAccount)" + + "test10@test.com (account1023 Example2Account)" + + "test20@test.com (account203 ExampleAccount)" + + "test10@test.com (account1014 ExampleAccount)" + + "test10@test.com (account1024 Example2Account)" + + "test20@test.com (account204 ExampleAccount)" + + "test10@test.com (account1015 ExampleAccount)" + + "test10@test.com (account1025 Example2Account)" + + "test20@test.com (account205 ExampleAccount)" + + "test10@test.com (account1016 ExampleAccount)" + + "", + result_iq, True)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["max_items"], + ["25"]) + +class JCLCommandManagerGetDisabledUsersListCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'get-disabled-users-list' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#get-disabled-users-list") + + def test_execute_get_disabled_users_list(self): + self.account11.enabled = False + self.account12.enabled = False + self.account22.enabled = False + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#get-disabled-users-list", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "http://jabber.org/protocol/admin" + + "" + + "test1@test.com (account11 ExampleAccount)" + + "test1@test.com (account12 Example2Account)" + + "test2@test.com (account11 ExampleAccount)" + + "", + result_iq, True)) + + def test_execute_get_disabled_users_list_max(self): + user10 = User(jid="test10@test.com") + user20 = User(jid="test20@test.com") + for i in xrange(20): + _account = ExampleAccount(user=user10, + name="account101" + str(i), + jid="account101" + str(i) + + "@" + unicode(self.comp.jid)) + _account.enabled = False + Example2Account(user=user10, + name="account102" + str(i), + jid="account102" + str(i) + "@" + unicode(self.comp.jid)) + _account = ExampleAccount(user=user20, + name="account20" + str(i), + jid="account20" + str(i) + + "@" + unicode(self.comp.jid)) + _account.enabled = False + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#get-disabled-users-list", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + + "http://jabber.org/protocol/admin" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "", + result_iq, True)) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + + # Second step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#get-disabled-users-list", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="list-single", + name="max_items", + value="25")]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#get-disabled-users-list", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "http://jabber.org/protocol/admin" + + "" + + "test10@test.com (account1010 ExampleAccount)" + + "test20@test.com (account200 ExampleAccount)" + + "test10@test.com (account1011 ExampleAccount)" + + "test20@test.com (account201 ExampleAccount)" + + "test10@test.com (account1012 ExampleAccount)" + + "test20@test.com (account202 ExampleAccount)" + + "test10@test.com (account1013 ExampleAccount)" + + "test20@test.com (account203 ExampleAccount)" + + "test10@test.com (account1014 ExampleAccount)" + + "test20@test.com (account204 ExampleAccount)" + + "test10@test.com (account1015 ExampleAccount)" + + "test20@test.com (account205 ExampleAccount)" + + "test10@test.com (account1016 ExampleAccount)" + + "test20@test.com (account206 ExampleAccount)" + + "test10@test.com (account1017 ExampleAccount)" + + "test20@test.com (account207 ExampleAccount)" + + "test10@test.com (account1018 ExampleAccount)" + + "test20@test.com (account208 ExampleAccount)" + + "test10@test.com (account1019 ExampleAccount)" + + "test20@test.com (account209 ExampleAccount)" + + "test10@test.com (account10110 ExampleAccount)" + + "test20@test.com (account2010 ExampleAccount)" + + "test10@test.com (account10111 ExampleAccount)" + + "test20@test.com (account2011 ExampleAccount)" + + "test10@test.com (account10112 ExampleAccount)" + + "", + result_iq, True)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["max_items"], + ["25"]) + +class JCLCommandManagerGetOnlineUsersListCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'get-online-users-list' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#get-online-users-list") + + def test_execute_get_online_users_list(self): + self.account11.status = account.ONLINE + self.account12.status = "away" + self.account22.status = "xa" + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#get-online-users-list", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "http://jabber.org/protocol/admin" + + "" + + "test1@test.com (account11 ExampleAccount)" + + "test1@test.com (account12 Example2Account)" + + "test2@test.com (account11 ExampleAccount)" + + "", + result_iq, True)) + + def test_execute_get_online_users_list_max(self): + user10 = User(jid="test10@test.com") + user20 = User(jid="test20@test.com") + for i in xrange(20): + _account = ExampleAccount(user=user10, + name="account101" + str(i), + jid="account101" + str(i) + + "@" + unicode(self.comp.jid)) + _account.status = account.ONLINE + Example2Account(user=user10, + name="account102" + str(i), + jid="account102" + str(i) + "@" + unicode(self.comp.jid)) + _account = ExampleAccount(user=user20, + name="account20" + str(i), + jid="account20" + str(i) + + "@" + unicode(self.comp.jid)) + _account.status = "away" + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#get-online-users-list", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + + "http://jabber.org/protocol/admin" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "", + result_iq, True)) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + + # Second step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#get-online-users-list", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="list-single", + name="max_items", + value="25")]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#get-online-users-list", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "http://jabber.org/protocol/admin" + + "" + + "test10@test.com (account1010 ExampleAccount)" + + "test20@test.com (account200 ExampleAccount)" + + "test10@test.com (account1011 ExampleAccount)" + + "test20@test.com (account201 ExampleAccount)" + + "test10@test.com (account1012 ExampleAccount)" + + "test20@test.com (account202 ExampleAccount)" + + "test10@test.com (account1013 ExampleAccount)" + + "test20@test.com (account203 ExampleAccount)" + + "test10@test.com (account1014 ExampleAccount)" + + "test20@test.com (account204 ExampleAccount)" + + "test10@test.com (account1015 ExampleAccount)" + + "test20@test.com (account205 ExampleAccount)" + + "test10@test.com (account1016 ExampleAccount)" + + "test20@test.com (account206 ExampleAccount)" + + "test10@test.com (account1017 ExampleAccount)" + + "test20@test.com (account207 ExampleAccount)" + + "test10@test.com (account1018 ExampleAccount)" + + "test20@test.com (account208 ExampleAccount)" + + "test10@test.com (account1019 ExampleAccount)" + + "test20@test.com (account209 ExampleAccount)" + + "test10@test.com (account10110 ExampleAccount)" + + "test20@test.com (account2010 ExampleAccount)" + + "test10@test.com (account10111 ExampleAccount)" + + "test20@test.com (account2011 ExampleAccount)" + + "test10@test.com (account10112 ExampleAccount)" + + "", + result_iq, True)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["max_items"], + ["25"]) + +class JCLCommandManagerAnnounceCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'announce' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.account11.status = account.ONLINE + self.account12.status = "away" + self.account22.status = "xa" + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#announce") + + def _common_execute_announce(self): + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#announce", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_announce + "" + + "" + Lang.en.command_announce_1_description + + "" + + "" + + "http://jabber.org/protocol/admin" + + "" + + "", + result_iq, True)) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + return session_id + + def test_execute_announce(self): + session_id = self._common_execute_announce() + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#announce", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="text-multi", + name="announcement", + value=["test announce"])]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#announce", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True, test_sibling=False)) + result_iq = result[1].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "test announce", + result_iq, True, test_sibling=False)) + result_iq = result[2].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "test announce", + result_iq, True, test_sibling=False)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["announcement"], + ["test announce"]) + + def test_execute_announce_no_announcement(self): + session_id = self._common_execute_announce() + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#announce", + session_id=session_id, + from_jid="admin@test.com") + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#announce", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True, test_sibling=False)) + context_session = self.command_manager.sessions[session_id][1] + self.assertFalse(context_session.has_key("announcement")) + +class JCLCommandManagerSetMOTDCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'set-motd' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.account11.status = account.ONLINE + self.account12.status = "away" + self.account21.status = account.OFFLINE + self.account22.status = account.OFFLINE + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#set-motd") + + def test_execute_set_motd(self): + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#set-motd", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_set_motd + "" + + "" + Lang.en.command_set_motd_1_description + + "" + + "" + + "http://jabber.org/protocol/admin" + + " " + + "", + result_iq, True)) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + + # Second step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#edit-motd", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="text-multi", + name="motd", + value=["Message Of The Day"])]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#set-motd", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True, test_sibling=False)) + result_iq = result[1].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "Message Of The Day", + result_iq, True, test_sibling=False)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["motd"], + ["Message Of The Day"]) + self.assertTrue(self.account11.user.has_received_motd) + self.assertFalse(self.account21.user.has_received_motd) + +class JCLCommandManagerEditMOTDCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'edit-motd' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.comp.set_motd("test motd") + self.account11.status = account.ONLINE + self.account12.status = "away" + self.user2.has_received_motd = True + self.account21.status = account.OFFLINE + self.account22.status = account.OFFLINE + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#edit-motd") + + def test_execute_edit_motd(self): + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#edit-motd", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_set_motd + "" + + "" + Lang.en.command_set_motd_1_description + + "" + + "" + + "http://jabber.org/protocol/admin" + + "test motd" + + "", + result_iq, True)) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + + # Second step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#edit-motd", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="text-multi", + name="motd", + value=["Message Of The Day"])]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#edit-motd", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True, test_sibling=False)) + result_iq = result[1].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "Message Of The Day", + result_iq, True, test_sibling=False)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["motd"], + ["Message Of The Day"]) + self.assertTrue(self.account11.user.has_received_motd) + self.assertFalse(self.account21.user.has_received_motd) + self.comp.config.read(self.comp.config_file) + self.assertTrue(self.comp.config.has_option("component", "motd")) + self.assertEquals(self.comp.config.get("component", "motd"), + "Message Of The Day") + +class JCLCommandManagerDeleteMOTDCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'delete-motd' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.comp.set_motd("test motd") + self.account11.status = account.ONLINE + self.account12.status = "away" + self.account21.status = account.OFFLINE + self.account22.status = account.OFFLINE + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#delete-motd") + + def test_execute_delete_motd(self): + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#delete-motd", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True, test_sibling=False)) + self.comp.config.read(self.comp.config_file) + self.assertFalse(self.comp.config.has_option("component", "motd")) + +class JCLCommandManagerSetWelcomeCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'set-welcome' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.comp.set_welcome_message("Welcome Message") + self.account11.status = account.ONLINE + self.account12.status = "away" + self.account21.status = account.OFFLINE + self.account22.status = account.OFFLINE + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#set-welcome") + + def test_execute_set_welcome(self): + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#set-welcome", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_set_welcome + "" + + "" + Lang.en.command_set_welcome_1_description + + "" + + "" + + "http://jabber.org/protocol/admin" + + "Welcome Message" + + "", + result_iq, True)) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + + # Second step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#set-welcome", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="text-multi", + name="welcome", + value=["New Welcome Message"])]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#set-welcome", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True, test_sibling=False)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["welcome"], + ["New Welcome Message"]) + self.comp.config.read(self.comp.config_file) + self.assertTrue(self.comp.config.has_option("component", + "welcome_message")) + self.assertEquals(self.comp.config.get("component", + "welcome_message"), + "New Welcome Message") + +class JCLCommandManagerDeleteWelcomeCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'delete-welcome' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.comp.set_motd("test motd") + self.account11.status = account.ONLINE + self.account12.status = "away" + self.account21.status = account.OFFLINE + self.account22.status = account.OFFLINE + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#delete-welcome") + + def test_execute_delete_welcome(self): + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#delete-welcome", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True, test_sibling=False)) + self.comp.config.read(self.comp.config_file) + self.assertFalse(self.comp.config.has_option("component", + "welcome_message")) + +class JCLCommandManagerEditAdminCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'edit-admin' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.comp.set_admins(["admin1@test.com", "admin2@test.com"]) + self.account11.status = account.ONLINE + self.account12.status = "away" + self.account21.status = account.OFFLINE + self.account22.status = account.OFFLINE + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#edit-admin") + + def test_execute_edit_admin(self): + self.info_query.set_from("admin1@test.com") + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#edit-admin", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_edit_admin + "" + + "" + Lang.en.command_edit_admin_1_description + + "" + + "" + + "http://jabber.org/protocol/admin" + + "admin1@test.com" + + "admin2@test.com" + + "", + result_iq, True)) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + + # Second step + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#edit-admin", + session_id=session_id, + from_jid="admin1@test.com", + fields=[Field(field_type="jid-multi", + name="adminjids", + value=["admin3@test.com", "admin4@test.com"])]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#edit-admin", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True, test_sibling=False)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["adminjids"], + ["admin3@test.com", "admin4@test.com"]) + self.comp.config.read(self.comp.config_file) + self.assertTrue(self.comp.config.has_option("component", "admins")) + self.assertEquals(self.comp.config.get("component", "admins"), + "admin3@test.com,admin4@test.com") + +class JCLCommandManagerRestartCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'restart' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.comp.running = True + self.account11.status = account.ONLINE + self.account12.status = "away" + self.account22.status = "xa" + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#restart") + self.wait_event = threading.Event() + self.command_manager.sleep = lambda delay: self.wait_event.wait(2) + + def _common_execute_restart(self): + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#restart", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_restart + "" + + "" + Lang.en.command_restart_1_description + + "" + + "" + + "http://jabber.org/protocol/admin" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "", + result_iq, True)) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + return session_id + + def test_execute_restart(self): + session_id = self._common_execute_restart() + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#restart", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="list-multi", + name="delay", + value=[1]), + Field(field_type="text-multi", + name="announcement", + value=["service will be restarted in 1 second"])]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#restart", + "execute") + self.assertFalse(self.comp.restart) + self.assertTrue(self.comp.running) + threads = threading.enumerate() + self.assertEquals(len(threads), 2) + self.wait_event.set() + self.command_manager.restart_thread.join(1) + threads = threading.enumerate() + self.assertEquals(len(threads), 1) + self.assertTrue(self.comp.restart) + self.assertFalse(self.comp.running) + + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True, test_sibling=False)) + result_iq = result[1].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "service will be restarted in 1 second", + result_iq, True, test_sibling=False)) + result_iq = result[2].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "service will be restarted in 1 second", + result_iq, True, test_sibling=False)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["announcement"], + ["service will be restarted in 1 second"]) + self.assertEquals(context_session["delay"], + ["1"]) + + def test_execute_restart_no_announcement(self): + session_id = self._common_execute_restart() + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#restart", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="list-multi", + name="delay", + value=[1])]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#restart", + "execute") + self.assertFalse(self.comp.restart) + self.assertTrue(self.comp.running) + threads = threading.enumerate() + self.assertEquals(len(threads), 2) + self.wait_event.set() + self.command_manager.restart_thread.join(1) + threads = threading.enumerate() + self.assertEquals(len(threads), 1) + self.assertTrue(self.comp.restart) + self.assertFalse(self.comp.running) + + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True, test_sibling=False)) + context_session = self.command_manager.sessions[session_id][1] + self.assertFalse(context_session.has_key("announcement")) + self.assertEquals(context_session["delay"], + ["1"]) + +class JCLCommandManagerShutdownCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'shutdown' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.comp.running = True + self.account11.status = account.ONLINE + self.account12.status = "away" + self.account22.status = "xa" + self.command_node.setProp("node", + "http://jabber.org/protocol/admin#shutdown") + self.wait_event = threading.Event() + self.command_manager.sleep = lambda delay: self.wait_event.wait(2) + + def _common_execute_shutdown(self): + result = self.command_manager.apply_command_action(\ + self.info_query, + "http://jabber.org/protocol/admin#shutdown", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.command_shutdown + "" + + "" + Lang.en.command_shutdown_1_description + + "" + + "" + + "http://jabber.org/protocol/admin" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "", + result_iq, True)) + session_id = result_iq.children.prop("sessionid") + self.assertNotEquals(session_id, None) + return session_id + + def test_execute_shutdown(self): + session_id = self._common_execute_shutdown() + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#shutdown", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="list-multi", + name="delay", + value=[1]), + Field(field_type="text-multi", + name="announcement", + value=["service will be shutdown in 1 second"])]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#shutdown", + "execute") + self.assertFalse(self.comp.restart) + self.assertTrue(self.comp.running) + threads = threading.enumerate() + self.assertEquals(len(threads), 2) + self.wait_event.set() + self.command_manager.shutdown_thread.join(1) + threads = threading.enumerate() + self.assertEquals(len(threads), 1) + self.assertFalse(self.comp.restart) + self.assertFalse(self.comp.running) + + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True, test_sibling=False)) + result_iq = result[1].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "service will be shutdown in 1 second", + result_iq, True, test_sibling=False)) + result_iq = result[2].xmlnode + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "service will be shutdown in 1 second", + result_iq, True, test_sibling=False)) + context_session = self.command_manager.sessions[session_id][1] + self.assertEquals(context_session["announcement"], + ["service will be shutdown in 1 second"]) + self.assertEquals(context_session["delay"], + ["1"]) + + def test_execute_shutdown_no_announcement(self): + session_id = self._common_execute_shutdown() + info_query = prepare_submit(\ + node="http://jabber.org/protocol/admin#shutdown", + session_id=session_id, + from_jid="admin@test.com", + fields=[Field(field_type="list-multi", + name="delay", + value=[1])]) + result = self.command_manager.apply_command_action(\ + info_query, + "http://jabber.org/protocol/admin#shutdown", + "execute") + self.assertFalse(self.comp.restart) + self.assertTrue(self.comp.running) + threads = threading.enumerate() + self.assertEquals(len(threads), 2) + self.wait_event.set() + self.command_manager.shutdown_thread.join(1) + threads = threading.enumerate() + self.assertEquals(len(threads), 1) + self.assertFalse(self.comp.restart) + self.assertFalse(self.comp.running) + + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "", + result_iq, True, test_sibling=False)) + context_session = self.command_manager.sessions[session_id][1] + self.assertFalse(context_session.has_key("announcement")) + self.assertEquals(context_session["delay"], + ["1"]) + +class JCLCommandManagerGetLastErrorCommand_TestCase(JCLCommandManagerTestCase): + """ + Test 'get-last-error' ad-hoc command + """ + + def setUp (self, tables=[]): + """ + Prepare data + """ + JCLCommandManagerTestCase.setUp(self, tables) + self.command_node.setProp("node", "jcl#get-last-error") + + def test_execute_get_last_error_no_error(self): + self.info_query.set_from("test1@test.com") + self.info_query.set_to("account11@" + unicode(self.comp.jid)) + result = self.command_manager.apply_command_action(\ + self.info_query, + "jcl#get-last-error", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "" + Lang.en.account_no_error + "" + + "", + result_iq, True)) + + def test_execute_get_last_error(self): + self.info_query.set_from("test1@test.com") + self.info_query.set_to("account11@" + unicode(self.comp.jid)) + self.account11.error = "Current error" + result = self.command_manager.apply_command_action(\ + self.info_query, + "jcl#get-last-error", + "execute") + result_iq = result[0].xmlnode + result_iq.setNs(None) + self.assertTrue(jcl.tests.is_xml_equal(\ + u"" + + "" + + "" + + "" + + "Current error" + + "", + result_iq, True)) + +def suite(): + test_suite = unittest.TestSuite() + test_suite.addTest(unittest.makeSuite(CommandManager_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(FieldNoType_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManager_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerAddFormSelectUserJID_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerAddFormSelectAccount_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerAddUserCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerDeleteUserCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerDisableUserCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerReenableUserCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerEndUserSessionCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerGetUserRosterCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerGetUserLastLoginCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerGetRegisteredUsersNumCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerGetDisabledUsersNumCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerGetOnlineUsersNumCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerAnnounceCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerSetMOTDCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerEditMOTDCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerDeleteMOTDCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerSetWelcomeCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerDeleteWelcomeCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerEditAdminCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerRestartCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerShutdownCommand_TestCase, 'test')) + test_suite.addTest(unittest.makeSuite(JCLCommandManagerGetLastErrorCommand_TestCase, 'test')) + return test_suite + +if __name__ == '__main__': + logger = logging.getLogger() + logger.addHandler(logging.StreamHandler()) + if '-v' in sys.argv: + logger.setLevel(logging.INFO) + unittest.main(defaultTest='suite') --- /dev/null +++ jcl-0.1b2/src/jcl/jabber/tests/register.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +## +## register.py +## Login : David Rousselie +## Started on Fri Jul 6 21:40:55 2007 David Rousselie +## $Id$ +## +## Copyright (C) 2007 David Rousselie +## This program is free software; you can redistribute it and/or modify +## it under the terms of the GNU General Public License as published by +## the Free Software Foundation; either version 2 of the License, or +## (at your option) any later version. +## +## This program is distributed in the hope that it will be useful, +## but WITHOUT ANY WARRANTY; without even the implied warranty of +## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +## GNU General Public License for more details. +## +## You should have received a copy of the GNU General Public License +## along with this program; if not, write to the Free Software +## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +## + +import unittest + +from pyxmpp.iq import Iq +from pyxmpp.jabber.dataforms import Form + +from jcl.tests import JCLTestCase +from jcl.model.tests.account import ExampleAccount + +from jcl.lang import Lang +from jcl.model.account import User, Account +from jcl.jabber.component import JCLComponent +from jcl.jabber.register import SetRegisterHandler + +class SetRegisterHandler_TestCase(JCLTestCase): + def setUp(self): + JCLTestCase.setUp(self, tables=[User, Account, ExampleAccount]) + self.comp = JCLComponent("jcl.test.com", + "password", + "localhost", + "5347", + self.db_url) + self.handler = SetRegisterHandler(self.comp) + + def test_handle_valid_name(self): + """Test with invalid supplied name""" + iq_set = Iq(stanza_type="set", + from_jid="user1@test.com/res", + to_jid="jcl.test.com") + x_data = Form("submit") + x_data.add_field(name="name", + value="good_name", + field_type="text-single") + result = self.handler.handle(iq_set, Lang.en, None, x_data) + self.assertEquals(result, None) + + def test_handle_invalid_name(self): + """Test with invalid supplied name""" + iq_set = Iq(stanza_type="set", + from_jid="user1@test.com/res", + to_jid="jcl.test.com") + x_data = Form("submit") + x_data.add_field(name="name", + value="wrong@name", + field_type="text-single") + result = self.handler.handle(iq_set, Lang.en, None, x_data) + self.assertEquals(len(result), 1) + self.assertEquals(result[0].xmlnode.prop("type"), "error") + error = result[0].get_error() + self.assertEquals(error.get_condition().name, "not-acceptable") + self.assertEquals(error.get_text(), Lang.en.field_error \ + % ("name", Lang.en.arobase_in_name_forbidden)) + + def test_handle_invalid_empty_name(self): + """Test with empty supplied name""" + iq_set = Iq(stanza_type="set", + from_jid="user1@test.com/res", + to_jid="jcl.test.com") + x_data = Form("submit") + x_data.add_field(name="name", + value="", + field_type="text-single") + result = self.handler.handle(iq_set, Lang.en, None, x_data) + self.assertEquals(len(result), 1) + self.assertEquals(result[0].xmlnode.prop("type"), "error") + error = result[0].get_error() + self.assertEquals(error.get_condition().name, "not-acceptable") + self.assertEquals(error.get_text(), Lang.en.field_error \ + % ("name", Lang.en.mandatory_field)) + +def suite(): + test_suite = unittest.TestSuite() + test_suite.addTest(unittest.makeSuite(SetRegisterHandler_TestCase, 'test')) + return test_suite + +if __name__ == '__main__': + unittest.main(defaultTest='suite')