zeek/testing/btest/language/table-default-insert-errors.zeek
Arne Welzel 431767d04b Add &default_insert attribute for tables
This is based on the discussion in zeek/zeek#2668. Using &default with tables
can be confusing as the default value is not inserted. The following example
prints an empty table at the end even new Service records was instantiated.

    type Service: record {
        occurrences: count &default=0;
        last_seen: time &default=network_time();
    };

    global services: table[string] of Service &default=Service();

    event zeek_init()
        {
        services["http"]$occurrences += 1;
        services["http"]$last_seen = network_time();

        print services;
        }

Changing above &default to &default_insert will insert the newly created
default value upon a missed lookup and act less surprising.

Other examples that caused confusion previously revolved around table of sets
 or table of vectors and `add` or `+=` not working as expected.

    tbl_of_vector["http"] += 1
    add tbl_of_set["http"][1];
2023-08-04 12:30:36 +02:00

36 lines
1 KiB
Text

# @TEST-DOC: Bad &default_insert usage.
#
# @TEST-EXEC-FAIL: zeek -b %INPUT
# @TEST-EXEC: TEST_DIFF_CANONIFIER=$SCRIPTS/diff-remove-abspath btest-diff .stderr
# Not applicable to record fields.
type R: record {
a: string &default_insert="a";
};
@TEST-START-NEXT
# Not applicable to sets.
global s: set[string] &default_insert="a";
@TEST-START-NEXT
# Wrong expression type
global tbl: table[count] of string &default_insert=1;
@TEST-START-NEXT
# default function has wrong type
global tbl: table[count] of string &default_insert=function(c: count): count { return c; };
@TEST-START-NEXT
# default function has wrong type for inferred type
global tbl = table([1] = "a") &default_insert=function(c: count): count { return c; };
@TEST-START-NEXT
# Using &default and &default_insert together does not work.
global tbl: table[count] of string &default="a" &default_insert="b";
@TEST-START-NEXT
# Using &default and &default_insert together does not work, reversed order.
global tbl: table[count] of string &default_insert="a" &default="b";