blob: 5c389cf9da4d07049d4484c8cdcc32a0ae9f233a [file] [log] [blame]
Scott Bakerbba67b62019-01-28 17:38:21 -08001# Copyright 2017-present Open Networking Foundation
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import os
16import cPickle
17import subprocess
18
19"""
20 Support for autogenerating mock_modelaccessor.
21
22 Each unit test might have its own requirements for the set of xprotos that make
23 up its model testing framework. These should always include the core, and
24 optionally include one or more services.
25"""
26
27
28def build_mock_modelaccessor(
29 dest_dir, xos_dir, services_dir, service_xprotos, target="mock_classes.xtarget"
30):
31 dest_fn = os.path.join(dest_dir, "mock_modelaccessor.py")
32
33 args = ["xosgenx", "--target", target]
34 args.append(os.path.join(xos_dir, "core/models/core.xproto"))
35 for xproto in service_xprotos:
36 args.append(os.path.join(services_dir, xproto))
37
38 # Check to see if we've already run xosgenx. If so, don't run it again.
39 context_fn = dest_fn + ".context"
40 this_context = (xos_dir, services_dir, service_xprotos, target)
41 need_xosgenx = True
42 if os.path.exists(context_fn):
43 try:
44 context = cPickle.loads(open(context_fn).read())
45 if context == this_context:
46 return
47 except (cPickle.UnpicklingError, EOFError):
48 # Something went wrong with the file read or depickling
49 pass
50
51 if os.path.exists(context_fn):
52 os.remove(context_fn)
53
54 if os.path.exists(dest_fn):
55 os.remove(dest_fn)
56
57 p = subprocess.Popen(
58 " ".join(args) + " > " + dest_fn,
59 shell=True,
60 stdout=subprocess.PIPE,
61 stderr=subprocess.STDOUT,
62 )
63 (stdoutdata, stderrdata) = p.communicate()
64 if (p.returncode != 0) or (not os.path.exists(dest_fn)):
65 raise Exception(
66 "Failed to create mock model accessor, returncode=%d, stdout=%s"
67 % (p.returncode, stdoutdata)
68 )
69
70 # Save the context of this invocation of xosgenx
71 open(context_fn, "w").write(cPickle.dumps(this_context))