示例#1
0
 def test_config(self):
     config.set("test_flag", False)
     config.save()
     
     # Get a hash of the file
     with open(config.config_path) as f:
         file_hash = hash(f.read())
     
     # Get a value
     r = config.get("test_flag")
     not_r = not r
     
     # Innit should not override the existing value
     config.init("test_flag", not_r)
     self.assertNotEqual(not_r, config.get("test_flag"))
     
     config.set("test_flag", not_r)
     
     # Ensure everything is still as it was
     with open(config.config_path) as f:
         self.assertEqual(file_hash, hash(f.read()))
     
     # Now try to save it
     config.save()
     
     with open(config.config_path) as f:
         self.assertNotEqual(file_hash, hash(f.read()))
     
     # Now try to set a new property
     config.delete("test_flag2")
     self.assertEqual(config.check("test_flag2"), False)
     
     # Lets set it and then delete it, just to be sure
     config.set("test_flag2", False)
     self.assertEqual(config.check("test_flag2"), True)
     
     # Now save it, it should have a diffrent hash
     config.save()
     with open(config.config_path) as f:
         self.assertNotEqual(file_hash, hash(f.read()))
     
     # Delete the check
     config.delete("test_flag2")
     
     # Check it's all back to how it started
     config.set("test_flag", False)
     config.save()
     with open(config.config_path) as f:
         self.assertEqual(file_hash, hash(f.read()))
示例#2
0
文件: user.py 项目: Teifion/Profiteer
 def _func(cursor, *args, **kwargs):
     response = attempt_login(cursor)
     
     # If it's a string they've failed to login
     if type(response) == str:
         return login_form(response)
     
     # They are logged in, now we need to make sure they have the privilages
     if response.has_privileges(*privileges) != []:
         if response.root:
             return no_access(missing=response.has_privileges(*privileges))
         return no_access()
     
     # Try to get the page itself
     try:
         page_result = f(cursor, *args, **kwargs)
     except Exception as e:
         if common_f.cache['user'].root or False:
             print(error.html_render())
             exit()
         else:
             return error.log_error(cursor, e, context=0)
     
     # Try logging the usage, if not we'll quietly log the error
     try:
         if config.get("log_usage") and common_f.get_val("ajax", False) == False:
             user_log.log_usage(cursor)
     except Exception as e:
         error.log_error(cursor, e)
     
     return page_result
示例#3
0
文件: cli.py 项目: Teifion/Profiteer
def tests(options):
    from profiteer import tests as profiteer_tests
    
    profiteer_tests.setup_test_db()
    
    suite = unittest.TestLoader()
    suite = suite.discover(sys.path[0], pattern="*_test.py")
    
    test_program = unittest.TextTestRunner().run(suite)
    
    if test_program.failures == [] and test_program.errors == []:
        module_skip = ['bpgsql3', 'cli', 'sync', 'tests', 'ploc', 'cli_f']
        dirs_skip = ['checks', 'test_lib', 'prof_site', 'data_lists']
        
        if options.verbose:
            output_mode = "print"
        else:
            output_mode = "summary"
        
        covers.get_coverage(
            suite=suite,
            test_program=test_program,
            root_dir=config.get('file_path'),
            verbose=options.all,
            module_skip = module_skip,
            dirs_skip = dirs_skip,
            output_mode=output_mode)
示例#4
0
文件: cli.py 项目: Teifion/Profiteer
def main():
    if config.get("clean_screen"):
        os.system('clear')
    
    parser = argparse.ArgumentParser(description='Arl command line interface.', prog="arl")
    parser.add_argument('m', help='the mode being run with, list modes with mode set to "list"')
    parser.add_argument('-v', dest="verbose", action="store_true", help='Verbose mode')
    parser.add_argument('-a', dest="all", action="store_true", help='all mode means everything is run', required=False)
    parser.add_argument('-live', dest="live", action="store_true", help='live mode for turns', required=False)
    
    args = parser.parse_args()
    
    # Try the func dict
    if args.m.lower() in func_dict:
        f, info, a, k = func_dict[args.m.lower()]
        
        f(args, *a, **k)
    else:
        if args.m == "":
            exit()
        
        # Standard mode
        try:
            print("No mode of {} found".format(args.m))
            f, info, a, k = func_dict["default"]
            f(args, *a, **k)
        except KeyboardInterrupt:
            exit("Exiting from keyboard interrupt")
示例#5
0
文件: cli.py 项目: Teifion/Profiteer
def install(options):
    from profiteer import sync as sync_module
    
    """Installs the system"""
    
    # Setup database connection
    if config.get('db_username') == "username":
        if config.get('db_password') == "password":
            print(cli_f.shell_text("[y]No database login[/y]"))
            print("""
Access to the database has not yet been setup. Open config.json and fill in
values for db_host, db_username, db_password and db_name.
            
You can optionally also create values for test and mock databases too. These
will allow you to run unit tests involving the database and to trial code
against mock data.

When ready, run this program again.""")
            
            return False
    
    # Test database connection
    try:
        cursor = database_f.get_cursor()
    except Exception:
        print(cli_f.shell_text("[r]Database not accessible[/r]"))
        print("""
The login details for the database are incorrect. Double check the db_host,
db_username, db_password and db_name fields in config.json

When ready, run this program again to retry the connection.""")
        return False
    
    print(cli_f.shell_text("[g]Connected to database[/g]"))
    
    # Install database
    o = sync_module.main(fix=True, show_fixes=False, print_output=False)
    
    # Insert admin
    query = """UPDATE users SET password = '******' WHERE id = 1;""".format(user.encode_password('password', 'K*WJgU&j8M) ZT?=J_T-TUfH9*lY#!>@'))
    try: cursor.execute(query)
    except Exception as e:
        raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query))
    
    print(cli_f.shell_text("[g]Database installed[/g]"))
    
    return True
示例#6
0
文件: user.py 项目: Teifion/Profiteer
def encode_password(password, salt, passes=1):
    if passes > 1:
        password = encode_password(password, salt, passes-1)
    
    passcode = config.get("passcode")
    
    m = md5()
    m.update(passcode.encode("utf-8"))
    m.update(password.encode("utf-8"))
    m.update(salt.encode("utf-8"))
    return m.hexdigest()
示例#7
0
文件: cli.py 项目: Teifion/Profiteer
def replicate(options):
    # First we backup the live one
    file_path = backup(options)
    
    connect_string = "-h {host} -U {user}".format(
        host    = config.get("mock_db_host"),
        user    = config.get("mock_db_username"),
    )
    
    # Now we drop the mock one
    os.system("dropdb {} {}".format(connect_string, config.get("mock_db_name")))
    
    # Create a new one
    os.system("createdb {} {}".format(connect_string, config.get("mock_db_name")))
    
    os.system("psql {conn} -d {db_name} -f {path}".format(
        conn    = connect_string,
        db_name = config.get("mock_db_name"),
        path    = file_path,
    ))
示例#8
0
文件: cli.py 项目: Teifion/Profiteer
def backup(options):
    """Backs up the database"""
    file_path = "{}/backup/{}_{}_{}.sql".format(
        sys.path[0],
        datetime.date.today().day,
        datetime.date.today().month,
        datetime.date.today().year,
    )
    args = "-h {host} -U {user} {db}".format(
        host = config.get("db_host"),
        user = config.get("db_username"),
        db = config.get("db_name")
    )
    
    os.system("/Library/PostgreSQL/bin/pg_dump {} -f {}".format(args, file_path))
    
    if options.verbose:
        print(cli_f.shell_text("[g]Database backed up[/g]"))
    
    return file_path
示例#9
0
文件: web.py 项目: Teifion/Profiteer
def main():
    # Need this so it uses the correct path
    try:
        for k, v in page_dict.items():
            v[1] = v[1].replace("gui/", "{}/gui/".format(sys.path[0]))
    except Exception as e:
        print(error.html_render(context=1))
        raise

    import cgitb

    cgitb.enable(context=1)
    cgitb.html = error.html_render

    # Override the shell patterns to output HTML instead
    cli_f.shell_patterns = cli_f.html_patterns

    # Connect to DB
    cursor = database_f.get_cursor()

    # Default to listing players
    m = common_f.get_val("mode", pages.default_page)
    the_page = import_page(m)

    output = []

    try:
        page_results = the_page.main(cursor)
    except Exception as e:
        print("Content-type: text/html; charset=utf-8")
        print("")
        print(
            "There was an error executing the main function of the_page: %s"
            % str(the_page).replace("<", "&lt;").replace(">", "&gt;")
        )
        print("<br /><br />")

        print(error.log_error(cursor, e, context=0))

        return

    # Is this an AJAX request?
    ajax = bool(common_f.get_val("ajax", False))

    # Redirect
    if page_results == "" and the_page.page_data.get("Redirect", "") != "":
        print("Location: {0}".format(the_page.page_data["Redirect"]))
        print("")
        return

    # Serving content
    print(the_page.page_data.get("Content-type", "Content-type: text/html; charset=utf-8"))
    print(html_f.cookies)
    print("")

    # Import the header/footer
    try:
        find = imp.find_module(the_page.page_data["Template"], ["templates"])
        the_template = imp.load_module("the_template", *find)
        find[0].close()
    except KeyError:
        print(error.html_render(context=1, headers=False))
        exit()

    except Exception:
        try:
            find[0].close()
        except Exception:
            pass

        print(error.html_render(context=1, headers=False))
        print("<br /><br />Found template: {}<br />".format(the_page.page_data["Template"]))
        exit()

    # Headers
    if the_page.page_data.get("Headers", True) and page_results != "" and ajax != True:
        output.append(the_template.headers(cursor, the_page.page_data))

    # Core output
    output.append(page_results)

    the_page.page_data["time"] = time.time() - start_time

    # Footers
    if the_page.page_data.get("Headers", True) and page_results != "" and ajax != True:
        output.append(the_template.footers(cursor, the_page.page_data))

    output = de_unicode("".join([str(i) for i in output]))

    # We now want to print it out, sometimes there can be errors
    # related to unicode
    try:
        print(output)
    except UnicodeEncodeError as e:
        ignore_uni_errror = common_f.get_val("iue", 0)

        from profiteer import config

        try:
            f = open("%sutf8_out.html" % config.get("cache_path"), "w", encoding="utf-8")
            f.write(output)
            f.close()
        except Exception:
            pass

        if ignore_uni_errror:
            _print_ignoring_error(output)

        o = output

        print(
            "Unicode error at character %d, Ignore errors by adding '&iue=1', <a href='http://localhost/profiteer/utf8_out.html'>alternately view raw</a><br />"
            % e.start
        )
        print(
            "%s<strong style='color:red;'>*</strong>%s"
            % (
                o[e.start - 300 : e.start].replace("<", "&lt;").replace(">", "&gt;"),
                o[e.start + 1 : e.start + 20].replace("<", "&lt;").replace(">", "&gt;"),
            )
        )
        print("<br />")
        print(e.start, "<br />")
        print(dir(e))
        exit()
    except Exception as e:
        raise
示例#10
0
#!/usr/bin/env python3

from profiteer import common_f

common_f.cache['test_mode'] = True

from profiteer import database_f, config
from profiteer import sync as sync_module

# Set to test database, just incase something tries to get a new cursor
database_f.dbname   = config.get("test_db_name")

import sys
import unittest

# Data to setup the test database
dummy_data = """INSERT INTO errors ("timestamp", "args", "user_id", "mode", "exception_type", "traceback")
    values
('2010-01-01 20:20:20', 'a=1', 1, 'list_users', 'Exception', 'traceback'),
('2010-01-02 20:20:20', 'a=2', 1, 'list_users', 'Exception', 'traceback'),
('2010-01-03 20:20:20', 'a=3', 1, 'list_users', 'Exception', 'traceback'),
('2010-01-03 20:20:20', 'a=4', 1, 'list_users', 'Exception', 'traceback'),
('2010-01-03 20:20:20', 'a=5', 1, 'list_users', 'Exception', 'traceback');
"""

def setup_test_db():
    cursor = database_f.get_test_cursor()
    
    # Strip it down
    tables = []
    query = """SELECT tablename FROM pg_tables WHERE schemaname = 'public'"""
示例#11
0
文件: cli.py 项目: Teifion/Profiteer
import os
import sys
import argparse
from profiteer import common_f, database_f, cli_f, config, covers, user
from profiteer import sync as sync_module
import datetime

# Padding
padding = "".join([" " for x in range(0, 8*1024)])

# Function dictionary
func_dict = {}

# Sometimes it's nice to have each output start on a clean screen
if __name__ == '__main__':
    if config.get("clean_screen"):
        os.system('clear')

def tests(options):
    from profiteer import tests as profiteer_tests
    
    profiteer_tests.setup_test_db()
    
    suite = unittest.TestLoader()
    suite = suite.discover(sys.path[0], pattern="*_test.py")
    
    test_program = unittest.TextTestRunner().run(suite)
    
    if test_program.failures == [] and test_program.errors == []:
        module_skip = ['bpgsql3', 'cli', 'sync', 'tests', 'ploc', 'cli_f']
        dirs_skip = ['checks', 'test_lib', 'prof_site', 'data_lists']
示例#12
0
def get_test_cursor():
    return get_custom_cursor(username, password, host, config.get('test_db_name'), dictionaries=True)
示例#13
0
from profiteer import config, bpgsql3, cli_f, common_f
import datetime
import re

# Use this to target the mock or production DB
mock_mode = config.get('use_mock_db', False)

alter_default_string = "ALTER TABLE {0} ALTER COLUMN {1} SET DEFAULT '{2}';"
alter_type_string = "ALTER TABLE {0} ALTER COLUMN {1} TYPE {2};"
strip_quotes_re = re.compile(r"(^'|'$)")

try:
    if mock_mode:
        host        = config.get('mock_db_host')
        username    = config.get('mock_db_username')
        password    = config.get('mock_db_password')
        dbname      = config.get('mock_db_name')
    
    else:
        host        = config.get('db_host')
        username    = config.get('db_username')
        password    = config.get('db_password')
        dbname      = config.get('db_name')
    
except KeyError as e:
    # We set all the needed keys to be blank and allow
    # the program to error when making the connection
    
    host        = ""
    username    = ""
    password    = ""