Robot Framework Integrated Development Environment (RIDE)
etreewrapper.py
Go to the documentation of this file.
1 # Copyright 2008-2015 Nokia Networks
2 # Copyright 2016- Robot Framework Foundation
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 
16 from io import BytesIO
17 
18 from .compat import py2to3
19 from .platform import IRONPYTHON, PY_VERSION
20 from .robottypes import is_string
21 
22 
23 IRONPYTHON_WITH_BROKEN_ETREE = IRONPYTHON and PY_VERSION < (2, 7, 9)
24 NO_ETREE_ERROR = 'No valid ElementTree XML parser module found'
25 
26 
27 if not IRONPYTHON_WITH_BROKEN_ETREE:
28  try:
29  from xml.etree import cElementTree as ET
30  except ImportError:
31  try:
32  from xml.etree import ElementTree as ET
33  except ImportError:
34  raise ImportError(NO_ETREE_ERROR)
35 else:
36  # Standard ElementTree works only with IronPython 2.7.9+
37  # https://github.com/IronLanguages/ironpython2/issues/370
38  try:
39  from elementtree import ElementTree as ET
40  except ImportError:
41  raise ImportError(NO_ETREE_ERROR)
42  from StringIO import StringIO
43 
44 
45 # cElementTree.VERSION seems to always be 1.0.6. We want real API version.
46 if ET.VERSION < '1.3' and hasattr(ET, 'tostringlist'):
47  ET.VERSION = '1.3'
48 
49 
50 @py2to3
51 class ETSource():
52 
53  def __init__(self, source):
54  self._source_source = source
55  self._opened_opened = None
56 
57  def __enter__(self):
58  self._opened_opened = self._open_source_if_necessary_open_source_if_necessary()
59  return self._opened_opened or self._source_source
60 
61  def __exit__(self, exc_type, exc_value, exc_trace):
62  if self._opened_opened:
63  self._opened_opened.close()
64 
65  def __unicode__(self):
66  if self._source_is_file_name_source_is_file_name():
67  return self._source_source
68  if hasattr(self._source_source, 'name'):
69  return self._source_source.name
70  return '<in-memory file>'
71 
73  return is_string(self._source_source) \
74  and not self._source_source.lstrip().startswith('<')
75 
77  if self._source_is_file_name_source_is_file_name() or not is_string(self._source_source):
78  return None
79  if IRONPYTHON_WITH_BROKEN_ETREE:
80  return StringIO(self._source_source)
81  return BytesIO(self._source_source.encode('UTF-8'))
def __exit__(self, exc_type, exc_value, exc_trace)
Definition: etreewrapper.py:61