Merge lp:~camptocamp/oerpscenario/trunk-add_load-afe into lp:oerpscenario

Proposed by Alexandre Fayolle - camptocamp
Status: Needs review
Proposed branch: lp:~camptocamp/oerpscenario/trunk-add_load-afe
Merge into: lp:oerpscenario
Diff against target: 111 lines (+107/-0)
1 file modified
features/steps/load.py (+107/-0)
To merge this branch: bzr merge lp:~camptocamp/oerpscenario/trunk-add_load-afe
Reviewer Review Type Date Requested Status
Leonardo Pistone code review Needs Fixing
Review via email: mp+206372@code.launchpad.net

Description of the change

add @given('I load the data file "{filename}.csv" into the model "{model_name}"')
and @given('I load the data file "{filename}.yml"')

the yaml version can process images, which is useful for products.

To post a comment you must log in.
Revision history for this message
Leonardo Pistone (lepistone) wrote :

Thanks!

In fact, we already have a step to import csv files in tools.py, but your one is better, because you check the messages returned by load().

This would have saved me a headache, because load() does not raise on error, so it is important to check the return value.

I suggest you remove the old step in this branch.

review: Needs Fixing (code review)
Revision history for this message
Yannick Vaucher @ Camptocamp (yvaucher-c2c) wrote :

To port on github

Unmerged revisions

330. By Alexandre Fayolle - camptocamp

[ADD] phrases to load csv or yaml files. Yaml files support references to images

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
=== added file 'features/steps/load.py'
--- features/steps/load.py 1970-01-01 00:00:00 +0000
+++ features/steps/load.py 2014-02-14 09:50:19 +0000
@@ -0,0 +1,107 @@
1import csv
2import os
3import base64
4import yaml
5from support.tools import set_trace
6import openerp
7
8#---------
9#from openerp.tools import yaml_import
10
11class Image(openerp.tools.yaml_tag.YamlTag):
12 def __init__(self, path):
13 self.path = path
14 super(Image, self).__init__()
15
16 def __str__(self):
17 return '!image %r' % self.path
18
19
20class YamlInterpreter(openerp.tools.YamlInterpreter):
21 def __init__(self, ctx, *args, **kwargs):
22 self.ctx=ctx
23 return super(YamlInterpreter,self).__init__(*args,**kwargs)
24
25 def process(self, yaml_string):
26 def image_constructor(loader, node):
27 expression = loader.construct_scalar(node)
28 return Image(expression)
29 yaml.add_constructor(u"!image", image_constructor)
30 return super(YamlInterpreter,self).process(yaml_string)
31
32 def process_image(self, node):
33 return base64.encodestring(_fileopen(self.ctx, node.path).read())
34
35 def _eval_field(self, cmodel, field_name, expression, view_info=False, parent=None, default=True):
36 # Allow to ref m2o with search criteria
37 # TODO : push as MP on server
38 if parent is None:
39 parent={}
40 if field_name in cmodel._columns:
41 column = cmodel._columns[field_name]
42 elif field_name in cmodel._inherit_fields:
43 column = cmodel._inherit_fields[field_name][2]
44 else:
45 raise KeyError("Object '%s' does not contain field '%s'" % (cmodel, field_name))
46 if column._type == "many2one":
47 if isinstance(expression,dict):
48 domain=[(k,'=',v) for k,v in expression.iteritems()]
49 return model(column._obj).search(domain)
50 elif isinstance(expression,Image):
51 return self.process_image(expression)
52 return super(YamlInterpreter,self)._eval_field(cmodel, field_name, expression, view_info=view_info, parent=parent, default=default)
53
54
55def yaml_import(ctx, cr, module_name, fp, kind, mode='init'):
56 idref = {}
57 yaml_interpreter = YamlInterpreter(ctx, cr, module_name, idref, mode='update', filename=fp.name)
58 yaml_interpreter.process(fp.read())
59
60
61def _fileopen(ctx, filename, mode='r'):
62 tmp_path = ctx.feature.filename.split(os.path.sep)
63 tmp_path = tmp_path[1: tmp_path.index('features')] + ['data', '%s'%filename]
64 tmp_path = [str(x) for x in tmp_path]
65 path = os.path.join('/', *tmp_path)
66 assert os.path.exists(path)
67 return open(path, mode)
68
69
70@given('I load the data file "{filename}.csv" into the model "{model_name}"')
71def impl(ctx, model_name, filename, sep=","):
72 data = csv.reader(_fileopen(ctx, '%s.csv'%filename, 'rb'), delimiter=str(sep))
73 head = []
74 skip = [] #skip columns that are not mapped
75 for index,field in enumerate(data.next()):
76 if field:
77 head.append(field)
78 else:
79 skip.append(index)
80 values=[]
81 for line in data:
82 values.append([field for index,field in enumerate(line) if index not in skip])
83 rewrite=[i for i,e in enumerate(head) if e=='id' or e.endswith('/id')]
84 if rewrite:
85 for line in iter(values):
86 for pos in rewrite:
87 if line[pos] and '.' not in line[pos]:
88 line[pos]='scenario.'+line[pos]
89 result = model(model_name).load(head, values)
90 has_errors = any(m for m in result['messages'] if m['type'] == 'error')
91 assert not has_errors, result
92
93
94
95@given('I load the data file "{filename}.yml"')
96def impl(ctx, filename):
97 openerp = ctx.conf['server']
98 db_name = ctx.conf['db_name']
99 pool = openerp.modules.registry.RegistryManager.get(db_name)
100 cr = pool.db.cursor()
101 module_name='scenario'
102 fp=_fileopen(ctx, '%s.yml'%filename)
103 try:
104 cr.autocommit(True)
105 yaml_import(ctx, cr, module_name, fp, 'data', mode='update')
106 finally:
107 cr.close()

Subscribers

People subscribed via source and target branches

to all changes: