~jfb-tempo-consulting/unifield-wm/sync-env-py3

1 by Samus CTO
[INIT]
1
#!/usr/bin/env python2
23 by Samus CTO
[FIX] missing utf8 header
2
# -*- coding: utf-8 -*-
17 by Samus CTO
[IMP] Note + skip some tests by command line
3
"""
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
4
  (C) 2012 OpenERP - All rights reserved
17 by Samus CTO
[IMP] Note + skip some tests by command line
5
6
"""
1 by Samus CTO
[INIT]
7
8
#Load config file
9
import config
100.1.2 by Fabien MORIN
US-1610 [IMP] define the default oc in the config file to be able to change it
10
from config import coordo_count, project_count, hq_count, default_oc
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
11
63 by jf
[IMP] New algo:
12
import sys
13
import os
14
import shutil
15
import time
16
import uuid
17
66 by jf
[IMP] Dump dbs
18
import argparse
67 by jf
[IMP] New test to update branches
19
from subprocess import call
66 by jf
[IMP] Dump dbs
20
87.1.1 by jf
[IMP] Add config to load translations
21
import base64
22
import csv
23
37 by Cecile Tonglet
[IMP] mkdb.py is now more permissive about the graph of the instances
24
assert hq_count > 0, "You must have at least one HQ!"
1 by Samus CTO
[INIT]
25
113 by jf
UF5 intersection and intermission created at HQ
26
from scripts.common import client, db_instance, Synchro, check_lp_update, get_revno_from_path
27
4 by Samus CTO
[IMPORT] imported unittest from Python 2.7
28
if sys.version_info >= (2, 7):
29
    import unittest
30
else:
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
31
    # Needed for setUpClass and skipIf methods
4 by Samus CTO
[IMPORT] imported unittest from Python 2.7
32
    import unittest27 as unittest
33
61 by jf
Test to recreate instance id
34
bool_configuration_only = False
35
bool_creation_only = False
63 by jf
[IMP] New algo:
36
master_dir = '/'.join(os.path.realpath(__file__).split('/')[0:-1]+['master_dump'])
37
master_prefix_name = 'msf_profile_sync_so'
67 by jf
[IMP] New test to update branches
38
dir_to_dump = os.path.join(config.dump_dir, time.strftime('%Y%m%d%H%M'))
52 by duy.vo at msf
Added accounts for partners + open periods by default to date
39
123 by jftempo
Load user rights from unifield-server/bin/addons/msf_profile/user_rights
40
def get_file_from_source(filename):
41
    if filename:
42
        last = filename.split('/')[-1]
43
        newfile = os.path.expanduser('~/unifield-server/bin/addons/msf_profile/user_rights/%s' % last)
44
        if os.path.exists(newfile):
45
            return newfile
46
    return filename
47
57 by Cecile Tonglet
[FIX] Version problem with openerplib
48
def warn(*messages):
49
    sys.stderr.write(" ".join(messages)+"\n")
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
50
51
# Fake TestCase to enable/disable quickly some tests
17 by Samus CTO
[IMP] Note + skip some tests by command line
52
class creation_only(unittest.TestCase):
53
    pass
54
55
class configuration_only(unittest.TestCase):
56
    pass
14 by duy.vo at msf
SP-48: Some more config update
57
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
58
class skip_all(unittest.TestCase):
59
    pass
60
87.1.1 by jf
[IMP] Add config to load translations
61
def get_users_from_file(filename):
62
63
    LOGIN_COLUMN_INDEX=1
64
    PASSWD_COLUMN_INDEX=2
65
    FOR_HQ_COLUMN_INDEX=3
66
    FOR_COORDO_COLUMN_INDEX=4
67
    FOR_PROJECT_COLUMN_INDEX=5
68
69
    FIRST_GROUP_COLUMN_INDEX=6
70
71
    SELECTION_CHAR='X'
72
73
    users = []
74
    with open(filename, 'rb') as csvfile:
75
        reader = csv.reader(csvfile, delimiter=';')
76
        header=False
77
78
        groups = []
79
80
        for row in reader:
81
            if not header:
82
                header=True
83
84
                for index in range(FIRST_GROUP_COLUMN_INDEX, len(row)):
85
                    groups.append((index, row[index]))
86
            else:
87
                user_groups = []
88
                for grp in groups:
89
                    if row[grp[0]] == SELECTION_CHAR:
90
                        user_groups.append(grp[1])
91
92
                data = {
93
                    'login': row[LOGIN_COLUMN_INDEX],
94
                    'passwd': row[PASSWD_COLUMN_INDEX],
95
                    'for_hq': True if row[FOR_HQ_COLUMN_INDEX] == SELECTION_CHAR else False,
96
                    'for_co': True if row[FOR_COORDO_COLUMN_INDEX] == SELECTION_CHAR else False,
97
                    'for_pr': True if row[FOR_PROJECT_COLUMN_INDEX] == SELECTION_CHAR else False,
98
                    'groups': user_groups
99
                }
100
101
                users.append(data)
102
    return users
103
14 by duy.vo at msf
SP-48: Some more config update
104
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
105
# Determin skip flags if needed
66 by jf
[IMP] Dump dbs
106
skipDrop = True
68 by jf
Always dumps dbs
107
skipDumpDbs = False
67 by jf
[IMP] New test to update branches
108
skipBranchesUpdate = True
66 by jf
[IMP] Dump dbs
109
61 by jf
Test to recreate instance id
110
if __name__ == '__main__':
66 by jf
[IMP] Dump dbs
111
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
67 by jf
[IMP] New test to update branches
112
    parser.add_argument("--nodrop", "-n", action='store_true', default=False, help="Don't drop existing db")
68 by jf
Always dumps dbs
113
    parser.add_argument("--nodump", action='store_true', default=False, help="Disable dbs dump at the end")
67 by jf
[IMP] New test to update branches
114
    parser.add_argument("--log-to-file", action='store_true', default=False, help="Log the unittest")
71 by jf
[TODO] Stop tests if no update
115
    parser.add_argument("--update-code", action='store_true', default=False, help="Update the code, restart servers and create db if needed")
116
    parser.add_argument('unit_test_option', nargs='*', help='Tests to start: server_creation hq01_creation coordo01_creation dump_all  ...')
66 by jf
[IMP] Dump dbs
117
67 by jf
[IMP] New test to update branches
118
66 by jf
[IMP] Dump dbs
119
    o = parser.parse_args()
68 by jf
Always dumps dbs
120
    if o.nodump and 'dump_all' not in o.unit_test_option:
121
        skipDumpDbs = True
69 by jf
[FIX] dump opt
122
    elif o.unit_test_option and 'dump_all' not in o.unit_test_option:
123
        o.unit_test_option.append('dump_all')
67 by jf
[IMP] New test to update branches
124
71 by jf
[TODO] Stop tests if no update
125
    if o.update_code or 'update_branches' in  o.unit_test_option:
126
        skipBranchesUpdate = False
127
        if o.unit_test_option and 'update_branches' not in o.unit_test_option:
128
            o.unit_test_option.insert(0, 'update_branches')
66 by jf
[IMP] Dump dbs
129
130
    sys.argv = [sys.argv[0]] + o.unit_test_option
67 by jf
[IMP] New test to update branches
131
    skipDrop = o.nodrop
66 by jf
[IMP] Dump dbs
132
63 by jf
[IMP] New algo:
133
    bool_creation_only = bool('creation_only' in sys.argv) or bool('skip_all' in sys.argv)
134
    bool_configuration_only = bool('configuration_only' in sys.argv) or bool('skip_all' in sys.argv)
61 by jf
Test to recreate instance id
135
else:
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
136
    bool_skip_all = bool(__name__+'.skip_all' in sys.argv)
137
    if bool_skip_all:
138
        bool_creation_only = True
139
        bool_configuration_only = True
140
    else:
141
        bool_creation_only = bool(__name__+'.creation_only' in sys.argv)
142
        bool_configuration_only = bool(__name__+'.configuration_only' in sys.argv)
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
143
61 by jf
Test to recreate instance id
144
skipCreation = bool_configuration_only
145
skipModules = bool_configuration_only
76 by jf
[FIX] Wrong skip
146
skipSyncSo = bool_configuration_only
61 by jf
Test to recreate instance id
147
skipModuleUpdate = bool_configuration_only
148
skipUniUser = bool_configuration_only
63 by jf
[IMP] New algo:
149
skipMasterCreation = False
61 by jf
Test to recreate instance id
150
skipGroups = bool_creation_only
151
skipPropInstance = bool_creation_only
152
skipConfig = bool_creation_only
153
skipRegister = bool_creation_only
154
skipSync = bool_creation_only
87.1.1 by jf
[IMP] Add config to load translations
155
skipSync = bool_creation_only
61 by jf
Test to recreate instance id
156
skipModuleData = bool_creation_only
157
skipPartner = bool_creation_only
158
skipManualConfig = bool_creation_only
159
skipOpenPeriod = bool_creation_only
87.1.1 by jf
[IMP] Add config to load translations
160
skipLoadUACFile = bool_creation_only
161
skipCreateUsers = bool_creation_only
162
skipLoadExtraFiles = bool_creation_only
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
163
63 by jf
[IMP] New algo:
164
# eval cond during the run
165
def skip_test_real_eval(cond, reason):
166
    def deco(fun):
167
        def wrap(*a, **b):
168
            if eval(cond):
169
                raise unittest.SkipTest(reason)
170
            return fun(*a, **b)
171
        return wrap
172
    return deco
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
173
67 by jf
[IMP] New test to update branches
174
class update_branches(unittest.TestCase):
175
176
    @unittest.skipIf(skipBranchesUpdate, "Branches update deactivated")
177
    def test_01_update_branch(self):
178
        to_up = check_lp_update(True)
179
        if 'unifield-web' in to_up:
180
            if not config.web_restart_cmd:
181
                raise self.fail('web_restart_cmd not define in config.py')
77 by jf
[FIX] Restart server on update
182
            call(config.web_restart_cmd, shell=True)
67 by jf
[IMP] New test to update branches
183
            to_up.remove('unifield-web')
184
        if to_up:
185
            if not config.server_restart_cmd:
186
                raise self.fail('server_restart_cmd not define in config.py')
77 by jf
[FIX] Restart server on update
187
            call(config.server_restart_cmd, shell=True)
188
            time.sleep(5)
71 by jf
[TODO] Stop tests if no update
189
        if not to_up:
72 by jf
Failed if update asked but no code to pull. It's stop the other tests, usefull for automatic up
190
            raise self.fail('No new code to pull')
67 by jf
[IMP] New test to update branches
191
192
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
193
# Base of database creation
1 by Samus CTO
[INIT]
194
class db_creation(object):
195
37.1.2 by Matthieu Dietrich
UF-1708: [FIX] use new cost center/instance relations
196
    #ignore_wizard = ['sale.price.setup'] # Fixed in unifield-wm > SP5
197
    ignore_wizard = ['msf_button_access_rights.view_config_wizard_install']
1 by Samus CTO
[INIT]
198
199
    base_wizards = {
3 by Samus CTO
[IMP] Add prefix, version in config; shortname and name in db classes; clean up + [IMP] Create msf_instance for each instance created
200
        'base.setup.config' : {
201
            'button' : 'config',
202
        },
1 by Samus CTO
[INIT]
203
        'res.config.view' : {
204
            'name' : "auto_init",
205
            'view' : 'extended',
206
        },
207
        'sale.price.setup' : {
208
            'sale_price' : 0.10,
209
        },
210
        'stock.location.configuration.wizard' : {
211
            'location_type' : 'internal',
212
            'location_usage' : 'stock',
213
            'location_name' : 'Test Location',
214
            'button' : 'action_stop',
215
        },
28 by tfr at openerp
[FIX] Add manual operation
216
        'currency.setup' : {
137.1.1 by Mallory MARCOT
can now select currency for each HQ
217
            'functional_id' : config.default_currency,
28 by tfr at openerp
[FIX] Add manual operation
218
        } 
1 by Samus CTO
[INIT]
219
    }
220
221
    db = None
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
222
    parent = None
223
224
    @property
225
    def parent_name(self):
31.1.2 by Samus CTO
[FIX] TestCases parent problems (msf.instance problem remains: cost_center are not synchronized between brother/sisters)
226
        return self.parent.db.name if self.parent else None
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
227
228
    @classmethod
79 by jf
[IMP] Tree structure
229
    def getNameFormat(cls):
230
        return  {
231
            'db': config.prefix,
232
            'ind': cls.index,
233
            'pind': cls.parent and cls.parent.index or '','ppind': cls.parent and cls.parent.parent and cls.parent.parent.index or ''
234
        }
235
236
    @classmethod
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
237
    def setUpClass(cls):
238
        if cls.db is None and hasattr(cls, 'index'):
79 by jf
[IMP] Tree structure
239
            if cls.parent is not None:
240
                cls.parent.setUpClass()
241
242
243
            name = cls.name_format % cls.getNameFormat()
87.1.1 by jf
[IMP] Add config to load translations
244
            if hasattr(config, 'sync_user_admin') and config.sync_user_admin:
245
                sync_user = 'admin'
246
            else:
247
                sync_user = name
248
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
249
            cls.db = db_instance(
250
                server=client,
251
                name=name,
252
                synchro={
119.2.1 by Fabien MORIN
US-3048 [FIX] use xmlrpc instead of netrpc as it has been removed from the
253
                    'protocol' : 'xmlrpc',
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
254
                    'host' : config.server_host,
119.2.1 by Fabien MORIN
US-3048 [FIX] use xmlrpc instead of netrpc as it has been removed from the
255
                    'port' : config.server_port,
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
256
                    'database' : Synchro.name,
87.1.1 by jf
[IMP] Add config to load translations
257
                    'login' : sync_user,
258
                    'password' : sync_user,
87 by jf
Prevent timeout
259
                    'timeout': 600,
260
                    'netrpc_retry': 10,
261
                    'xmlrpc_retry': 10,
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
262
                },
263
            )
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
264
            last_sync.test_cases.append(cls)
1 by Samus CTO
[INIT]
265
266
    def setUp(self):
267
        if self.db is None:
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
268
            self.fail("Bad use of class")
1 by Samus CTO
[INIT]
269
67 by jf
[IMP] New test to update branches
270
    @unittest.skipIf(skipDrop, "Drop DB deactivated")
1 by Samus CTO
[INIT]
271
    def test_00_drop(self):
272
        self.db.connect('admin')
273
        self.db.drop()
274
63 by jf
[IMP] New algo:
275
    @skip_test_real_eval("skipCreation", "Creation desactivated")
1 by Samus CTO
[INIT]
276
    def test_01_create_db(self):
277
        self.db.connect('admin')
278
        self.db.create_db(config.admin_password)
279
        self.db.wait()
3 by Samus CTO
[IMP] Add prefix, version in config; shortname and name in db classes; clean up + [IMP] Create msf_instance for each instance created
280
        self.db.user('admin').addGroups('Useability / Extended View')
1 by Samus CTO
[INIT]
281
63 by jf
[IMP] New algo:
282
    @skip_test_real_eval("skipModules", "Modules installation desactivated")
1 by Samus CTO
[INIT]
283
    def test_02_base_install(self):
284
        self.db.connect('admin')
285
        self.db.module('msf_profile').install().do()
75 by jf
[FIX] Install sync_so after the master dump.
286
287
76 by jf
[FIX] Wrong skip
288
    @skip_test_real_eval("skipSyncSo", "Modules installation desactivated")
289
    def test_04_sync_so_install(self):
75 by jf
[FIX] Install sync_so after the master dump.
290
        self.db.connect('admin')
1 by Samus CTO
[INIT]
291
        self.db.module('sync_so').install().do()
85.1.1 by jf
Disable automatic backup
292
        # disable automatic backup
85.1.3 by jf
Disable automatic backup
293
        backup_ids = self.db.get('ir.model').search([('model', '=', 'backup.config')])
294
        if backup_ids:
295
            self.db.get('backup.config').write([1], {
85.1.1 by jf
Disable automatic backup
296
                'beforemanualsync': False,
297
                'beforeautomaticsync': False,
298
                'aftermanualsync': False,
299
                'afterautomaticsync': False,
300
                'scheduledbackup': False
301
            })
1 by Samus CTO
[INIT]
302
74 by jf
[IMP] dump db @the end
303
    @skip_test_real_eval("skipUniUser", "UniField user creation desactivated")
75 by jf
[FIX] Install sync_so after the master dump.
304
    def test_05_unifield_user_creation(self):
1 by Samus CTO
[INIT]
305
        self.db.connect('admin')
87.1.1 by jf
[IMP] Add config to load translations
306
        if not hasattr(config, 'load_uac_file') or not config.load_uac_file:
307
            self.db.user('unifield').add('admin').addGroups('Sync / User', 'Purchase / User')
1 by Samus CTO
[INIT]
308
63 by jf
[IMP] New algo:
309
1 by Samus CTO
[INIT]
310
    def configure(self):
3 by Samus CTO
[IMP] Add prefix, version in config; shortname and name in db classes; clean up + [IMP] Create msf_instance for each instance created
311
        # We did rather start on msf_instance.setup...
312
        # Reason: For an unknown reason, this wizard is set as 'done' automatically after run any first wizard
313
        #model = 'base.setup.installer'
314
        model = 'msf_instance.setup'
1 by Samus CTO
[INIT]
315
        while model != 'ir.ui.menu':
316
            try:
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
317
                # skip account.installer if no parent_name providen (typically: HQ instance)
37.1.2 by Matthieu Dietrich
UF-1708: [FIX] use new cost center/instance relations
318
                if model in self.ignore_wizard or \
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
319
                   (model == 'account.installer' and self.parent_name is not None) or \
320
                   (model == 'msf_instance.setup' and self.db is Synchro):
1 by Samus CTO
[INIT]
321
                    proxy = self.db.get(model)
322
                    answer = proxy.action_skip([])
3 by Samus CTO
[IMP] Add prefix, version in config; shortname and name in db classes; clean up + [IMP] Create msf_instance for each instance created
323
                elif model == 'msf_instance.setup':
98 by jf
US-1362 [IMP] New wizard to set sync instance
324
                    instance_id = self.db.search_data('msf.instance', [('instance','=',self.db.name)])[0]
325
                    self.db.get('res.company').write([1], {'instance_id': instance_id})
326
                    answer = self.db.wizard(model, {'instance_id': instance_id}).action_next()
1 by Samus CTO
[INIT]
327
                else:
3 by Samus CTO
[IMP] Add prefix, version in config; shortname and name in db classes; clean up + [IMP] Create msf_instance for each instance created
328
                    data = dict(self.base_wizards.get(model, {}))
1 by Samus CTO
[INIT]
329
                    button = data.pop('button', 'action_next')
330
                    answer = getattr(self.db.wizard(model, data), button)()
331
                model = answer.get('res_model', None)
332
            except:
57 by Cecile Tonglet
[FIX] Version problem with openerplib
333
                warn("DEBUG: db=%s, model=%s" % (self.db.name, model))
1 by Samus CTO
[INIT]
334
                raise
335
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
336
    @classmethod
337
    def sync(cls, db=None):
338
        if db is None: db = cls.db
339
        db.connect('admin')
41 by Cecile Tonglet
[IMP] Try to connect before syncing
340
        db.get('sync.client.sync_server_connection').connect()
1 by Samus CTO
[INIT]
341
        if not db.get('sync.client.entity').sync():
342
            monitor = db.get('sync.monitor')
343
            ids = monitor.search([], 0, 1, '"end" desc')
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
344
            raise Exception('Synchronization process of database "%s" failed!\n%s' % (db.db_name,monitor.read(ids, ['error'])[0]['error']))
106 by jf
US-1610 New OC field on groups / instances
345
21 by Samus CTO
[FIX] prop instance and cost center for test cases and from hq_data + [FIX] self.db.db_name to self.db.name to avoid connection error + [IMP] Added finance.py test + [FIX] use groups of hq_data + [IMP] remove shortname and version
346
    # Create Cost Center and Proprietary Instance for Test Cases
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
347
    def make_prop_instance(self, hq, prop_instance=None, mission=None):
31.1.2 by Samus CTO
[FIX] TestCases parent problems (msf.instance problem remains: cost_center are not synchronized between brother/sisters)
348
        hq.connect('admin')
37.1.2 by Matthieu Dietrich
UF-1708: [FIX] use new cost center/instance relations
349
        # Get 2 cost centers: the top one and the normal one
350
        cost_center_id = False
351
        top_cost_center_id = False
89 by jf
[FIX] Set correctly mission field on msf.instance
352
        mission_suffix = 'OC'
40.1.1 by Matthieu Dietrich
UF-1871: [FIX] changed for UF-1871
353
        if mission and mission.db is hq:
89 by jf
[FIX] Set correctly mission field on msf.instance
354
            # coordo
355
            mission_suffix = "%02d" % self.index
37.1.2 by Matthieu Dietrich
UF-1708: [FIX] use new cost center/instance relations
356
            top_data = {
357
                'name' : "HT%d" % (self.index),
358
                'code' : "HT%d" % (self.index),
359
                'category' : 'OC',
360
                'type' : 'view',
361
                'parent_id' : hq.search_data('account.analytic.account', {'Code':'OC'})[0],
362
            }
363
            top_cost_center_id = hq.get('account.analytic.account').create(top_data)
21 by Samus CTO
[FIX] prop instance and cost center for test cases and from hq_data + [FIX] self.db.db_name to self.db.name to avoid connection error + [IMP] Added finance.py test + [FIX] use groups of hq_data + [IMP] remove shortname and version
364
            data = {
37.1.2 by Matthieu Dietrich
UF-1708: [FIX] use new cost center/instance relations
365
                'name' : "HT%d01" % (self.index),
366
                'code' : "HT%d01" % (self.index),
21 by Samus CTO
[FIX] prop instance and cost center for test cases and from hq_data + [FIX] self.db.db_name to self.db.name to avoid connection error + [IMP] Added finance.py test + [FIX] use groups of hq_data + [IMP] remove shortname and version
367
                'category' : 'OC',
37.1.2 by Matthieu Dietrich
UF-1708: [FIX] use new cost center/instance relations
368
                'type' : 'normal',
369
                'parent_id' : top_cost_center_id,
100 by jf
[IMP] Cost Center: start date 2013 + set fx_gain_loss
370
                'date_start': '2013-01-01',
21 by Samus CTO
[FIX] prop instance and cost center for test cases and from hq_data + [FIX] self.db.db_name to self.db.name to avoid connection error + [IMP] Added finance.py test + [FIX] use groups of hq_data + [IMP] remove shortname and version
371
            }
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
372
            cost_center_id = hq.get('account.analytic.account').create(data)
40.1.1 by Matthieu Dietrich
UF-1871: [FIX] changed for UF-1871
373
        elif self.db is not hq:
89 by jf
[FIX] Set correctly mission field on msf.instance
374
            # project
375
            mission_suffix = "%02d" % mission.index
37.1.2 by Matthieu Dietrich
UF-1708: [FIX] use new cost center/instance relations
376
            parent_cost_center_id = hq.search_data('account.analytic.account', {'Code':"HT%d" % (mission.index)})[0]
377
            data = {
378
                'name' : "HT%d%d1" % (mission.index, self.index),
379
                'code' : "HT%d%d1" % (mission.index, self.index),
380
                'category' : 'OC',
381
                'type' : 'normal',
382
                'parent_id' : parent_cost_center_id,
100 by jf
[IMP] Cost Center: start date 2013 + set fx_gain_loss
383
                'date_start': '2013-01-01',
37.1.2 by Matthieu Dietrich
UF-1708: [FIX] use new cost center/instance relations
384
            }
385
            top_cost_center_id = hq.get('account.analytic.account').create(data)
21 by Samus CTO
[FIX] prop instance and cost center for test cases and from hq_data + [FIX] self.db.db_name to self.db.name to avoid connection error + [IMP] Added finance.py test + [FIX] use groups of hq_data + [IMP] remove shortname and version
386
        data = {
387
            'code' : self.db.name,
388
            'name' : self.db.name,
389
            'instance' : self.db.name,
89 by jf
[FIX] Set correctly mission field on msf.instance
390
            'mission' : '%s_MISSION_%s' % (config.prefix, mission_suffix),
21 by Samus CTO
[FIX] prop instance and cost center for test cases and from hq_data + [FIX] self.db.db_name to self.db.name to avoid connection error + [IMP] Added finance.py test + [FIX] use groups of hq_data + [IMP] remove shortname and version
391
            'state' : 'active',
392
        }
393
        if prop_instance is not None:
394
            data.update(prop_instance)
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
395
        if not hq.test('msf.instance', data):
37.1.2 by Matthieu Dietrich
UF-1708: [FIX] use new cost center/instance relations
396
            instance_id = hq.get('msf.instance').create(data)
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
397
            if self.db is not hq:
37.1.2 by Matthieu Dietrich
UF-1708: [FIX] use new cost center/instance relations
398
                # Create/update cost center lines as needed by level
399
                if mission.db is hq:
400
                    # Coordo: add cost center lines to the instance, tick both
401
                    top_line_data = {
402
                        'instance_id' : instance_id,
403
                        'cost_center_id' : top_cost_center_id,
404
                        'is_target' : True,
40.1.1 by Matthieu Dietrich
UF-1871: [FIX] changed for UF-1871
405
                        'is_top_cost_center' : True,
41.1.2 by Matthieu Dietrich
UF-1858: [IMP] new is_po_fo_cost_center field in instance cost centers
406
                        'is_po_fo_cost_center' : False,
37.1.2 by Matthieu Dietrich
UF-1708: [FIX] use new cost center/instance relations
407
                    }
408
                    hq.get('account.target.costcenter').create(top_line_data)
409
                    line_data = {
410
                        'instance_id' : instance_id,
411
                        'cost_center_id' : cost_center_id,
412
                        'is_target' : True,
40.1.1 by Matthieu Dietrich
UF-1871: [FIX] changed for UF-1871
413
                        'is_top_cost_center' : False,
41.1.2 by Matthieu Dietrich
UF-1858: [IMP] new is_po_fo_cost_center field in instance cost centers
414
                        'is_po_fo_cost_center' : True,
37.1.2 by Matthieu Dietrich
UF-1708: [FIX] use new cost center/instance relations
415
                    }
416
                    hq.get('account.target.costcenter').create(line_data)
417
                else:
418
                    # Project: add cost center lines to parent coordo instance, tick them in instance
419
                    top_line_data = {
420
                        'instance_id' : data['parent_id'],
421
                        'cost_center_id' : top_cost_center_id,
422
                        'is_target' : False,
40.1.1 by Matthieu Dietrich
UF-1871: [FIX] changed for UF-1871
423
                        'is_top_cost_center' : False,
41.1.2 by Matthieu Dietrich
UF-1858: [IMP] new is_po_fo_cost_center field in instance cost centers
424
                        'is_po_fo_cost_center' : False,
37.1.2 by Matthieu Dietrich
UF-1708: [FIX] use new cost center/instance relations
425
                    }
426
                    hq.get('account.target.costcenter').create(top_line_data)
427
                    project_target_ids = hq.search_data('account.target.costcenter', {'instance_id' : instance_id, 'cost_center_id' : top_cost_center_id})
41.1.2 by Matthieu Dietrich
UF-1858: [IMP] new is_po_fo_cost_center field in instance cost centers
428
                    hq.write('account.target.costcenter', project_target_ids, {'is_target': True, 'is_top_cost_center': True, 'is_po_fo_cost_center' : True})
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
429
                self.sync(hq)
21 by Samus CTO
[FIX] prop instance and cost center for test cases and from hq_data + [FIX] self.db.db_name to self.db.name to avoid connection error + [IMP] Added finance.py test + [FIX] use groups of hq_data + [IMP] remove shortname and version
430
100.1.2 by Fabien MORIN
US-1610 [IMP] define the default oc in the config file to be able to change it
431
    def add_to_group(self, group_name, group_type, oc=default_oc):
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
432
        Synchro.connect('admin')
433
        entity_ids = Synchro.get('sync.server.entity').search([('name','=',self.db.name)])
434
        assert len(entity_ids) == 1, "The entity must exists!"
435
        # Make groups
436
        group = Synchro.get('sync.server.entity_group')
437
        # Make or update OC group
438
        group_ids = group.search([('name','=',group_name)])
439
        if group_ids:
440
            group.write(group_ids, {'entity_ids' : [(4,entity_ids[0])]})
441
        else:
442
            Type = Synchro.get('sync.server.group_type')
443
            type_ids = Type.search([('name', '=', group_type)])
444
            if not type_ids:
445
                type_ids = [Type.create({'name':group_type})]
446
            group.create({
447
                'name' : group_name,
448
                'type_id' : type_ids[0],
449
                'entity_ids' : [(6,0,entity_ids)],
100.1.1 by Fabien MORIN
US-1610 [IMP] add the oc property to the group creation as it is now a required
450
                'oc': oc
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
451
            })
452
65 by jf
EXP
453
    @classmethod
66 by jf
[IMP] Dump dbs
454
    def dump_db(self, path, name=None):
455
        if self.db is None:
456
            self.setUpClass()
65 by jf
EXP
457
        if not os.path.exists(path):
458
            os.makedirs(path)
459
        if name is None:
66 by jf
[IMP] Dump dbs
460
            self.db.connect()
461
            name =self.db.db_name
65 by jf
EXP
462
        bckfile = os.path.join(path, '%s.dump' % name)
63 by jf
[IMP] New algo:
463
        orig_bck = bckfile
464
        i = 0
465
        while os.path.exists(bckfile):
466
            i += 1
65 by jf
EXP
467
            bckfile = os.path.join(path, '%s_%s.dump' % (name, i))
63 by jf
[IMP] New algo:
468
        if i:
469
            shutil.move(orig_bck, bckfile)
91.1.1 by jftempo
[IMP] Dump/restore: don't load file in memory + add sync menu shortcuts
470
        self.db.dump_db_file(orig_bck)
63 by jf
[IMP] New algo:
471
472
    def restore_db(self):
473
        dump = os.path.join(master_dir, "%s.dump" % (master_prefix_name,) ) #self.db.name)
474
        self.db.connect('admin')
91.1.1 by jftempo
[IMP] Dump/restore: don't load file in memory + add sync menu shortcuts
475
        self.db.restore_db_file(self.db.name, dump)
79 by jf
[IMP] Tree structure
476
        # wait process
477
        time.sleep(10)
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
478
479
# Run a last sync after all synchronization
480
class last_sync(unittest.TestCase):
481
    test_cases = []
482
483
    def test_50_last_synchronization(self):
484
        if not self.test_cases:
485
            self.skipTest("No database to update")
87.1.1 by jf
[IMP] Add config to load translations
486
        for i in [0,1]:
487
            for tc in self.test_cases:
488
                assert issubclass(tc, db_creation), "The object %s is not of type db_creation!"
489
                tc.sync()
65 by jf
EXP
490
126 by jf
MKDB: activate inter partners
491
class activate_inter_partner(unittest.TestCase):
492
493
    def test_99_activate_inter_partner(self):
130 by jftempo
Intermission/section activation: disable projects
494
        all_projects = []
495
        for tc in test_cases:
496
            if issubclass(tc, projectn_creation):
497
                all_projects.append(tc.db.name)
127 by jf
MKDB: activate inter partners
498
        for tc in test_cases:
126 by jf
MKDB: activate inter partners
499
            if issubclass(tc, (coordon_creation, projectn_creation)):
500
                db = tc.db
501
                db.connect('admin')
127 by jf
MKDB: activate inter partners
502
                p_obj = db.get('res.partner')
130 by jftempo
Intermission/section activation: disable projects
503
                exclude_name = [db.name]
131 by jftempo
Exclude same mission partner
504
                same_mission_ids = p_obj.search([('partner_type', '=', 'internal')])
505
                for p in p_obj.read(same_mission_ids, ['name']):
506
                    exclude_name.append(p['name'])
130 by jftempo
Intermission/section activation: disable projects
507
                exclude_name += all_projects
127 by jf
MKDB: activate inter partners
508
                partner_ids = p_obj.search([('partner_type', 'in', ['section', 'intermission']), ('active', '=', False), ('name', 'not in', exclude_name)])
126 by jf
MKDB: activate inter partners
509
                if partner_ids:
127 by jf
MKDB: activate inter partners
510
                    p_obj.write(partner_ids, {'active': True})
126 by jf
MKDB: activate inter partners
511
65 by jf
EXP
512
class dump_all(unittest.TestCase):
66 by jf
[IMP] Dump dbs
513
514
    @unittest.skipIf(skipDumpDbs, "DBs dump directory creation deactivated")
515
    def test_00_create_dump_dir(self):
67 by jf
[IMP] New test to update branches
516
        if not os.path.exists(dir_to_dump):
517
            os.makedirs(dir_to_dump)
65 by jf
EXP
518
519
    @unittest.skipIf(skipDumpDbs, "DBs dump deactivated")
520
    def test_10_dump_all(self):
66 by jf
[IMP] Dump dbs
521
        for tc in test_cases:
65 by jf
EXP
522
            if issubclass(tc, db_creation):
67 by jf
[IMP] New test to update branches
523
                tc.dump_db(dir_to_dump)
66 by jf
[IMP] Dump dbs
524
525
    @unittest.skipIf(skipDumpDbs, "DBs dump deactivated")
526
    def test_20_dump_branch_info(self):
527
        info = {}
528
        for ad in config.addons:
529
            src_path = os.path.join(config.source_path, ad)
79 by jf
[IMP] Tree structure
530
            if not os.path.exists(src_path):
531
                raise self.fail('%s does not exist ! Did you set source_path in config.py ?' % src_path)
67 by jf
[IMP] New test to update branches
532
            info[ad] = get_revno_from_path(src_path)
533
        f = open(os.path.join(dir_to_dump, 'info.txt'), 'w')
66 by jf
[IMP] Dump dbs
534
        for mod, data in info.items():
535
            f.write("%s_url=%s\n" % (mod, data['lpurl']))
536
            f.write("%s_revno=%s\n" % (mod, data['revno']))
537
        f.close()
538
17 by Samus CTO
[IMP] Note + skip some tests by command line
539
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
540
# Specific Sync Server creation
16 by duy.vo at msf
SP-48: more modif
541
class server_creation(db_creation, unittest.TestCase):
1 by Samus CTO
[INIT]
542
    db = Synchro
87.1.1 by jf
[IMP] Add config to load translations
543
544
    def test_02_install_lang(self):
545
        self.db.connect('admin')
546
        lang = False
547
        if hasattr(config, 'lang'):
548
            lang = config.lang
549
        if lang:
550
            if self.db.get('sync.client.entity'):
551
                call(config.server_restart_cmd, shell=True)
552
                time.sleep(5)
553
            lang_obj = self.db.get('res.lang')
554
            lang_id = lang_obj.search([('code', '=', lang)]) 
555
            mod_obj = self.db.get('ir.module.module')
556
            if lang_id:
557
                lang_obj.write(lang_id, {'translatable': True})
558
                mod_ids = mod_obj.search([('state', '=', 'installed')])
559
                mod_obj.button_update_translations(mod_ids, lang)
560
63 by jf
[IMP] New algo:
561
    @unittest.skipIf(skipMasterCreation, "Master dump creation desactivated") 
75 by jf
[FIX] Install sync_so after the master dump.
562
    def test_03_dump_master(self):
65 by jf
EXP
563
        self.dump_db(master_dir, master_prefix_name)
1 by Samus CTO
[INIT]
564
2 by Samus CTO
[FIX] msf_sync_data_* enabled
565
    @unittest.skipIf(skipModuleUpdate, "update_server installation desactivated")
566
    def test_10_install_update_server(self):
567
        self.db.connect('admin')
568
        self.db.module('update_server').install().do()
569
5 by Samus CTO
[IMP] Better installation
570
    @unittest.skipIf(skipModuleData, "Data module installation desactivated")
2 by Samus CTO
[FIX] msf_sync_data_* enabled
571
    def test_10_install_data_server(self):
572
        self.db.connect('admin')
60.1.1 by jf
Module remote wh added in server
573
        self.db.module('sync_remote_warehouse_server').install().do()
21 by Samus CTO
[FIX] prop instance and cost center for test cases and from hq_data + [FIX] self.db.db_name to self.db.name to avoid connection error + [IMP] Added finance.py test + [FIX] use groups of hq_data + [IMP] remove shortname and version
574
        self.db.module('msf_sync_data_server').install().do()
1 by Samus CTO
[INIT]
575
576
    @unittest.skipIf(skipConfig, "Modules configuration desactivated")
2 by Samus CTO
[FIX] msf_sync_data_* enabled
577
    def test_30_configuration_wizards(self):
1 by Samus CTO
[INIT]
578
        self.db.connect('admin')
579
        self.configure()
580
581
    @unittest.skipIf(skipSync, "Synchronization desactivated")
2 by Samus CTO
[FIX] msf_sync_data_* enabled
582
    def test_40_activate_rules(self):
1 by Samus CTO
[INIT]
583
        self.db.connect('admin')
60.1.2 by jf
[FIX] sync_server.sync_rule: are activated by default at creation, don't call activate desactivated rules on csv
584
        sync_rule_obj = Synchro.get('sync_server.message_rule')
585
        rule_ids = sync_rule_obj.search([('active', '=', 1)])
586
        for rule in sync_rule_obj.read(rule_ids, ['model_id']):
106 by jf
US-1610 New OC field on groups / instances
587
            sync_rule_obj.write(rule['id'], {'model_id': rule['model_id'] , 'status': 'valid'})
60.1.2 by jf
[FIX] sync_server.sync_rule: are activated by default at creation, don't call activate desactivated rules on csv
588
        #Synchro.activate('sync_server.sync_rule', [])
1 by Samus CTO
[INIT]
589
100 by jf
[IMP] Cost Center: start date 2013 + set fx_gain_loss
590
    def test_99_add_shortcut(self):
591
        self.db.connect('admin')
592
        menu_to_add = ['sync_server.entity_menu', 'sync_server.sync_rule_menu', 'sync_server.message_rule_menu']
593
        for menu in menu_to_add:
594
            module, xml = menu.split('.')
595
            menu_id = self.db.get('ir.model.data').get_object_reference(module, xml)[1]
596
            menu_name = self.db.get('ir.ui.menu').name_get([menu_id])[0][1]
597
            try:
598
                self.db.get('ir.ui.view_sc').create({'res_id': menu_id, 'name': menu_name})
599
            except:
600
                raise
601
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
602
# Base for instances creation ('is not Synchro')
1 by Samus CTO
[INIT]
603
class client_creation(db_creation):
87.1.1 by jf
[IMP] Add config to load translations
604
    def import_csv(self, filename):
605
        model = os.path.splitext(os.path.basename(filename))[0]
606
        if model in ('product.nomenclature', 'product.category', 'product.product'):
607
            req = self.db.get('res.request')
608
            nb = req.search([])
609
            wiz = self.db.get('import_data')
610
            f = open(filename, 'rb')
611
            rec_id = wiz.create({'object': model, 'file': base64.encodestring(f.read())})
612
            f.close()
613
            wiz.import_csv([rec_id], {})
614
            imported = False
615
            while not imported:
106 by jf
US-1610 New OC field on groups / instances
616
                time.sleep(5)
617
                imported = nb != req.search([])
87.1.1 by jf
[IMP] Add config to load translations
618
            return
619
        with open(filename, 'rb') as csvfile:
620
            reader = csv.reader(csvfile, delimiter=',')
621
            fields = False
622
            data = []
623
            for row in reader:
624
                if not fields:
625
                    fields = row
626
                else:
627
                    data.append(row)
628
            obj = self.db.get(model)
629
            if obj and fields and data:
630
                obj.import_data(fields, data)
63 by jf
[IMP] New algo:
631
632
    @unittest.skipIf(skipMasterCreation, "Creation of coordo from master")
79 by jf
[IMP] Tree structure
633
    def test_00_restore_from_master(self):
63 by jf
[IMP] New algo:
634
        global skipCreation
635
        global skipModules
636
        skipCreation = True
637
        skipModules = True
638
        self.restore_db()
639
2 by Samus CTO
[FIX] msf_sync_data_* enabled
640
    @unittest.skipIf(skipModuleUpdate, "update_client installation desactivated")
641
    def test_10_install_update_client(self):
642
        self.db.connect('admin')
643
        self.db.module('update_client').install().do()
644
645
    @unittest.skipIf(skipModules, "Modules installation desactivated")
646
    def test_10_install_web_module(self):
647
        self.db.connect('admin')
648
        self.db.module('sync_client_web').install().do()
649
1 by Samus CTO
[INIT]
650
    @unittest.skipIf(skipRegister, "Registration desactivated")
2 by Samus CTO
[FIX] msf_sync_data_* enabled
651
    def test_20_register_entity(self):
1 by Samus CTO
[INIT]
652
        Synchro.connect('admin')
87.1.1 by jf
[IMP] Add config to load translations
653
        if not hasattr(config, 'sync_user_admin') or not config.sync_user_admin:
654
            Synchro.user(self.db.name).add(self.db.name).addGroups('Sync / User')
3 by Samus CTO
[IMP] Add prefix, version in config; shortname and name in db classes; clean up + [IMP] Create msf_instance for each instance created
655
        self.db.connect('admin')
61 by jf
Test to recreate instance id
656
        # search the current entity
107 by jf
US-1610 [FIX] Allow to build pre oc-field RB
657
        with_oc_field = False
658
        entity_fields = self.db.get('sync.client.entity').fields_get(['oc'])
659
        if entity_fields.get('oc'):
660
            with_oc_field = True
661
61 by jf
Test to recreate instance id
662
        entity_id = self.db.get('sync.client.entity').search([])
100.1.2 by Fabien MORIN
US-1610 [IMP] define the default oc in the config file to be able to change it
663
        data = {
106 by jf
US-1610 New OC field on groups / instances
664
            'name': self.db.name,
665
            'identifier': str(uuid.uuid1()),
100.1.2 by Fabien MORIN
US-1610 [IMP] define the default oc in the config file to be able to change it
666
        }
107 by jf
US-1610 [FIX] Allow to build pre oc-field RB
667
        if with_oc_field:
668
            data['oc'] = default_oc
61 by jf
Test to recreate instance id
669
        if entity_id:
670
            entity_data = self.db.get('sync.client.entity').read(entity_id[0])
671
            if entity_data['name'] != self.db.name:
672
                self.db.get('sync.client.entity').write(entity_id[0], data)
673
        else:
674
            self.db.get('sync.client.entity').create(data)
107 by jf
US-1610 [FIX] Allow to build pre oc-field RB
675
        wiz_data = {'email': config.default_email}
676
        if with_oc_field:
677
            wiz_data['oc'] = default_oc
678
        wizard = self.db.wizard('sync.client.register_entity', wiz_data)
1 by Samus CTO
[INIT]
679
        # Fetch instances
680
        wizard.next()
681
        # Group state
682
        wizard.group_state()
683
        # Register instance
684
        wizard.validate()
685
        # Search entity record, server side
686
        entities = Synchro.get('sync.server.entity')
21 by Samus CTO
[FIX] prop instance and cost center for test cases and from hq_data + [FIX] self.db.db_name to self.db.name to avoid connection error + [IMP] Added finance.py test + [FIX] use groups of hq_data + [IMP] remove shortname and version
687
        entity_ids = entities.search([('name','=',self.db.name)])
5 by Samus CTO
[IMP] Better installation
688
        if not len(entity_ids) == 1:
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
689
            self.fail("Cannot find validation request for entity %s!" % self.db.name)
1 by Samus CTO
[INIT]
690
        # Set parent
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
691
        if self.parent_name is not None:
692
            parents = entities.search([('name','=',self.parent_name)])
1 by Samus CTO
[INIT]
693
            if not parents:
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
694
                self.fail('Cannot find parent entity for %s!' % self.db.name)
5 by Samus CTO
[IMP] Better installation
695
            entities.write(entity_ids, {'parent_id':parents[0]})
1 by Samus CTO
[INIT]
696
        # Server accept validation
5 by Samus CTO
[IMP] Better installation
697
        entities.validate_action(entity_ids)
3 by Samus CTO
[IMP] Add prefix, version in config; shortname and name in db classes; clean up + [IMP] Create msf_instance for each instance created
698
1 by Samus CTO
[INIT]
699
    @unittest.skipIf(skipSync, "Synchronization desactivated")
3 by Samus CTO
[IMP] Add prefix, version in config; shortname and name in db classes; clean up + [IMP] Create msf_instance for each instance created
700
    def test_50_synchronize(self):
1 by Samus CTO
[INIT]
701
        self.db.connect('admin')
702
        self.sync()
114 by jf
Create ESC partner + registers
703
113 by jf
UF5 intersection and intermission created at HQ
704
    def test_70_create_intermission(self):
705
        if isinstance(self, hqn_creation):
706
            return True
707
708
        partner = self.hq.db.get('res.partner')
709
        account = self.hq.db.get('account.account')
710
        partner.create({
711
            'name': self.db.name,
712
            'partner_type': 'intermission',
713
            'customer': False,
714
            'supplier': False,
715
            'property_account_payable':  account.search([('code','=','30020')])[0],
716
            'property_account_receivable': account.search([('code','=','12050')])[0],
717
            'city': 'XXX',
718
        })
1 by Samus CTO
[INIT]
719
87.1.1 by jf
[IMP] Add config to load translations
720
    @unittest.skipIf(skipCreateUsers, "Create users desactivated")
721
    def test_70_create_users(self):
722
        if not hasattr(config, 'load_users_file') or not config.load_users_file:
723
            return
724
725
        is_hq = isinstance(self, hqn_creation)
726
        is_coordo = isinstance(self, coordon_creation)
727
        is_project = isinstance(self, projectn_creation)
728
729
        if is_hq or is_coordo or is_project:
730
            users = get_users_from_file(config.load_users_file);
731
            for u in users:
732
                if (is_hq and u['for_hq']) or (is_coordo and u['for_co']) or (is_project and u['for_pr']):
733
                    self.db.user(u['login']).add(u['passwd']).addGroups(*u['groups'])
734
735
5 by Samus CTO
[IMP] Better installation
736
    @unittest.skipIf(skipModuleData, "Data module installation desactivated")
737
    def test_90_install_post_data(self):
738
        self.db.connect('admin')
87.1.1 by jf
[IMP] Add config to load translations
739
        if hasattr(config, 'load_data') and config.load_data:
740
            for filename in config.load_data:
741
                self.import_csv(filename)
742
        else:
743
            self.db.module('msf_sync_data_post_synchro').install().do().set_notinstalled()
5 by Samus CTO
[IMP] Better installation
744
89 by jf
[FIX] Set correctly mission field on msf.instance
745
    def search_account(self, code):
746
        account = self.db.get('account.account')
747
        ac_ids = account.search([('code', '=', code)])
748
        if ac_ids:
749
            return ac_ids[0]
750
        return False
751
752
    def test_91_configure_company_accounts(self):
753
        company_fields = {
754
            'salaries_default_account': '30100',
755
            'counterpart_hq_entries_default_account': '33010',
756
            'import_invoice_default_account': '12011',
757
            'intermission_default_counterpart': '14010',
758
            'revaluation_default_account': '67050',
759
            'ye_pl_cp_for_bs_debit_bal_account': '69001',
760
            'ye_pl_cp_for_bs_credit_bal_account': '79002',
761
            'ye_pl_pos_credit_account': '79003',
762
            'ye_pl_ne_credit_account': '50000',
763
            'ye_pl_pos_debit_account': '51000',
764
            'ye_pl_ne_debit_account': '69002',
765
        }
766
        for f in company_fields:
767
            company_fields[f] = self.search_account(company_fields[f])
768
        self.db.get('res.company').write([1], company_fields)
769
10 by Samus CTO
[IMP] Instance Partner is now supplier and customer + accounts are set
770
    @unittest.skipIf(skipPartner, "Partner creation desactivated")
771
    def test_91_instance_partner(self):
772
        self.db.connect('admin')
773
        account = self.db.get('account.account')
87.1.1 by jf
[IMP] Add config to load translations
774
52 by duy.vo at msf
Added accounts for partners + open periods by default to date
775
        res = self.db.get('res.partner')
776
        temp_partner = res.search([('name','=','Local Market')])
81.1.1 by jf
Master data: New Coa
777
        # new CoA (2014-02-20)
81.1.2 by jf
Tab vs space
778
        payable_ids = account.search([('code','=','30020')])
779
        if not payable_ids:
780
            payable_ids = account.search([('code','=','3000')])
81.1.1 by jf
Master data: New Coa
781
81.1.2 by jf
Tab vs space
782
        receivable_ids = account.search([('code','=','12050')])
81.1.1 by jf
Master data: New Coa
783
        if not receivable_ids:
81.1.2 by jf
Tab vs space
784
            receivable_ids = account.search([('code','=','1205')])
52 by duy.vo at msf
Added accounts for partners + open periods by default to date
785
        if temp_partner:
786
            # set account values for local market
787
            self.db.write('res.partner', temp_partner,{
81.1.1 by jf
Master data: New Coa
788
                'property_account_payable' : payable_ids[0],
789
                'property_account_receivable' : receivable_ids[0],
52 by duy.vo at msf
Added accounts for partners + open periods by default to date
790
                'city': 'Geneva',
106 by jf
US-1610 New OC field on groups / instances
791
            })
52 by duy.vo at msf
Added accounts for partners + open periods by default to date
792
        temp_partner = res.search([('name','=',self.db.name)])
793
        if temp_partner:
794
            # set account values for the default user
795
            self.db.write('res.partner', temp_partner,{
81.1.1 by jf
Master data: New Coa
796
                'property_account_payable' : payable_ids[0],
797
                'property_account_receivable' : receivable_ids[0],
106 by jf
US-1610 New OC field on groups / instances
798
            })
17 by Samus CTO
[IMP] Note + skip some tests by command line
799
55 by duy.vo at msf
Moved open period to the end
800
    @unittest.skipIf(skipOpenPeriod, "Open Period desactivated")
801
    def test_92_open_period(self):
802
        self.db.connect('admin')
803
        today = time.strftime('%Y-%m-%d')
804
        month = time.strftime('%m')
805
        # search current fiscalyear
806
        fy_ids = self.db.search_data('account.fiscalyear', [('date_start', '<=', today), ('date_stop', '>=', today)])
119.1.1 by jf
US-3204: create FY
807
        if not fy_ids:
808
            create_fy_wiz = self.db.get('account.period.create')
809
            wiz_id = create_fy_wiz.create({'fiscalyear': 'current'})
810
            create_fy_wiz.account_period_create_periods([wiz_id])
811
            fy_ids = self.db.search_data('account.fiscalyear', [('date_start', '<=', today), ('date_stop', '>=', today)])
812
55 by duy.vo at msf
Moved open period to the end
813
        assert len(fy_ids) > 0, "No fiscalyear found!"
814
        period_ids = self.db.search_data('account.period', [('fiscalyear_id', 'in', fy_ids), ('number', '<=', month), ('state', '=', 'created')])
815
        # change all period by draft state (should use action_set_state but openerplib doesn't give way to do this)
816
        # as it's to open period from created to draft state, it's not very important
817
        self.db.write('account.period', period_ids, {'state': 'draft'})
87.1.1 by jf
[IMP] Add config to load translations
818
100 by jf
[IMP] Cost Center: start date 2013 + set fx_gain_loss
819
    def set_analytic_loss(self, db, code):
820
        db.connect('admin')
821
        ana_obj = db.get('account.analytic.account')
822
        ids = ana_obj.search([('code', '=', code)])
823
        if ids:
824
            ana_obj.write(ids[0], {'for_fx_gain_loss': True})
825
826
    def test_93_set_gain_loss(self):
827
        to_hq = False
828
        code = False
829
        if isinstance(self, projectn_creation):
830
            code = "HT%d%d1" % (self.parent.index, self.index)
831
        elif isinstance(self, coordon_creation):
832
            code = "HT%d01" % (self.index)
833
            if self.index == 1:
834
                to_hq = True
835
        if code:
836
            self.set_analytic_loss(self.db, code)
837
            if to_hq:
838
                self.set_analytic_loss(self.hq.db, code)
839
114 by jf
Create ESC partner + registers
840
    def test_95_create_registers(self):
841
        if isinstance(self, hqn_creation):
842
            return True
843
844
        reg = {}
845
        for j_type, account_code in [('bank', '10200'), ('cash', '10100'), ('cheque', '10210')]:
846
            account_id = self.db.get('account.account').search([('code', '=', account_code)])[0]
847
            data = {
848
                'name': '%s %s' % (j_type, self.db.name),
849
                'code': '%s%s' % (j_type, self.db.name[-2:]),
850
                'type': j_type,
116 by jf
[FIX]
851
                'currency': self.db.get('res.currency').search([('name', '=', 'EUR')])[0],
114 by jf
Create ESC partner + registers
852
                'default_credit_account_id': account_id,
853
                'default_debit_account_id': account_id,
854
            }
118 by jftempo
Mkdb: set analityc journal on liquidity journals
855
            get_ana = self.db.get('account.journal').onchange_type(False, j_type, False)
856
            data['analytic_journal_id'] = get_ana.get('value', {}).get('analytic_journal_id', False)
114 by jf
Create ESC partner + registers
857
            if j_type == 'cheque':
858
                if not reg.get('bank'):
859
                    continue
860
                data['bank_journal_id'] = reg['bank']
861
862
            reg[j_type] = self.db.get('account.journal').create(data)
863
119 by jftempo
Create locations Ext/Int CU
864
    def test_95_create_stock_cu(self):
865
        if isinstance(self, hqn_creation):
866
            return True
867
868
        stock_wiz = self.db.get('stock.location.configuration.wizard')
869
        w_id = stock_wiz.create({'location_usage': 'consumption_unit', 'location_type': 'internal', 'location_name': 'IntCU'})
870
        stock_wiz.confirm_creation(w_id)
871
        w_id = stock_wiz.create({'location_usage': 'consumption_unit', 'location_type': 'customer', 'location_name': 'ExtCU'})
872
        stock_wiz.confirm_creation(w_id)
114 by jf
Create ESC partner + registers
873
91.1.1 by jftempo
[IMP] Dump/restore: don't load file in memory + add sync menu shortcuts
874
    def test_99_add_shortcut(self):
875
        self.db.connect('admin')
876
        menu_to_add = ['sync_client.sync_wiz_menu', 'sync_client.sync_monitor_menu']
877
        for menu in menu_to_add:
878
            module, xml = menu.split('.')
879
            menu_id = self.db.get('ir.model.data').get_object_reference(module, xml)[1]
880
            menu_name = self.db.get('ir.ui.menu').name_get([menu_id])[0][1]
881
            try:
882
                self.db.get('ir.ui.view_sc').create({'res_id': menu_id, 'name': menu_name})
883
            except:
884
                raise
55 by duy.vo at msf
Moved open period to the end
885
103 by jftempo
[IMP] Instances setup
886
    @unittest.skipIf(skipSync, "Synchronization desactivated")
887
    def test_99_synchronize(self):
888
        self.db.connect('admin')
889
        self.sync()
890
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
891
# Replicable class to create hq n
892
class hqn_creation(client_creation, unittest.TestCase):
79 by jf
[IMP] Tree structure
893
    name_format = "%(db)s_HQ%(ind)d"
1 by Samus CTO
[INIT]
894
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
895
    @unittest.skipIf(skipGroups, "Group creation desactivated")
896
    def test_30_make_groups_coordo(self):
45 by Matthieu Dietrich
UTP-754: [FIX] group COORDINATIONS must have HQ as well
897
        self.add_to_group('Coordinations of %s' % self.db.name, 'COORDINATIONS')
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
898
        self.add_to_group('OC_%02d' % self.index, 'OC')
44 by Matthieu Dietrich
added new group 'mission + HQ'
899
        for i in range(1, coordo_count+1):
87.1.3 by jf
[IMP] Sync group name to manage HQ2
900
            self.add_to_group('HQ%s + Mission %s' % (self.index, i), 'HQ + MISSION')
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
901
3 by Samus CTO
[IMP] Add prefix, version in config; shortname and name in db classes; clean up + [IMP] Create msf_instance for each instance created
902
    @unittest.skipIf(skipPropInstance, "Proprietary Instance creation desactivated")
903
    def test_40_prop_instance(self):
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
904
        self.db.connect('admin')
905
        if self.db.search_data('msf.instance', [('instance','=',self.db.name)]):
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
906
            self.skipTest("Proprietary Instance already exists")
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
907
        self.make_prop_instance(self.db, {
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
908
            'level' : 'section',
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
909
            'reconcile_prefix' : self.prefix,
910
            'move_prefix' : self.prefix,
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
911
        })
3 by Samus CTO
[IMP] Add prefix, version in config; shortname and name in db classes; clean up + [IMP] Create msf_instance for each instance created
912
1 by Samus CTO
[INIT]
913
    @unittest.skipIf(skipConfig, "Modules configuration desactivated")
3 by Samus CTO
[IMP] Add prefix, version in config; shortname and name in db classes; clean up + [IMP] Create msf_instance for each instance created
914
    def test_41_configuration_wizards(self):
1 by Samus CTO
[INIT]
915
        self.db.connect('admin')
916
        self.configure()
917
11 by duy.vo at msf
SP-48: changed the order of tasks in HQ
918
    @unittest.skipIf(skipModuleData, "Data module installation desactivated")
919
    def test_42_install_data_client(self):
920
        self.db.connect('admin')
87.1.1 by jf
[IMP] Add config to load translations
921
        if hasattr(config, 'load_hq_data') and config.load_hq_data:
922
            for filename in config.load_hq_data:
923
                self.import_csv(filename)
924
        else:
925
            self.db.module('msf_sync_data_hq').install().do().set_notinstalled()
98.1.3 by jftempo
[IMP] Intersection: create unidata poduct
926
        # duplicate as UniData
927
        if hq_count > 1:
928
            data = [
929
                'DORADIDA15T',
930
                'DINJCEFA1V-',
931
                'ADAPCABL1S-',
932
                'ADAPCABL2S-',
933
                'ADAPCART02-',
934
            ]
935
            prod = self.db.get('product.product')
98.1.4 by jftempo
[FIX] UD Product
936
            unidata_id = self.db.get('ir.model.data').get_object_reference('product_attributes', 'int_6')[1]
98.1.3 by jftempo
[IMP] Intersection: create unidata poduct
937
            msfid = 100
938
            for code in data:
939
                p_id = prod.search([('default_code', '=', code)])
940
                if p_id:
941
                    newcode = 'HQ%s%s' % (self.index, code)
98.1.4 by jftempo
[FIX] UD Product
942
                    copy_id = prod.copy(p_id[0], {'default_code': newcode, 'international_status': unidata_id, 'msfid': msfid})
943
                    prod.write([copy_id], {'name': newcode})
98.1.3 by jftempo
[IMP] Intersection: create unidata poduct
944
                msfid += 10
87.1.1 by jf
[IMP] Add config to load translations
945
102 by jftempo
[IMP] load fx rates
946
    def test_41_load_rates(self):
947
        cur_dir = os.path.dirname(os.path.realpath(__file__))
137.1.1 by Mallory MARCOT
can now select currency for each HQ
948
949
        cur_to_load = config.default_currency
950
        db_level_name = self.db.name.split('_')[-1] # e.g 'HQ1'
951
        if hasattr(config, 'currency_tree') and config.currency_tree.get(db_level_name, False):
952
            cur_to_load = config.currency_tree[db_level_name]
953
954
        rate_file = os.path.join(cur_dir, 'data', '%s.txt' % cur_to_load)
102 by jftempo
[IMP] load fx rates
955
        if os.path.isfile(rate_file):
956
            rate_obj = self.db.get('res.currency')
957
            fx_rate_obj = self.db.get('res.currency.rate')
958
            rate_ids = rate_obj.search([('active', 'in', ['t', 'f'])])
959
            rate_dict = {}
960
            for x in rate_obj.read(rate_ids, ['name']):
961
                rate_dict[x['name']] = x['id']
137.1.1 by Mallory MARCOT
can now select currency for each HQ
962
            fx_rate_obj.create({'currency_id': rate_dict[cur_to_load.upper()], 'rate': 1, 'name': '2016-01-01'})
102 by jftempo
[IMP] load fx rates
963
            f = open(rate_file, 'r')
964
            date = False
965
            for data in f:
966
                data = data.rstrip()
967
                if data[0] != ' ':
968
                    date = data
969
                elif data[0] == ' ' and ':' in data:
970
                    cur, rate = data[1:].split(':')
971
                    if date and rate_dict.get(cur):
972
                        fx_rate_obj.create({'currency_id': rate_dict[cur], 'rate': rate, 'name': date})
973
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
974
    @unittest.skipIf(skipManualConfig, "Manual link on analytic account destination desactivated")
975
    def test_43_manual_link_on_analytic_account_destination(self):
976
        self.db.connect('admin')
81.1.1 by jf
Master data: New Coa
977
        # new CoA (2014-02-20)
81.1.2 by jf
Tab vs space
978
        link_ids = self.db.search_data('account.destination.link', [])
979
        if not link_ids:
980
            account_ids = self.db.search_data('account.account', [('type','!=','view'),('user_type.code','=','expense')])
981
            analytic_account_ids = self.db.search_data('account.analytic.account', [('name', 'in', ['Expatriates','National Staff','Operations','Support'])])
982
            self.db.write('account.analytic.account',  analytic_account_ids, {'destination_ids': [(6, 0, account_ids)]})
11 by duy.vo at msf
SP-48: changed the order of tasks in HQ
983
17 by Samus CTO
[IMP] Note + skip some tests by command line
984
87.1.1 by jf
[IMP] Add config to load translations
985
    @unittest.skipIf(skipLoadExtraFiles, "Load Extra Data Files desactivated")
986
    def test_46_load_extra_data_files(self):
987
        if not hasattr(config, 'load_extra_files') or not config.load_extra_files:
988
            return
989
990
        for filename in config.load_extra_files:
123 by jftempo
Load user rights from unifield-server/bin/addons/msf_profile/user_rights
991
            self.import_csv(get_file_from_source(filename))
87.1.1 by jf
[IMP] Add config to load translations
992
993
    @unittest.skipIf(skipLoadUACFile, "Load UAC File desactivated")
994
    def test_45_load_uac_file(self):
995
        if not hasattr(config, 'load_uac_file') or not config.load_uac_file:
996
            return
997
998
        self.db.connect('admin')
999
123 by jftempo
Load user rights from unifield-server/bin/addons/msf_profile/user_rights
1000
        f = open(get_file_from_source(config.load_uac_file))
87.1.1 by jf
[IMP] Add config to load translations
1001
        data = base64.encodestring(f.read())
1002
        f.close()
1003
1004
        wiz = self.db.get('user.access.configurator')
1005
        rec_id = wiz.create({'file_to_import_uac': data})
1006
        try:
1007
            wiz.do_process_uac([rec_id])
1008
        except:
1009
            pass
1010
115 by jf
Intersection parnters @hq
1011
    def test_70_create_intersection(self):
1012
        partner = self.db.get('res.partner')
1013
        account = self.db.get('account.account')
1014
        for tc in test_cases:
1015
            if (issubclass(tc, coordon_creation) or issubclass(tc, projectn_creation)) and tc.hq.index != self.index:
1016
                if tc.db is None:
1017
                    db_name = tc.name_format % tc.getNameFormat()
1018
                else:
1019
                    db_name = tc.db.name
1020
                partner.create({
1021
                    'name': db_name,
1022
                    'partner_type': 'section',
1023
                    'po_by_project': 'project',
1024
                    'customer': True,
1025
                    'supplier': True,
1026
                    'property_account_payable':  account.search([('code','=','30010')])[0],
1027
                    'property_account_receivable': account.search([('code','=','12010')])[0],
1028
                    'city': 'XXX',
1029
                })
1030
114 by jf
Create ESC partner + registers
1031
    def test_99_create_esc(self):
1032
        account = self.db.get('account.account')
1033
        self.db.get('res.partner').create({
1034
            'name': 'ESC',
117 by jftempo
Fx Rates
1035
            'partner_type': 'esc',
1036
            'po_by_project': 'project',
1037
            'supplier': True,
1038
            'customer': False,
1039
            'property_account_payable':  account.search([('code','=','30010')])[0],
1040
            'property_account_receivable': account.search([('code','=','12050')])[0],
1041
            'city': 'XXX',
114 by jf
Create ESC partner + registers
1042
        })
87.1.1 by jf
[IMP] Add config to load translations
1043
115 by jf
Intersection parnters @hq
1044
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
1045
# Replicable class to create coordo n
1046
class coordon_creation(client_creation):
79 by jf
[IMP] Tree structure
1047
    name_format = "%(db)s_HQ%(pind)dC%(ind)d"
1 by Samus CTO
[INIT]
1048
5 by Samus CTO
[IMP] Better installation
1049
    @unittest.skipIf(skipGroups, "Group creation desactivated")
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
1050
    def test_30_make_groups_coordo(self):
1051
        self.add_to_group('OC_%02d' % self.hq.index, 'OC')
36 by Matthieu Dietrich
[FIX] changed group types to be searched/created, to avoid conflicts with rules
1052
        self.add_to_group('Coordinations of %s' % self.hq.db.name, 'COORDINATIONS')
87.1.3 by jf
[IMP] Sync group name to manage HQ2
1053
        self.add_to_group('Mission %s-%s' % (self.hq.index, self.index), 'MISSION')
1054
        self.add_to_group('HQ%s + Mission %s' % (self.hq.index, self.index), 'HQ + MISSION')
2 by Samus CTO
[FIX] msf_sync_data_* enabled
1055
3 by Samus CTO
[IMP] Add prefix, version in config; shortname and name in db classes; clean up + [IMP] Create msf_instance for each instance created
1056
    @unittest.skipIf(skipPropInstance, "Proprietary Instance creation desactivated")
1057
    def test_40_prop_instance(self):
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
1058
        self.hq.db.connect('admin')
1059
        if self.hq.db.search_data('msf.instance', [('instance','=',self.db.name)]):
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
1060
            self.skipTest("Proprietary Instance already exists")
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
1061
        self.make_prop_instance(self.hq.db, {
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
1062
            'level' : 'coordo',
1063
            'reconcile_prefix' : self.prefix,
1064
            'move_prefix' : self.prefix,
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
1065
            'parent_id' : self.hq.db.search_data('msf.instance', [('instance','=',self.hq.db.name)])[0],
1066
        }, self.hq)
3 by Samus CTO
[IMP] Add prefix, version in config; shortname and name in db classes; clean up + [IMP] Create msf_instance for each instance created
1067
1068
    @unittest.skipIf(skipConfig, "Modules configuration desactivated")
1069
    def test_60_configuration_wizards(self):
1070
        self.db.connect('admin')
1071
        self.configure()
1072
5 by Samus CTO
[IMP] Better installation
1073
    @unittest.skipIf(skipModuleData, "Data module installation desactivated")
1074
    def test_61_install_data_client(self):
1075
        self.db.connect('admin')
87.1.1 by jf
[IMP] Add config to load translations
1076
        self.db.module('msf_sync_data_coordo').install().do().set_notinstalled()
122 by jf
Activate ESC partner on Coordo
1077
        partner_obj = self.db.get('res.partner')
1078
        p_ids = partner_obj.search([('name', '=', 'ESC'), ('active', '=', False)])
1079
        if p_ids:
1080
            partner_obj.write(p_ids, {'active': True})
5 by Samus CTO
[IMP] Better installation
1081
17 by Samus CTO
[IMP] Note + skip some tests by command line
1082
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
1083
# Replicable class to create project n
1084
class projectn_creation(client_creation):
79 by jf
[IMP] Tree structure
1085
    name_format = "%(db)s_HQ%(ppind)dC%(pind)dP%(ind)d"
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
1086
21 by Samus CTO
[FIX] prop instance and cost center for test cases and from hq_data + [FIX] self.db.db_name to self.db.name to avoid connection error + [IMP] Added finance.py test + [FIX] use groups of hq_data + [IMP] remove shortname and version
1087
    @unittest.skipIf(skipGroups, "Group creation desactivated")
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
1088
    def test_30_make_groups_coordo(self):
1089
        self.add_to_group('OC_%02d' % self.hq.index, 'OC')
87.1.3 by jf
[IMP] Sync group name to manage HQ2
1090
        self.add_to_group('Mission %s-%s' % (self.hq.index, self.parent.index), 'MISSION')
1091
        self.add_to_group('HQ%s + Mission %s' % (self.hq.index, self.parent.index), 'HQ + MISSION')
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
1092
1093
    @unittest.skipIf(skipGroups, "Group creation desactivated")
21 by Samus CTO
[FIX] prop instance and cost center for test cases and from hq_data + [FIX] self.db.db_name to self.db.name to avoid connection error + [IMP] Added finance.py test + [FIX] use groups of hq_data + [IMP] remove shortname and version
1094
    def test_31_make_groups_project(self):
1095
        Synchro.connect('admin')
1096
        entity_ids = Synchro.get('sync.server.entity').search([('name','=',self.db.name)])
1097
        # Add entity to groups
1098
        group = Synchro.get('sync.server.entity_group')
1099
        group.write(group.search([('name','=','Mission1')]), {
1100
            'entity_ids' : [(4,entity_ids[0])],
1101
        })
1102
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
1103
    @unittest.skipIf(skipPropInstance, "Proprietary Instance creation desactivated")
1104
    def test_40_prop_instance(self):
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
1105
        self.hq.db.connect('admin')
1106
        if self.hq.db.search_data('msf.instance', [('instance','=',self.db.name)]):
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
1107
            self.skipTest("Proprietary Instance already exists")
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
1108
        self.make_prop_instance(self.hq.db, {
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
1109
            'level' : 'project',
1110
            'reconcile_prefix' : self.prefix,
1111
            'move_prefix' : self.prefix,
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
1112
            'parent_id' : self.hq.db.search_data('msf.instance', [('instance','=',self.parent_name)])[0],
1113
        }, self.parent)
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
1114
3 by Samus CTO
[IMP] Add prefix, version in config; shortname and name in db classes; clean up + [IMP] Create msf_instance for each instance created
1115
    @unittest.skipIf(skipConfig, "Modules configuration desactivated")
1116
    def test_60_configuration_wizards(self):
1117
        self.db.connect('admin')
1118
        self.configure()
1119
17 by Samus CTO
[IMP] Note + skip some tests by command line
1120
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
1121
class verbose(unittest.TestCase):
79 by jf
[IMP] Tree structure
1122
    def test_10_show_dbs(self):
57 by Cecile Tonglet
[FIX] Version problem with openerplib
1123
        warn("\n"+"-" * 40)
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
1124
        for tc_hq in filter(lambda tc:issubclass(tc, hqn_creation), test_cases):
79 by jf
[IMP] Tree structure
1125
            warn( " * %s" % hqn_creation.name_format % tc_hq.getNameFormat())
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
1126
            for tc in filter(lambda tc:issubclass(tc, coordon_creation) \
106 by jf
US-1610 New OC field on groups / instances
1127
                             and tc.parent is tc_hq, test_cases):
79 by jf
[IMP] Tree structure
1128
                warn( "    - %s" % coordon_creation.name_format % tc.getNameFormat())
1129
                for tp in filter(lambda tp:issubclass(tp, projectn_creation) \
106 by jf
US-1610 New OC field on groups / instances
1130
                                 and tp.parent is tc, test_cases):
79 by jf
[IMP] Tree structure
1131
                    warn( "        + %s" % projectn_creation.name_format % tp.getNameFormat())
57 by Cecile Tonglet
[FIX] Version problem with openerplib
1132
            warn("-" * 40)
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
1133
1134
1135
17 by Samus CTO
[IMP] Note + skip some tests by command line
1136
# Base Install
67 by jf
[IMP] New test to update branches
1137
test_cases = [verbose, update_branches, server_creation]
31.1.1 by Samus CTO
[IMP] Multi-creation of HQ instances (problem with multiple HQ and msf.instance and missing cost center)
1138
1139
# Create HQ classes
103 by jftempo
[IMP] Instances setup
1140
if not hasattr(config, 'instance_tree') or not config.instance_tree:
1141
    config.instance_tree = {}
1142
    for i in range(1, hq_count+1):
1143
        config.instance_tree['HQ%d'%i] = {}
1144
        for ci in range(1, coordo_count+1):
1145
            config.instance_tree['HQ%d'%i]['C%d'%ci] = []
1146
            for pi in range(1, project_count+1):
1147
                config.instance_tree['HQ%d'%i]['C%d'%ci].append('P%d'%pi)
1148
else:
1149
    hq_count = len(config.instance_tree.keys())
1150
    coordo_count = max([len(x.values()) for x in config.instance_tree.values()])
1151
1152
hq_index = 0
1153
for hq, coordos in config.instance_tree.iteritems():
1154
    hq_index += 1
1155
    test_cases.append( type("HQ%d_creation" % hq_index, (hqn_creation,unittest.TestCase), {
1156
        'prefix' : 'HQ%s'%hq_index,
1157
        'index' : hq_index,
79 by jf
[IMP] Tree structure
1158
    }) )
1159
    # Make testcase visible for importation
1160
    globals()[test_cases[-1].__name__] = test_cases[-1]
1161
103 by jftempo
[IMP] Instances setup
1162
    coordo_index = 0
79 by jf
[IMP] Tree structure
1163
    # Create Coordo classes
103 by jftempo
[IMP] Instances setup
1164
    for coordo in sorted(coordos.keys()):
1165
        coordo_index += 1
1166
        test_cases.append( type("HQ%d_C%d_creation" % (hq_index, coordo_index), (coordon_creation,unittest.TestCase), {
1167
            'prefix' : 'C%s%s' % (hq_index, coordo_index),
1168
            'index' : coordo_index,
1169
            'parent' : globals()["HQ%d_creation" % hq_index],
79 by jf
[IMP] Tree structure
1170
        }) )
1171
        test_cases[-1].hq = test_cases[-1].parent
1172
        # Make testcase visible for importation
1173
        globals()[test_cases[-1].__name__] = test_cases[-1]
1174
103 by jftempo
[IMP] Instances setup
1175
        project_index = 0
79 by jf
[IMP] Tree structure
1176
        # Create Project classes
103 by jftempo
[IMP] Instances setup
1177
        for pi in coordos[coordo]:
1178
            project_index += 1
1179
            test_cases.append( type("HQ%d_C%d_P%d_creation" % (hq_index, coordo_index, project_index), (projectn_creation,unittest.TestCase), {
1180
                'prefix' : 'P%s%s%s'%(hq_index, coordo_index, project_index),
1181
                'index' : project_index,
1182
                'parent' : globals()["HQ%d_C%d_creation" % (hq_index, coordo_index)],
79 by jf
[IMP] Tree structure
1183
            }) )
1184
            test_cases[-1].hq = test_cases[-1].parent.parent
1185
            # Make testcase visible for importation
1186
            globals()[test_cases[-1].__name__] = test_cases[-1]
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
1187
1 by Samus CTO
[INIT]
1188
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
1189
# Push last_sync test at last
74 by jf
[IMP] dump db @the end
1190
test_cases.append(last_sync)
1191
126 by jf
MKDB: activate inter partners
1192
# activate inter partners
1193
test_cases.append(activate_inter_partner)
1194
74 by jf
[IMP] dump db @the end
1195
# and dump
1196
test_cases.append(dump_all)
31.1.3 by Samus CTO
[IMP] Fix groups creation for mkdb + [IMP] Last sync based on runned test cases
1197
1198
1 by Samus CTO
[INIT]
1199
def load_tests(loader, tests, pattern):
1200
    suite = unittest.TestSuite()
1201
    for test_class in test_cases:
1202
        tests = loader.loadTestsFromTestCase(test_class)
1203
        suite.addTests(tests)
1204
    return suite
1205
22 by Samus CTO
[IMP] Multiple creation of databases (see the documentation of the module)
1206
1 by Samus CTO
[INIT]
1207
if __name__ == '__main__':
67 by jf
[IMP] New test to update branches
1208
    if o.log_to_file:
1209
        if not os.path.exists(dir_to_dump):
1210
            os.makedirs(dir_to_dump)
78 by jf
[FIX] mkdb log filename
1211
        f = open(os.path.join(dir_to_dump, 'script_result.log'), "w")
67 by jf
[IMP] New test to update branches
1212
        stream = f
1213
    else:
1214
        stream = sys.stderr
1215
    unittest.main(testRunner=unittest.TextTestRunner(stream,failfast=True, verbosity=2))
1216
    if o.log_to_file:
1217
        f.close()