# Path: tiddlywebplugins/tiddlyspace/spaces.py
# def _update_policy(policy, add=None, subtract=None):
#     """
#     Update the policy adding or subtracting the user named in
#     add or subtract.
#     """
#     for constraint in ('read', 'write', 'create', 'delete', 'manage'):
#         constraint_values = getattr(policy, constraint)
#         if add and add not in constraint_values:
#             if constraint == 'read' and constraint_values == []:
#                 pass
#             else:
#                 if 'ANY' in constraint_values or 'NONE' in constraint_values:
#                     raise HTTP409('Policy contains ANY or NONE.')
#                 constraint_values.append(add)
#         if subtract and subtract in constraint_values:
#             constraint_values.remove(subtract)
#     return policy
# 
# def _make_policy(member):
#     """
#     Make a new private policy with the named member.
#     """
#     policy = Policy()
#     policy.owner = member
#     for constraint in ('read', 'write', 'create', 'delete', 'manage'):
#         setattr(policy, constraint, [member])
#     policy.accept = ['NONE']
#     return policy
# 
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
#     """
#     If hsearch is False, don't bother updating the whoosh index
#     for this test instance. We do this by removing the store HOOK
#     used by whoosh.
#     """
#     global SESSION_COUNT
# 
#     # bump up a level if we're already in the test instance
#     if os.getcwd().endswith('test_instance'):
#         os.chdir('..')
# 
#     try:
#         shutil.rmtree('test_instance')
#     except:
#         pass
# 
#     os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
#     if SESSION_COUNT > 1:
#         del sys.modules['tiddlywebplugins.tiddlyspace.store']
#         del sys.modules['tiddlywebplugins.mysql3']
#         del sys.modules['tiddlywebplugins.sqlalchemy3']
#         import tiddlywebplugins.tiddlyspace.store
#         import tiddlywebplugins.mysql3
#         import tiddlywebplugins.sqlalchemy3
#         tiddlywebplugins.mysql3.Session.remove()
#         clear_hooks(HOOKS)
#     SESSION_COUNT += 1
#     db_config = init_config['server_store'][1]['db_config']
#     db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
#     init_config['server_store'][1]['db_config'] = db_config
#     init_config['log_level'] = 'DEBUG'
# 
#     if sys.path[0] != os.getcwd():
#         sys.path.insert(0, os.getcwd())
#     spawn('test_instance', init_config, instance_module)
#     os.chdir('test_instance')
#     os.symlink('../tiddlywebplugins/templates', 'templates')
#     os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
# 
#     from tiddlyweb.web import serve
#     module.store = get_store(init_config)
# 
#     app = serve.load_app()
# 
#     if not hsearch:
#         from tiddlywebplugins.whoosher import _tiddler_change_handler
#         try:
#             HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
#             HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
#         except ValueError:
#             pass
# 
#     def app_fn():
#         return app
#     module.app_fn = app_fn
# 
# def make_fake_space(store, name):
#     """
#     Call the spaces api to create a space.
#     """
#     make_space(name, store, name)
# 
# def get_auth(username, password):
#     http = httplib2.Http()
#     response, _ = http.request(
#             'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form',
#             body='user=%s&password=%s' % (username, password),
#             method='POST',
#             headers={'Content-Type': 'application/x-www-form-urlencoded'})
#     assert response.previous['status'] == '303'
# 
#     user_cookie = response.previous['set-cookie']
#     cookie = Cookie.SimpleCookie()
#     cookie.load(user_cookie)
#     return cookie['tiddlyweb_user'].value


import simplejson
import httplib2
import wsgi_intercept
import py.test
from wsgi_intercept import httplib2_intercept
from httpexceptor import HTTP409
from tiddlyweb.model.bag import Bag
from tiddlyweb.model.recipe import Recipe
from tiddlyweb.model.user import User
from tiddlywebplugins.tiddlyspace.spaces import _update_policy, _make_policy
from test.fixtures import make_test_env, make_fake_space, get_auth
    from tiddlyweb.config import config
    wsgi_intercept.add_wsgi_intercept('extra.0.0.0.0', 8080, app_fn)
    make_fake_space(module.store, 'cdent')
    user = User('cdent')
    user.set_password('cow')
    module.store.put(user)
    user = User('fnd')
    user.set_password('bird')
    module.store.put(user)
    user = User('psd')
    user.set_password('cat')
    module.store.put(user)


def test_spaces_list():
    http = httplib2.Http()
    response, content = http.request('http://0.0.0.0:8080/spaces',
            method='GET')
    assert response['status'] == '200'
    assert response['cache-control'] == 'no-cache, no-transform'

    info = simplejson.loads(content)
    uris = [uri for _, uri in [item.values() for item in info]]
    names = [name for name, _ in [item.values() for item in info]]
    expected_uris = ['http://0.0.0.0:8080/', 'http://cdent.0.0.0.0:8080/']
    expected_uris.extend(SYSTEM_URLS)
    expected_names = ['cdent', 'frontpage']
    expected_names.extend(SYSTEM_SPACES)
    assert sorted(uris) == sorted(expected_uris)
    assert sorted(names) == sorted(expected_names)


# Path: tiddlywebplugins/tiddlyspace/spaces.py
# def _update_policy(policy, add=None, subtract=None):
#     """
#     Update the policy adding or subtracting the user named in
#     add or subtract.
#     """
#     for constraint in ('read', 'write', 'create', 'delete', 'manage'):
#         constraint_values = getattr(policy, constraint)
#         if add and add not in constraint_values:
#             if constraint == 'read' and constraint_values == []:
#                 pass
#             else:
#                 if 'ANY' in constraint_values or 'NONE' in constraint_values:
#                     raise HTTP409('Policy contains ANY or NONE.')
#                 constraint_values.append(add)
#         if subtract and subtract in constraint_values:
#             constraint_values.remove(subtract)
#     return policy
# 
# def _make_policy(member):
#     """
#     Make a new private policy with the named member.
#     """
#     policy = Policy()
#     policy.owner = member
#     for constraint in ('read', 'write', 'create', 'delete', 'manage'):
#         setattr(policy, constraint, [member])
#     policy.accept = ['NONE']
#     return policy
# 
# Path: test/fixtures.py
# def make_test_env(module, hsearch=False):
#     """
#     If hsearch is False, don't bother updating the whoosh index
#     for this test instance. We do this by removing the store HOOK
#     used by whoosh.
#     """
#     global SESSION_COUNT
# 
#     # bump up a level if we're already in the test instance
#     if os.getcwd().endswith('test_instance'):
#         os.chdir('..')
# 
#     try:
#         shutil.rmtree('test_instance')
#     except:
#         pass
# 
#     os.system('echo "drop database if exists tiddlyspacetest; create database tiddlyspacetest character set = utf8mb4 collate = utf8mb4_bin;" | mysql')
#     if SESSION_COUNT > 1:
#         del sys.modules['tiddlywebplugins.tiddlyspace.store']
#         del sys.modules['tiddlywebplugins.mysql3']
#         del sys.modules['tiddlywebplugins.sqlalchemy3']
#         import tiddlywebplugins.tiddlyspace.store
#         import tiddlywebplugins.mysql3
#         import tiddlywebplugins.sqlalchemy3
#         tiddlywebplugins.mysql3.Session.remove()
#         clear_hooks(HOOKS)
#     SESSION_COUNT += 1
#     db_config = init_config['server_store'][1]['db_config']
#     db_config = db_config.replace('///tiddlyspace?', '///tiddlyspacetest?')
#     init_config['server_store'][1]['db_config'] = db_config
#     init_config['log_level'] = 'DEBUG'
# 
#     if sys.path[0] != os.getcwd():
#         sys.path.insert(0, os.getcwd())
#     spawn('test_instance', init_config, instance_module)
#     os.chdir('test_instance')
#     os.symlink('../tiddlywebplugins/templates', 'templates')
#     os.symlink('../tiddlywebplugins', 'tiddlywebplugins')
# 
#     from tiddlyweb.web import serve
#     module.store = get_store(init_config)
# 
#     app = serve.load_app()
# 
#     if not hsearch:
#         from tiddlywebplugins.whoosher import _tiddler_change_handler
#         try:
#             HOOKS['tiddler']['put'].remove(_tiddler_change_handler)
#             HOOKS['tiddler']['delete'].remove(_tiddler_change_handler)
#         except ValueError:
#             pass
# 
#     def app_fn():
#         return app
#     module.app_fn = app_fn
# 
# def make_fake_space(store, name):
#     """
#     Call the spaces api to create a space.
#     """
#     make_space(name, store, name)
# 
# def get_auth(username, password):
#     http = httplib2.Http()
#     response, _ = http.request(
#             'http://0.0.0.0:8080/challenge/tiddlywebplugins.tiddlyspace.cookie_form',
#             body='user=%s&password=%s' % (username, password),
#             method='POST',
#             headers={'Content-Type': 'application/x-www-form-urlencoded'})
#     assert response.previous['status'] == '303'
# 
#     user_cookie = response.previous['set-cookie']
#     cookie = Cookie.SimpleCookie()
#     cookie.load(user_cookie)
#     return cookie['tiddlyweb_user'].value


# Path: test/test_space_handler.py
import simplejson
import httplib2
import wsgi_intercept
import py.test
from wsgi_intercept import httplib2_intercept
from httpexceptor import HTTP409
from tiddlyweb.model.bag import Bag
from tiddlyweb.model.recipe import Recipe
from tiddlyweb.model.user import User
from tiddlywebplugins.tiddlyspace.spaces import _update_policy, _make_policy
from test.fixtures import make_test_env, make_fake_space, get_auth
    from tiddlyweb.config import config

    wsgi_intercept.add_wsgi_intercept('extra.0.0.0.0', 8080, app_fn)
    make_fake_space(module.store, 'cdent')
    user = User('cdent')
    user.set_password('cow')
    module.store.put(user)
    user = User('fnd')
    user.set_password('bird')
    module.store.put(user)
    user = User('psd')
    user.set_password('cat')
    module.store.put(user)


def test_spaces_list():
    http = httplib2.Http()
    response, content = http.request('http://0.0.0.0:8080/spaces',
            method='GET')
    assert response['status'] == '200'
    assert response['cache-control'] == 'no-cache, no-transform'

    info = simplejson.loads(content)
    uris = [uri for _, uri in [item.values() for item in info]]
    names = [name for name, _ in [item.values() for item in info]]
    expected_uris = ['http://0.0.0.0:8080/', 'http://cdent.0.0.0.0:8080/']
    expected_uris.extend(SYSTEM_URLS)
    expected_names = ['cdent', 'frontpage']
    expected_names.extend(SYSTEM_SPACES)
    assert sorted(uris) == sorted(expected_uris)
    assert sorted(names) == sorted(expected_names)


    make_fake_space(store, 'fnd')