From 9c4adbc5a7bd96fe0ac4a5388114cfcf767165d4 Mon Sep 17 00:00:00 2001 From: Sergey Bronnikov Date: Tue, 18 Jun 2024 13:59:36 +0300 Subject: [PATCH] molly: add a log iterator The patch add a generator which, when asked for an operation, logs a message and yields `nil`. --- CHANGELOG.md | 1 + molly/gen.lua | 24 +++++++++++++++++++----- test/tests.lua | 9 ++++++++- 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dda991b..3fffdc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- A `log()` iterator. - A `mix()` iterator. - A CAS-register generator. diff --git a/molly/gen.lua b/molly/gen.lua index 943ec8d..c82236b 100644 --- a/molly/gen.lua +++ b/molly/gen.lua @@ -38,6 +38,7 @@ local fun = require('fun') local clock = require('molly.clock') +local log = require('molly.log') local tbl = require('molly.compat.tbl') local fun_mt = debug.getmetatable(fun.range(10)) @@ -456,15 +457,28 @@ methods.flip_flop = flip_flop --- Special generators -- @section ---- (TODO) A generator which, when asked for an operation, logs a message and yields --- nil. Occurs only once; use `repeat` to repeat. +--- A generator which, when asked for an operation, logs +-- a message and yields `nil`. Occurs only once; use `repeat` to +-- repeat. -- @return an iterator -- +-- @usage +-- > molly.gen.iter({1, 2, 3}):log() +-- [INFO 2024-07-07 11:38:47:119933]: 1 +-- --- +-- - null +-- ... +-- -- -- @function log -local log = function() - -- TODO +local log_it = function(it) + assert(tostring(it) == '') + local gen, param, state = unwrap(it) + local _, v = gen(param, state) + log.info(v) + return nil_gen(nil, nil) end -exports.log = log +exports.log = log_it +methods.log = log_it --- (TODO) Operations from that generator are scheduled at uniformly random intervals -- between `0` to `2 * (dt seconds)`. diff --git a/test/tests.lua b/test/tests.lua index b9cd18c..0d41f83 100644 --- a/test/tests.lua +++ b/test/tests.lua @@ -27,7 +27,7 @@ local utils = molly.utils local seed = os.time() math.randomseed(seed) -test:plan(12) +test:plan(13) test:test('clock', function(test) test:plan(5) @@ -226,6 +226,13 @@ test:test('gen.mix', function(test) test:is(#tbl, 11, 'length of items generated by gen.mix') end) +test:test('gen.log', function(test) + test:plan(1) + + local res = molly.gen.iter({1, 2, 3}):log() + test:is(res, nil, 'gen.log returns nil') +end) + test:test('runner', function(test) test:plan(4)