Python: Make isSequence() and isMapping() tests version specific

Since unicode/bytes difference, output can't match between Python 2 and Python 3.
This commit is contained in:
Rasmus Wriedt Larsen
2020-06-10 16:43:56 +02:00
parent bacd491875
commit 48b2d2cc5c
8 changed files with 89 additions and 3 deletions

View File

@@ -0,0 +1,12 @@
| mapping | builtin-class collections.defaultdict |
| mapping | builtin-class dict |
| mapping | class MyDictSubclass |
| mapping | class MyMappingABC |
| mapping | class OrderedDict |
| neither sequence nor mapping | builtin-class set |
| sequence | builtin-class list |
| sequence | builtin-class str |
| sequence | builtin-class tuple |
| sequence | builtin-class unicode |
| sequence | class MySequenceABC |
| sequence | class MySequenceImpl |

View File

@@ -0,0 +1 @@
semmle-extractor-options: --lang=2 --max-import-depth=2

View File

@@ -1,13 +1,15 @@
from collections import OrderedDict, defaultdict
import collections.abc
# Python 2 specific
from collections import Sequence, Mapping
def test(*args):
pass
class MySequenceABC(collections.abc.Sequence):
class MySequenceABC(Sequence):
pass
class MyMappingABC(collections.abc.Mapping):
class MyMappingABC(Mapping):
pass
class MySequenceImpl(object):
@@ -24,6 +26,7 @@ test(
list,
tuple,
str,
unicode,
bytes,
MySequenceABC,
MySequenceImpl,

View File

@@ -0,0 +1,20 @@
import python
from ClassValue cls, string res
where
exists(CallNode call |
call.getFunction().(NameNode).getId() = "test" and
call.getAnArg().pointsTo(cls)
) and
(
cls.isSequence() and
cls.isMapping() and
res = "IS BOTH. SHOULD NOT HAPPEN. THEY ARE MUTUALLY EXCLUSIVE."
or
cls.isSequence() and not cls.isMapping() and res = "sequence"
or
not cls.isSequence() and cls.isMapping() and res = "mapping"
or
not cls.isSequence() and not cls.isMapping() and res = "neither sequence nor mapping"
)
select res, cls.toString()

View File

@@ -0,0 +1,50 @@
from collections import OrderedDict, defaultdict
# Python 3 specific
from collections.abc import Sequence, Mapping
def test(*args):
pass
class MySequenceABC(Sequence):
pass
class MyMappingABC(Mapping):
pass
class MySequenceImpl(object):
def __getitem__(self, key):
pass
def __len__(self):
pass
class MyDictSubclass(dict):
pass
test(
list,
tuple,
str,
unicode,
bytes,
MySequenceABC,
MySequenceImpl,
set,
dict,
OrderedDict,
defaultdict,
MyMappingABC,
MyDictSubclass,
)
for seq_cls in (list, tuple, str, bytes):
assert issubclass(seq_cls, collections.abc.Sequence)
assert not issubclass(seq_cls, collections.abc.Mapping)
for map_cls in (dict, OrderedDict, defaultdict):
assert not issubclass(map_cls, collections.abc.Sequence)
assert issubclass(map_cls, collections.abc.Mapping)
assert not issubclass(set, collections.abc.Sequence)
assert not issubclass(set, collections.abc.Mapping)