Commits

Sebastian  committed 608b269

reformat code (spaces etc.)

  • Participants
  • Parent commits b48d010

Comments (0)

Files changed (6)

File sievelib/commands.py

 import sys
 from collections import Iterable
 
+
 class UnknownCommand(Exception):
     """Specific exception raised when an unknown command is encountered"""
+
     def __init__(self, name):
         self.name = name
 
     def __str__(self):
         return "unknown command %s" % self.name
 
+
 class BadArgument(Exception):
     """Specific exception raised when a bad argument is encountered"""
+
     def __init__(self, command, seen, expected):
         self.command = command
         self.seen = seen
 
     def __str__(self):
         return "bad argument %s for command %s (%s expected)" \
-            % (self.seen, self.command, self.expected)
+               % (self.seen, self.command, self.expected)
+
 
 class BadValue(Exception):
     """Specific exception raised when a bad argument value is encountered"""
+
     def __init__(self, argument, value):
         self.argument = argument
         self.value = value
 
     def __str__(self):
         return "bad value %s for argument %s" \
-            % (self.value, self.argument)
+               % (self.value, self.argument)
 
 
 # Statement elements (see RFC, section 8.3)
 # They are used in different commands.
-comparator = {"name" : "comparator",
-              "type" : ["tag"],
-              "values" : [":comparator"],
-              "extra_arg" : {"type" : "string",
-                             "values" : ['"i;octet"', '"i;ascii-casemap"']},
-              "required" : False}
-address_part = {"name" : "address-part",
-                "values" : [":localpart", ":domain", ":all"],
-                "type" : ["tag"],
-                "required" : False}
-match_type = {"name" : "match-type",
-              "values" : [":is", ":contains", ":matches"],
-              "type" : ["tag"],
-              "required" : False}
+comparator = {"name": "comparator",
+              "type": ["tag"],
+              "values": [":comparator"],
+              "extra_arg": {"type": "string",
+                            "values": ['"i;octet"', '"i;ascii-casemap"']},
+              "required": False}
+address_part = {"name": "address-part",
+                "values": [":localpart", ":domain", ":all"],
+                "type": ["tag"],
+                "required": False}
+match_type = {"name": "match-type",
+              "values": [":is", ":contains", ":matches"],
+              "type": ["tag"],
+              "required": False}
+
 
 class Command(object):
     """Generic command representation.
 
         if not self.accept_children:
             if self.get_type() != "test":
-                print >>target, ";"
+                print >> target, ";"
             return
         if self.get_type() != "control":
             return
-        print >>target, " {"
+        print >> target, " {"
         for ch in self.children:
             ch.tosieve(indentlevel + 4, target=target)
         self.__print("}", indentlevel, target=target)
         if nocr:
             target.write(text)
         else:
-            print >>target, text
+            print >> target, text
 
     def __get_arg_type(self, arg):
         """Return the type corresponding to the given name.
                 if arg["required"]:
                     self.required_args += 1
         return (not self.curarg or not "extra_arg" in self.curarg) \
-                           and (self.rargs_cnt == self.required_args)
+            and (self.rargs_cnt == self.required_args)
 
     def get_type(self):
         """Return the command's type"""
         if self.curarg is not None and "extra_arg" in self.curarg:
             if atype == self.curarg["extra_arg"]["type"]:
                 if not self.curarg["extra_arg"].has_key("values") or \
-                        avalue in self.curarg["extra_arg"]["values"]:
+                                avalue in self.curarg["extra_arg"]["values"]:
                     if add:
                         self.arguments[self.curarg["name"]] = avalue
                     self.curarg = None
             pos += 1
 
         if failed:
-            raise BadArgument(self.name, avalue, 
+            raise BadArgument(self.name, avalue,
                               self.args_definition[pos]["type"])
         return True
 
             raise KeyError(name)
         return self.arguments[name]
 
+
 class ControlCommand(Command):
     """Indermediate class to represent "control" commands"""
     _type = "control"
-    
+
+
 class RequireCommand(ControlCommand):
     """The 'require' command
 
     unloaded extensions during the parsing)
     """
     args_definition = [
-        {"name" : "capabilities",
-         "type" : ["string", "stringlist"],
-         "required" : True}
-        ]
+        {"name": "capabilities",
+         "type": ["string", "stringlist"],
+         "required": True}
+    ]
 
     loaded_extensions = []
 
             if not ext in RequireCommand.loaded_extensions:
                 RequireCommand.loaded_extensions += [ext]
 
+
 class StopCommand(ControlCommand):
     args_definition = []
 
+
 class IfCommand(ControlCommand):
     accept_children = True
 
     args_definition = [
-        {"name" : "test",
-         "type" : ["test"],
-         "required" : True}
-        ]
+        {"name": "test",
+         "type": ["test"],
+         "required": True}
+    ]
 
     def get_expected_first(self):
         return ["identifier"]
 
+
 class ElsifCommand(ControlCommand):
     accept_children = True
     must_follow = ["if", "elsif"]
     args_definition = [
-        {"name" : "test",
-         "type" : ["test"],
-         "required" : True}
-        ]
+        {"name": "test",
+         "type": ["test"],
+         "required": True}
+    ]
 
     def get_expected_first(self):
         return ["identifier"]
 
+
 class ElseCommand(ControlCommand):
     accept_children = True
     must_follow = ["if", "elsif"]
     args_definition = []
 
+
 class ActionCommand(Command):
     """Indermediate class to represent "action" commands"""
     _type = "action"
 
+
 class FileintoCommand(ActionCommand):
     is_extension = True
     args_definition = [
-        {"name" : "mailbox",
-         "type" : ["string"],
-         "required" : True}
-        ]
+        {"name": "mailbox",
+         "type": ["string"],
+         "required": True}
+    ]
+
 
 class RedirectCommand(ActionCommand):
     args_definition = [
-        {"name" : "address",
-         "type" : ["string"],
-         "required" : True}
-        ]
+        {"name": "address",
+         "type": ["string"],
+         "required": True}
+    ]
+
 
 class RejectCommand(ActionCommand):
     is_extension = True
     args_definition = [
-        {"name" : "text",
-         "type" : ["string"],
-         "required" : True}
-        ]
+        {"name": "text",
+         "type": ["string"],
+         "required": True}
+    ]
+
 
 class KeepCommand(ActionCommand):
     args_definition = []
 
+
 class DiscardCommand(ActionCommand):
     args_definition = []
 
+
 class TestCommand(Command):
     """Indermediate class to represent "test" commands"""
     _type = "test"
 
+
 class AddressCommand(TestCommand):
     args_definition = [
         comparator,
         address_part,
         match_type,
-        {"name" : "header-list",
-         "type" : ["string", "stringlist"],
-         "required" : True},
-        {"name" : "key-list",
-         "type" : ["string", "stringlist"],
-         "required" : True}
-        ]
+        {"name": "header-list",
+         "type": ["string", "stringlist"],
+         "required": True},
+        {"name": "key-list",
+         "type": ["string", "stringlist"],
+         "required": True}
+    ]
+
 
 class AllofCommand(TestCommand):
     accept_children = True
     variable_args_nb = True
 
     args_definition = [
-        {"name" : "tests",
-         "type" : ["testlist"],
-         "required" : True}
-        ]
+        {"name": "tests",
+         "type": ["testlist"],
+         "required": True}
+    ]
 
     def get_expected_first(self):
         return ["left_parenthesis"]
 
+
 class AnyofCommand(TestCommand):
     accept_children = True
     variable_args_nb = True
 
     args_definition = [
-        {"name" : "tests",
-         "type" : ["testlist"],
-         "required" : True}
-        ]
+        {"name": "tests",
+         "type": ["testlist"],
+         "required": True}
+    ]
 
     def get_expected_first(self):
         return ["left_parenthesis"]
 
+
 class EnvelopeCommand(TestCommand):
     args_definition = [
         comparator,
         address_part,
         match_type,
-        {"name" : "header-list",
-         "type" : ["string", "stringlist"],
-         "required" : True},
-        {"name" : "key-list",
-         "type" : ["string", "stringlist"],
-         "required" : True}
-        ]
+        {"name": "header-list",
+         "type": ["string", "stringlist"],
+         "required": True},
+        {"name": "key-list",
+         "type": ["string", "stringlist"],
+         "required": True}
+    ]
+
 
 class ExistsCommand(TestCommand):
     args_definition = [
-        {"name" : "header-names",
-         "type" : ["stringlist"],
-         "required" : True}
-        ]
+        {"name": "header-names",
+         "type": ["stringlist"],
+         "required": True}
+    ]
+
 
 class TrueCommand(TestCommand):
     args_definition = []
 
+
 class FalseCommand(TestCommand):
     args_definition = []
 
+
 class HeaderCommand(TestCommand):
     args_definition = [
         comparator,
         match_type,
-        {"name" : "header-names",
-         "type" : ["string", "stringlist"],
-         "required" : True},
-        {"name" : "key-list",
-         "type" : ["string", "stringlist"],
-         "required" : True}
-        ]
+        {"name": "header-names",
+         "type": ["string", "stringlist"],
+         "required": True},
+        {"name": "key-list",
+         "type": ["string", "stringlist"],
+         "required": True}
+    ]
+
 
 class NotCommand(TestCommand):
     accept_children = True
 
     args_definition = [
-        {"name" : "test",
-         "type" : ["test"],
-         "required" : True}
-        ]
+        {"name": "test",
+         "type": ["test"],
+         "required": True}
+    ]
 
     def get_expected_first(self):
         return ["identifier"]
 
+
 class SizeCommand(TestCommand):
     args_definition = [
-        {"name" : "comparator",
-         "type" : ["tag"],
-         "values" : [":over", ":under"],
-         "required" : True},
-        {"name" : "limit",
-         "type" : ["number"],
-         "required" : True},
-        ]
+        {"name": "comparator",
+         "type": ["tag"],
+         "values": [":over", ":under"],
+         "required": True},
+        {"name": "limit",
+         "type": ["number"],
+         "required": True},
+    ]
+
 
 class VacationCommand(ActionCommand):
     args_definition = [
-        {"name" : "subject",
-          "type" : ["tag"],
-          "write_tag": True,
-          "values" : [":subject"],
-          "extra_arg" : {"type" : "string"},
-          "required" : False},
-        {"name" : "days",
-          "type" : ["tag"],
-          "write_tag": True,
-          "values" : [":days"],
-          "extra_arg" : {"type" : "number"},
-          "required" : False},
-        {"name" : "from",
-          "type" : ["tag"],
-          "write_tag": True,
-          "values" : [":from"],
-          "extra_arg" : {"type" : "string"},
-          "required" : False},
-        {"name" : "addresses",
-          "type" : ["tag"],
-          "write_tag": True,
-          "values" : [":addresses"],
-          "extra_arg" : {"type" : "stringlist"},
-          "required" : False},
-        {"name" : "handle",
-          "type" : ["tag"],
-          "write_tag": True,
-          "values" : [":handle"],
-          "extra_arg" : {"type" : "string"},
-          "required" : False},
-        {"name" : "mime",
-          "type" : ["tag"],
-          "write_tag": True,
-          "values" : [":mime"],
-          "required" : False},
-        {"name" : "reason",
-         "type" : ["string"],
-         "required" : True},
-        ]
+        {"name": "subject",
+         "type": ["tag"],
+         "write_tag": True,
+         "values": [":subject"],
+         "extra_arg": {"type": "string"},
+         "required": False},
+        {"name": "days",
+         "type": ["tag"],
+         "write_tag": True,
+         "values": [":days"],
+         "extra_arg": {"type": "number"},
+         "required": False},
+        {"name": "from",
+         "type": ["tag"],
+         "write_tag": True,
+         "values": [":from"],
+         "extra_arg": {"type": "string"},
+         "required": False},
+        {"name": "addresses",
+         "type": ["tag"],
+         "write_tag": True,
+         "values": [":addresses"],
+         "extra_arg": {"type": "stringlist"},
+         "required": False},
+        {"name": "handle",
+         "type": ["tag"],
+         "write_tag": True,
+         "values": [":handle"],
+         "extra_arg": {"type": "string"},
+         "required": False},
+        {"name": "mime",
+         "type": ["tag"],
+         "write_tag": True,
+         "values": [":mime"],
+         "required": False},
+        {"name": "reason",
+         "type": ["string"],
+         "required": True},
+    ]
 
-def add_commands(cmds, name = None):
+
+def add_commands(cmds, name=None):
+    """
+    Adds one or more commands to the module namespace.
+    Commands must end in "Command" to be added.
+    Example (see tests/parser.py):
+    sievelib.commands.add_commands(MytestCommand)
+
+    :param cmds: a single Command Object or list of Command Objects
+    :param name: optional parameter under which to insert the Command
+    """
     if not isinstance(cmds, Iterable):
         cmds = [cmds]
 
         if command.__name__.endswith("Command"):
             globals()[command.__name__] = command
 
+
 def get_command_instance(name, parent=None, checkexists=True):
     """Try to guess and create the appropriate command instance
 

File sievelib/digest_md5.py

 import re
 import random
 
+
 class DigestMD5(object):
     def __init__(self, challenge, digesturi):
         self.__digesturi = digesturi
             self.__params[m.group(1)] = m.group(2)
 
     def __make_cnonce(self):
-	ret = ""
-	for i in xrange(12):
+        ret = ""
+        for i in xrange(12):
             ret += chr(random.randint(0, 0xff))
         return base64.b64encode(ret)
 
         return binascii.hexlify(hashlib.md5(value).digest())
 
     def __make_response(self, username, password, check=False):
-        a1 = "%s:%s:%s" % (self.__digest("%s:%s:%s" % (username, self.realm, password)), 
+        a1 = "%s:%s:%s" % (self.__digest("%s:%s:%s" % (username, self.realm, password)),
                            self.__params["nonce"], self.cnonce)
         if check:
             a2 = ":%s" % self.__digesturi
         else:
             a2 = "AUTHENTICATE:%s" % self.__digesturi
         resp = "%s:%s:00000001:%s:auth:%s" \
-            % (self.__hexdigest(a1), self.__params["nonce"],
-               self.cnonce, self.__hexdigest(a2))
+               % (self.__hexdigest(a1), self.__params["nonce"],
+                  self.cnonce, self.__hexdigest(a2))
 
         return self.__hexdigest(resp)
 
         respvalue = self.__make_response(username, password)
 
         dgres = 'username="%s",%snonce="%s",cnonce="%s",nc=00000001,qop=auth,' \
-            'digest-uri="%s",response=%s' \
-            % (username, ('realm="%s",' % self.realm) if len(self.realm) else "", 
-               self.__params["nonce"], self.cnonce, self.__digesturi, respvalue)
+                'digest-uri="%s",response=%s' \
+                % (username, ('realm="%s",' % self.realm) if len(self.realm) else "",
+                   self.__params["nonce"], self.cnonce, self.__digesturi, respvalue)
 
         return base64.b64encode(dgres)
 
     def check_last_challenge(self, username, password, value):
         challenge = base64.b64decode(value.strip('"'))
         return challenge == \
-            ("rspauth=%s" % self.__make_response(username, password, True))
+               ("rspauth=%s" % self.__make_response(username, password, True))
         

File sievelib/factory.py

 import cStringIO
 from commands import *
 
+
 class FiltersSet(object):
     def __init__(self, name, filter_name_pretext="# Filter:", filter_desc_pretext="# Description:"):
         """Represents a set of one or more filters
         :param matchtype: "anyof" or "allof"
         """
         ifcontrol = self.__create_filter(conditions, actions, matchtype)
-        self.filters += [{"name" : name, "content" : ifcontrol, "enabled" : True}]
+        self.filters += [{"name": name, "content": ifcontrol, "enabled": True}]
 
     def updatefilter(self, oldname, newname, conditions, actions, matchtype="anyof"):
         """Update a specific filter
             cmd.tosieve(target=target)
             target.write("\n")
         for f in self.filters:
-            print >>target, self.filter_name_pretext + f["name"]
+            print >> target, self.filter_name_pretext + f["name"]
             if len(f["description"]) > 0:
-                print >>target, self.filter_desc_pretext + f["description"]
+                print >> target, self.filter_desc_pretext + f["description"]
             f["content"].tosieve(target=target)
-        
-    
+
+
 if __name__ == "__main__":
     fs = FiltersSet("test")
-    
-    fs.addfilter("rule1", 
-                 [("Sender", ":is", "toto@toto.com"),],
-                 [("fileinto", "Toto"),])
+
+    fs.addfilter("rule1",
+                 [("Sender", ":is", "toto@toto.com"), ],
+                 [("fileinto", "Toto"), ])
     fs.tosieve()
     

File sievelib/managesieve.py

 Implementation based on <draft-martin-managesieve-12>.
 """
 
-import sys, os
 import socket
 import re
 import base64
 
 CRLF = '\r\n'
 
-KNOWN_CAPABILITIES = ["IMPLEMENTATION", "SASL", "SIEVE", 
+KNOWN_CAPABILITIES = ["IMPLEMENTATION", "SASL", "SIEVE",
                       "STARTTLS", "NOTIFY", "LANGUAGE",
                       "RENAME"]
 
 SUPPORTED_AUTH_MECHS = ["DIGEST-MD5", "PLAIN", "LOGIN"]
 
+
 class Error(Exception):
     pass
 
+
 class Response(Exception):
     def __init__(self, code, data):
         self.code = code
     def __str__(self):
         return "%s %s" % (self.code, self.data)
 
+
 class Literal(Exception):
     def __init__(self, value):
         self.value = value
     def __str__(self):
         return "{%d}" % self.value
 
+
 def authentication_required(meth):
     """Simple class method decorator.
 
 
     :param meth: the original called method
     """
+
     def check(cls, *args, **kwargs):
         if cls.authenticated:
             return meth(cls, *args, **kwargs)
         raise Error("Authentication required")
+
     return check
 
+
 class Client(object):
     read_size = 4096
     read_timeout = 5
             try:
                 pos = self.__read_buffer.index(CRLF)
                 ret = self.__read_buffer[0:pos]
-                self.__read_buffer = self.__read_buffer[pos+len(CRLF):]
+                self.__read_buffer = self.__read_buffer[pos + len(CRLF):]
                 break
             except ValueError:
                 pass
                 break
 
         return (code, data, resp)
-    
+
     def __prepare_args(self, args):
         """Format command arguments before sending them.
 
         if withcontent:
             return (code, data, content)
         return (code, data)
-  
+
     def __get_capabilities(self):
         code, data, capabilities = self.__read_response()
         if code == "NO":
         :param password: clear password
         :return: True on success, False otherwise.
         """
-        extralines = ['"%s"' % base64.b64encode(login), 
+        extralines = ['"%s"' % base64.b64encode(login),
                       '"%s"' % base64.b64encode(password)]
-        code, data = self.__send_command("AUTHENTICATE", ["LOGIN"], 
+        code, data = self.__send_command("AUTHENTICATE", ["LOGIN"],
                                          extralines=extralines)
         if code == "OK":
             return True
         :return: True on success, False otherwise.
         """
         code, data, challenge = \
-            self.__send_command("AUTHENTICATE", ["DIGEST-MD5"], 
+            self.__send_command("AUTHENTICATE", ["DIGEST-MD5"],
                                 withcontent=True, nblines=1)
         dmd5 = DigestMD5(challenge, "sieve/%s" % self.srvaddr)
-        
+
         code, data, challenge = \
             self.__send_command('"%s"' % dmd5.response(login, password),
                                 withcontent=True, nblines=1)
         if code == "OK":
             return True
         return False
-        
+
     def __authenticate(self, login, password, authmech=None):
         """AUTHENTICATE command
 
                 self.authenticated = True
                 return True
             return False
-        
+
         self.errmsg = "No suitable mechanism found"
         return False
 
             self.sock.settimeout(Client.read_timeout)
         except socket.error, msg:
             raise Error("Connection to server failed: %s" % str(msg))
-        
+
         if not self.__get_capabilities():
             raise Error("Failed to read capabilities from server")
         if starttls and not self.__starttls():
         """
         code, data = self.__send_command("SETACTIVE", [scriptname])
         if code == "OK":
-            return True        
+            return True
         return False
 

File sievelib/parser.py

 
 from commands import get_command_instance, UnknownCommand, BadArgument, BadValue
 
+
 class ParseError(Exception):
     """Generic parsing error"""
+
     def __init__(self, msg):
         self.msg = msg
 
     def __str__(self):
         return "parsing error: %s" % self.msg
 
+
 class Lexer(object):
     """
     The lexical analysis part. 
     
       [("left_bracket", r'\['),]
     """
+
     def __init__(self, definitions):
         self.definitions = definitions
         parts = []
             self.pos = m.end()
             yield (m.lastgroup, m.group(m.lastgroup))
 
+
 class Parser(object):
     """The grammatical analysis part.
 
         ("identifier", r'[a-zA-Z_][\w]*'),
         ("tag", r':[a-zA-Z_][\w]*'),
         ("number", r'[0-9]+[KMGkmg]?'),
-        ]
+    ]
 
     def __init__(self, debug=False):
         self.debug = debug
                     if len(self.__curcommand.parent.children) >= 2 else None
             if prevcmd is None or prevcmd.name not in self.__curcommand.must_follow:
                 raise ParseError("the %s command must follow an %s command" % \
-                                     (self.__curcommand.name,
-                                      " or ".join(self.__curcommand.must_follow)))
+                                 (self.__curcommand.name,
+                                  " or ".join(self.__curcommand.must_follow)))
 
         if not self.__curcommand.parent:
             #collect current amount of hash comments for later parsing into names and desciptions
             if command.get_type() == "test":
                 raise ParseError("%s may not appear as a first command" % command.name)
             if command.get_type() == "control" and command.accept_children \
-                    and command.has_arguments():
+                and command.has_arguments():
                 self.__set_expected("identifier")
             if self.__curcommand is not None:
                 if not self.__curcommand.addchild(command):
                     raise ParseError("%s unexpected after a %s" % \
-                                         (tvalue, self.__curcommand.name))
+                                     (tvalue, self.__curcommand.name))
             self.__curcommand = command
             self.__cstate = self.__arguments
 
                     if not ttype in self.__expected:
                         if self.lexer.pos < len(text):
                             msg = "%s found while %s expected near '%s'" \
-                                % (ttype, "|".join(self.__expected), text[self.lexer.pos])
+                                  % (ttype, "|".join(self.__expected), text[self.lexer.pos])
                         else:
                             msg = "%s found while %s expected at end of file" \
-                                % (ttype, "|".join(self.__expected))
+                                  % (ttype, "|".join(self.__expected))
                         raise ParseError(msg)
                     self.__expected = None
-                    
+
                 if not self.__command(ttype, tvalue):
                     msg = "unexpected token '%s' found near '%s'" \
-                        % (tvalue, text[self.lexer.pos])
+                          % (tvalue, text[self.lexer.pos])
                     raise ParseError(msg)
             if self.__opened_blocks:
                 self.__set_expected("right_cbracket")
             if self.__expected is not None:
                 raise ParseError("end of script reached while %s expected" % \
-                                     "|".join(self.__expected))
+                                 "|".join(self.__expected))
 
         except (ParseError, UnknownCommand, BadArgument, BadValue), e:
             self.error = "line %d: %s" % (self.lexer.curlineno(), str(e))
         for r in self.result:
             r.dump(target=target)
 
+
 if __name__ == "__main__":
     from optparse import OptionParser
 

File sievelib/tests/parser.py

 """
 Unit tests for the SIEVE language parser.
 """
-from sievelib.parser import Parser
-from sievelib.factory import FiltersSet
-import sievelib.commands
 import unittest
 import cStringIO
 import StringIO
 import os.path
 import codecs
 
+from sievelib.parser import Parser
+from sievelib.factory import FiltersSet
+import sievelib.commands
+
 
 class MytestCommand(sievelib.commands.ActionCommand):
     args_definition = [
-        {"name" : "testtag",
-         "type" : ["tag"],
+        {"name": "testtag",
+         "type": ["tag"],
          "write_tag": True,
-         "values" : [":testtag"],
-         "extra_arg" : {"type" : "number",
-                        "required": False},
-         "required" : False},
-        {"name" : "recipients",
-         "type" : ["string", "stringlist"],
-         "required" : True}
+         "values": [":testtag"],
+         "extra_arg": {"type": "number",
+                       "required": False},
+         "required": False},
+        {"name": "recipients",
+         "type": ["string", "stringlist"],
+         "required": True}
     ]
 
 
          "required": True}
     ]
 
+
 class SieveTest(unittest.TestCase):
     def setUp(self):
         self.parser = Parser()
 
 
 class AdditionalCommands(SieveTest):
-
     def test_add_command(self):
         self.assertRaises(sievelib.commands.UnknownCommand, sievelib.commands.get_command_instance, 'mytest')
         sievelib.commands.add_commands(MytestCommand)
 
 
 class ValidEncodings(SieveTest):
-
     def test_utf8_file(self):
-        utf8_sieve = os.path.join(os.path.dirname(__file__),'files', 'utf8_sieve.txt')
-        source_sieve = codecs.open(utf8_sieve,encoding='utf8').read()
+        utf8_sieve = os.path.join(os.path.dirname(__file__), 'files', 'utf8_sieve.txt')
+        source_sieve = codecs.open(utf8_sieve, encoding='utf8').read()
         self.parser.parse_file(utf8_sieve)
         self.sieve_is(source_sieve)
 
 
 class ValidSyntaxes(SieveTest):
-
     def test_hash_comment(self):
         self.compilation_ok("""
 if size :over 100k { # this is a comment
         100K
     discard (type: action)
 """)
-        
+
     def test_string_with_bracket_comment(self):
         self.compilation_ok("""
 if header :contains "Cc" "/* comment */" {
 }
 """)
 
+
 class InvalidSyntaxes(SieveTest):
-
     def test_nested_comments(self):
         self.compilation_ko("""
 /* this is a comment /* with a nested comment inside */
 }
 """)
 
+
 class LanguageRestrictions(SieveTest):
-
     def test_unknown_control(self):
         self.compilation_ko("""
 macommande "Toto";
 
     def test_test_outside_control(self):
         self.compilation_ko("true;")
-                            
+
+
 if __name__ == "__main__":
     unittest.main()