# 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

GET /spaces: list all spaces
GET /spaces/{space_name}: 204 if exist
GET /spaces/{space_name}/members: list all members
PUT /spaces/{space_name}: create a space
PUT /spaces/{space_name}/members/{member_name}: add a member
DELETE /spaces/{space_name}/members/{member_name}: remove a member
POST /spaces/{space_name}: Handle subscription, the data package is
  JSON as {"subscriptions": ["space1", "space2", "space3"]}
"""






SYSTEM_SPACES = ['system-plugins', 'system-info', 'system-images',
    'system-theme', 'system-applications']
SYSTEM_URLS = ['http://system-plugins.0.0.0.0:8080/',
    'http://system-info.0.0.0.0:8080/', 'http://system-applications.0.0.0.0:8080/',
    'http://system-images.0.0.0.0:8080/', 'http://system-theme.0.0.0.0:8080/']


def setup_module(module):
    make_test_env(module)
    httplib2_intercept.install()
    config['blacklisted_spaces'] = ['scrappy']
    wsgi_intercept.add_wsgi_intercept('0.0.0.0', 8080, app_fn)
    wsgi_intercept.add_wsgi_intercept('cdent.0.0.0.0', 8080, app_fn)
    wsgi_intercept.add_wsgi_intercept('extra.0.0.0.0', 8080, app_fn)

# 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


GET /spaces: list all spaces
GET /spaces/{space_name}: 204 if exist
GET /spaces/{space_name}/members: list all members
PUT /spaces/{space_name}: create a space
PUT /spaces/{space_name}/members/{member_name}: add a member
DELETE /spaces/{space_name}/members/{member_name}: remove a member
POST /spaces/{space_name}: Handle subscription, the data package is
  JSON as {"subscriptions": ["space1", "space2", "space3"]}
"""






SYSTEM_SPACES = ['system-plugins', 'system-info', 'system-images',
    'system-theme', 'system-applications']
SYSTEM_URLS = ['http://system-plugins.0.0.0.0:8080/',
    'http://system-info.0.0.0.0:8080/', 'http://system-applications.0.0.0.0:8080/',
    'http://system-images.0.0.0.0:8080/', 'http://system-theme.0.0.0.0:8080/']


def setup_module(module):
    make_test_env(module)
    httplib2_intercept.install()
    config['blacklisted_spaces'] = ['scrappy']
    wsgi_intercept.add_wsgi_intercept('0.0.0.0', 8080, app_fn)
    wsgi_intercept.add_wsgi_intercept('cdent.0.0.0.0', 8080, app_fn)
    wsgi_intercept.add_wsgi_intercept('extra.0.0.0.0', 8080, app_fn)

    make_fake_space(module.store, 'cdent')