def test_invalidinteger(self):
self.assertRaises(ValueError, plistlib.loads,
b"<plist><integer>not integer</integer></plist>")
python类loads()的实例源码
def test_invalidreal(self):
self.assertRaises(ValueError, plistlib.loads,
b"<plist><integer>not real</integer></plist>")
def test_nonstandard_refs_size(self):
# Issue #21538: Refs and offsets are 24-bit integers
data = (b'bplist00'
b'\xd1\x00\x00\x01\x00\x00\x02QaQb'
b'\x00\x00\x08\x00\x00\x0f\x00\x00\x11'
b'\x00\x00\x00\x00\x00\x00'
b'\x03\x03'
b'\x00\x00\x00\x00\x00\x00\x00\x03'
b'\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x00\x00\x00\x00\x00\x00\x13')
self.assertEqual(plistlib.loads(data), {'a': 'b'})
def get_model():
"""Obtain's the user's Mac model"""
# Obtain and parse the output of the system profiler command
try:
hardware_type_xml = run([
'system_profiler', 'SPHardwareDataType', '-xml'
])
except CampiesSubprocessError:
raise CampiesError(
'Unable to run the command required to obtain the model'
)
try:
hardware_type = loads_plist(hardware_type_xml)
except xml.parsers.expat.ExpatError:
raise CampiesError(
'Unable to parse hardware XML to obtain the model'
)
# We now need to grab the machine model which is buried in the data
# [{
# '_items': [
# {
# '_name': 'hardware_overview',
# 'machine_model': 'MacBookPro11,5',
# 'machine_name': 'MacBook Pro',
try:
model = hardware_type[0]['_items'][0]['machine_model']
except IndexError:
raise CampiesError(
'Unable to find model in the hardware XML'
)
return model
def _wait_for_media_to_end(self, session):
address = self._url(self.port, 'playback-info')
play_state = const.PLAY_STATE_LOADING
while True:
info = None
try:
info = yield from session.get(address)
data = yield from info.content.read()
parsed = plistlib.loads(data)
if play_state == const.PLAY_STATE_LOADING:
if 'duration' in parsed:
play_state = const.PLAY_STATE_PLAYING
elif 'readyToPlay' not in parsed:
play_state = const.PLAY_STATE_NO_MEDIA
break
elif play_state == const.PLAY_STATE_PLAYING:
if 'duration' not in parsed:
play_state = const.PLAY_STATE_NO_MEDIA
break
finally:
if info is not None:
info.close()
yield from asyncio.sleep(1, loop=self.loop)
def read_bplist(data, start, length):
"""Extract a binary plist from a position in a sequence."""
# TODO: pylint doesn't find FMT_BINARY, why?
# pylint: disable=no-member
return plistlib.loads(data[start:start+length],
fmt=plistlib.FMT_BINARY)
# pylint: disable=unused-argument
def readPlist(pathOrFile):
"""Raises NotBinaryPlistException, InvalidPlistException"""
didOpen = False
result = None
if isinstance(pathOrFile, (bytes, unicode)):
pathOrFile = open(pathOrFile, 'rb')
didOpen = True
try:
reader = PlistReader(pathOrFile)
result = reader.parse()
except NotBinaryPlistException as e:
try:
pathOrFile.seek(0)
result = None
if hasattr(plistlib, 'loads'):
contents = None
if isinstance(pathOrFile, (bytes, unicode)):
with open(pathOrFile, 'rb') as f:
contents = f.read()
else:
contents = pathOrFile.read()
result = plistlib.loads(contents)
else:
result = plistlib.readPlist(pathOrFile)
result = wrapDataObject(result, for_binary=True)
except Exception as e:
raise InvalidPlistException(e)
finally:
if didOpen:
pathOrFile.close()
return result
def test_bytes(self):
pl = self._create()
data = plistlib.dumps(pl)
pl2 = plistlib.loads(data)
self.assertNotIsInstance(pl, plistlib._InternalDict)
self.assertEqual(dict(pl), dict(pl2))
data2 = plistlib.dumps(pl2)
self.assertEqual(data, data2)
def test_indentation_array(self):
data = [[[[[[[[{'test': b'aaaaaa'}]]]]]]]]
self.assertEqual(plistlib.loads(plistlib.dumps(data)), data)
def test_indentation_dict(self):
data = {'1': {'2': {'3': {'4': {'5': {'6': {'7': {'8': {'9': b'aaaaaa'}}}}}}}}}
self.assertEqual(plistlib.loads(plistlib.dumps(data)), data)
def test_indentation_dict_mix(self):
data = {'1': {'2': [{'3': [[[[[{'test': b'aaaaaa'}]]]]]}]}}
self.assertEqual(plistlib.loads(plistlib.dumps(data)), data)
def test_appleformattingfromliteral(self):
self.maxDiff = None
for fmt in ALL_FORMATS:
with self.subTest(fmt=fmt):
pl = self._create(fmt=fmt)
pl2 = plistlib.loads(TESTDATA[fmt], fmt=fmt)
self.assertEqual(dict(pl), dict(pl2),
"generated data was not identical to Apple's output")
pl2 = plistlib.loads(TESTDATA[fmt])
self.assertEqual(dict(pl), dict(pl2),
"generated data was not identical to Apple's output")
def test_nondictroot(self):
for fmt in ALL_FORMATS:
with self.subTest(fmt=fmt):
test1 = "abc"
test2 = [1, 2, 3, "abc"]
result1 = plistlib.loads(plistlib.dumps(test1, fmt=fmt))
result2 = plistlib.loads(plistlib.dumps(test2, fmt=fmt))
self.assertEqual(test1, result1)
self.assertEqual(test2, result2)
def test_invalidarray(self):
for i in ["<key>key inside an array</key>",
"<key>key inside an array2</key><real>3</real>",
"<true/><key>key inside an array3</key>"]:
self.assertRaises(ValueError, plistlib.loads,
("<plist><array>%s</array></plist>"%i).encode())
def test_invaliddict(self):
for i in ["<key><true/>k</key><string>compound key</string>",
"<key>single key</key>",
"<string>missing key</string>",
"<key>k1</key><string>v1</string><real>5.3</real>"
"<key>k1</key><key>k2</key><string>double key</string>"]:
self.assertRaises(ValueError, plistlib.loads,
("<plist><dict>%s</dict></plist>"%i).encode())
self.assertRaises(ValueError, plistlib.loads,
("<plist><array><dict>%s</dict></array></plist>"%i).encode())
def test_invalidinteger(self):
self.assertRaises(ValueError, plistlib.loads,
b"<plist><integer>not integer</integer></plist>")
def test_invalidreal(self):
self.assertRaises(ValueError, plistlib.loads,
b"<plist><integer>not real</integer></plist>")
def test_nonstandard_refs_size(self):
# Issue #21538: Refs and offsets are 24-bit integers
data = (b'bplist00'
b'\xd1\x00\x00\x01\x00\x00\x02QaQb'
b'\x00\x00\x08\x00\x00\x0f\x00\x00\x11'
b'\x00\x00\x00\x00\x00\x00'
b'\x03\x03'
b'\x00\x00\x00\x00\x00\x00\x00\x03'
b'\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x00\x00\x00\x00\x00\x00\x13')
self.assertEqual(plistlib.loads(data), {'a': 'b'})
def __ipa_parse(file_path: str):
"""
??ipa?
:param file_path: ipa??
:return: PackageParse
"""
ipa_file = ZipFile(file_path)
# ??info.plist??
ns = [n for n in ipa_file.namelist() if Regex.IPAInfoPlistPath.match(n)]
if not ns:
log.warning('parse info.plist failure: {}'.format(file_path))
return
plist_path = ns[-1]
# ??plist
plist_data = ipa_file.read(plist_path)
plist_file = plistlib.loads(plist_data)
# ??icon'CFBundleIconFiles' (4400546488)
if plist_file.get('CFBundleIconFiles'):
icon_name = plist_file['CFBundleIconFiles'][-1]
else:
if plist_file.get('CFBundleIcons'):
icon_dict = plist_file['CFBundleIcons']
elif plist_file.get('CFBundleIcons'):
icon_dict = plist_file['CFBundleIcons~ipad']
else:
log.warning('parse icon failure: {}'.format(file_path))
return
icon_name = icon_dict['CFBundlePrimaryIcon']['CFBundleIconFiles'][-1]
log.debug('parse icon name: {}'.format(icon_name))
# ??icon??
re_icon_name_end = '(@\dx)\.png' if not icon_name.endswith('.png') else ''
re_icon_name = re.compile('([^/]+/){{2}}{}{}'.format(icon_name, re_icon_name_end))
ns = [n for n in ipa_file.namelist() if re_icon_name.match(n)]
if not ns:
log.warning('read icon failure: {}'.format(file_path))
return
icon_path = ns[-1]
log.debug('parse icon path: {}'.format(icon_path))
# ???
version_number = plist_file['CFBundleShortVersionString']
# build?
build_number = plist_file['CFBundleVersion']
# ??
package_name = plist_file['CFBundleIdentifier']
# app??
app_name = plist_file['CFBundleDisplayName'] if plist_file.get('CFBundleDisplayName') else plist_file[
'CFBundleName']
log.debug(
'app: {}, V{} build {}, package: {}'.format(app_name, version_number, build_number, package_name))
return PackageParse(ipa_file, AppType.iOS, package_name, app_name, icon_path, version_number, build_number)