Commit 12167e94 authored by YOU's avatar YOU Committed by Dylan Trotter

Implement dict.clear() (#135)

parent ccadc8ee
......@@ -508,6 +508,18 @@ func dictsAreEqual(f *Frame, d1, d2 *Dict) (bool, *BaseException) {
return result, nil
}
func dictClear(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if raised := checkMethodArgs(f, "clear", args, DictType); raised != nil {
return nil, raised
}
d := toDictUnsafe(args[0])
d.mutex.Lock(f)
d.table = newDictTable(0)
d.incVersion()
d.mutex.Unlock(f)
return None, nil
}
func dictContains(f *Frame, seq, value *Object) (*Object, *BaseException) {
item, raised := toDictUnsafe(seq).GetItem(f, value)
if raised != nil {
......@@ -713,6 +725,7 @@ func dictUpdate(f *Frame, args Args, kwargs KWArgs) (*Object, *BaseException) {
}
func initDictType(dict map[string]*Object) {
dict["clear"] = newBuiltinFunction("clear", dictClear).ToObject()
dict["get"] = newBuiltinFunction("get", dictGet).ToObject()
dict["items"] = newBuiltinFunction("items", dictItems).ToObject()
dict["iteritems"] = newBuiltinFunction("iteritems", dictIterItems).ToObject()
......
......@@ -46,6 +46,29 @@ func TestNewStringDict(t *testing.T) {
}
}
func TestDictClear(t *testing.T) {
clear := mustNotRaise(GetAttr(NewRootFrame(), DictType.ToObject(), NewStr("clear"), nil))
fun := newBuiltinFunction("TestDictClear", func(f *Frame, args Args, _ KWArgs) (*Object, *BaseException) {
if _, raised := clear.Call(f, args, nil); raised != nil {
return nil, raised
}
return args[0], nil
}).ToObject()
cases := []invokeTestCase{
{args: wrapArgs(NewDict()), want: NewDict().ToObject()},
{args: wrapArgs(newStringDict(map[string]*Object{"foo": NewInt(1).ToObject()})), want: NewDict().ToObject()},
{args: wrapArgs(newTestDict(2, None, "baz", 3.14)), want: NewDict().ToObject()},
{args: wrapArgs(NewDict(), NewList()), wantExc: mustCreateException(TypeErrorType, "'clear' of 'dict' requires 1 arguments")},
{args: wrapArgs(NewDict(), None), wantExc: mustCreateException(TypeErrorType, "'clear' of 'dict' requires 1 arguments")},
{args: wrapArgs(None), wantExc: mustCreateException(TypeErrorType, "unbound method clear() must be called with dict instance as first argument (got NoneType instance instead)")},
}
for _, cas := range cases {
if err := runInvokeTestCase(fun, &cas); err != "" {
t.Error(err)
}
}
}
func TestDictContains(t *testing.T) {
cases := []invokeTestCase{
{args: wrapArgs(NewDict(), "foo"), want: False.ToObject()},
......
......@@ -50,3 +50,14 @@ except KeyError:
pass
else:
raise AssertionError
# Test clear
d = {1: 1, 2: 2, 3: 3}
d.clear()
assert d == {}
try:
d.clear()
assert AssertionError
except TypeError:
pass
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment