You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mynewt.apache.org by ja...@apache.org on 2026/10/23 22:08:50 UTC
(mynewt-newtmgr) branch master updated (d512da4 -> c76e288)
This is an automated email from the ASF dual-hosted git repository.
sjanc pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/mynewt-newtmgr.git
from d512da4 newtmgr/nmutil: Add unit tests for ErrorCausedBy and TxOptions
new 32a30cc nmxact/xact: Add fake session and image chunking tests
new f2f7fab nmxact/xact: Fix data races in image upload
new ec0007b nmxact/xact: Fix image upload window deadlock
new 7770b41 nmxact/xact: Stop image upload on device error
new eb4fb87 nmxact/xact: Default image upload window size
new 2d03981 nmxact/xact: Allow image upgrade without progress callback
new f81c256 nmxact/xact: Do not busy-wait at the end of image upload
new 72eca30 nmxact/xact: Add unit tests for file upload and download
new e3ca36d nmxact/xact: Fix Status() of results without responses
new beee811 nmxact/xact: Add unit tests for management commands
new cc643ce nmxact/xact: Add unit tests for CoAP resource commands
new c76e288 nmxact/sesn: Add unit tests for transaction helpers
The 12 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
nmxact/sesn/sesn_util_test.go | 355 ++++++++++++++++++++
nmxact/xact/cmds_test.go | 631 ++++++++++++++++++++++++++++++++++++
nmxact/xact/fake_sesn_test.go | 348 ++++++++++++++++++++
nmxact/xact/fs.go | 14 +-
nmxact/xact/fs_test.go | 511 +++++++++++++++++++++++++++++
nmxact/xact/image.go | 93 ++++--
nmxact/xact/image_test.go | 507 +++++++++++++++++++++++++++++
nmxact/xact/image_upload_test.go | 679 +++++++++++++++++++++++++++++++++++++++
nmxact/xact/res_test.go | 194 +++++++++++
9 files changed, 3306 insertions(+), 26 deletions(-)
create mode 100644 nmxact/sesn/sesn_util_test.go
create mode 100644 nmxact/xact/cmds_test.go
create mode 100644 nmxact/xact/fake_sesn_test.go
create mode 100644 nmxact/xact/fs_test.go
create mode 100644 nmxact/xact/image_test.go
create mode 100644 nmxact/xact/image_upload_test.go
create mode 100644 nmxact/xact/res_test.go
(mynewt-newtmgr) 01/12: nmxact/xact: Add fake session and image chunking tests
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sjanc pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mynewt-newtmgr.git
commit 32a30cce4892ca4cff91e5ffe12c9c0b736a12c5
Author: Szymon Janc <sz...@codecoup.pl>
AuthorDate: Thu Oct 22 00:33:20 2026 +0200
nmxact/xact: Add fake session and image chunking tests
Add an in-memory, scripted implementation of sesn.Sesn for unit tests
of the xact package. It records every management request (header,
body, plain NMP encoding and the decoded CBOR fields) and hands it to a
handler which emulates the device. TxRxMgmtAsync is synchronous like
in the serial and naked BLE sessions. MTU, management protocol (NMP,
OMP over UDP or TCP) and CoAP filters are configurable.
Use it to test the image upload request building: an MTU sweep for all
protocol variants checking that requests fit the MTU, chunks are capped
at 512 bytes and use the available room, only the first chunk carries
len/sha/upgrade, the hash is dropped only if needed on small MTUs, too
small MTUs are reported as errors and the transmit filter is frozen
during the chunk size calculation. Also cover the upload window
tracker helpers.
Assisted-by: Claude:claude-opus-5-5
---
nmxact/xact/fake_sesn_test.go | 332 +++++++++++++++++++++++++++
nmxact/xact/image_test.go | 507 ++++++++++++++++++++++++++++++++++++++++++
2 files changed, 839 insertions(+)
diff --git a/nmxact/xact/fake_sesn_test.go b/nmxact/xact/fake_sesn_test.go
new file mode 100644
index 0000000..0f97a02
--- /dev/null
+++ b/nmxact/xact/fake_sesn_test.go
@@ -0,0 +1,332 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package xact
+
+import (
+ "fmt"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/runtimeco/go-coap"
+ "github.com/ugorji/go/codec"
+
+ "mynewt.apache.org/newtmgr/nmxact/mgmt"
+ "mynewt.apache.org/newtmgr/nmxact/nmcoap"
+ "mynewt.apache.org/newtmgr/nmxact/nmp"
+ "mynewt.apache.org/newtmgr/nmxact/sesn"
+)
+
+// testTimeout bounds every blocking operation in the tests so that a hang
+// turns into a test failure instead of a stuck test binary.
+const testTimeout = 5 * time.Second
+
+// fakeReq is a management request as seen by the fake session.
+type fakeReq struct {
+ Hdr nmp.NmpHdr
+
+ // Request body as passed by the command (e.g., *nmp.ImageUploadReq).
+ Body interface{}
+
+ // Plain NMP encoding of the request (header + CBOR body).
+ Plain []byte
+
+ // CBOR body decoded into a generic map; useful to check which fields
+ // are actually present on the wire.
+ Fields map[string]interface{}
+
+ // Length of the request encoded for the session's management protocol
+ // (what a real transport would transmit).
+ EncLen int
+}
+
+// fakeHandler emulates the device. It returns the response to a request or
+// an error which is reported the same way a real session would report it.
+type fakeHandler func(req fakeReq) (nmp.NmpRsp, error)
+
+// fakeCoapHandler emulates a CoAP server. A nil message means no reply.
+type fakeCoapHandler func(m coap.Message) coap.Message
+
+// fakeSesn is an in-memory, scripted implementation of sesn.Sesn.
+type fakeSesn struct {
+ mtx sync.Mutex
+
+ mtu int
+ proto sesn.MgmtProto
+ isTcp bool
+ txFilter nmcoap.TxMsgFilter
+ rxFilter nmcoap.RxMsgFilter
+ isOpen bool
+ openErr error
+ openCount int
+
+ // If set, requests whose encoding exceeds the MTU are rejected like
+ // a real datagram transport does.
+ strictMtu bool
+
+ handler fakeHandler
+ reqs []fakeReq
+
+ abortErr error
+ abortSeqs []uint8
+
+ coapHandler fakeCoapHandler
+ coapTx []coap.Message
+ listeners map[string]*nmcoap.Listener
+}
+
+func newFakeSesn(h fakeHandler) *fakeSesn {
+ return &fakeSesn{
+ mtu: 512,
+ proto: sesn.MGMT_PROTO_NMP,
+ isOpen: true,
+ strictMtu: true,
+ handler: h,
+ listeners: map[string]*nmcoap.Listener{},
+ }
+}
+
+func (s *fakeSesn) Requests() []fakeReq {
+ s.mtx.Lock()
+ defer s.mtx.Unlock()
+
+ return append([]fakeReq(nil), s.reqs...)
+}
+
+func (s *fakeSesn) Open() error {
+ s.mtx.Lock()
+ defer s.mtx.Unlock()
+
+ s.openCount++
+ if s.openErr != nil {
+ return s.openErr
+ }
+ s.isOpen = true
+ return nil
+}
+
+func (s *fakeSesn) Close() error {
+ s.mtx.Lock()
+ defer s.mtx.Unlock()
+
+ s.isOpen = false
+ return nil
+}
+
+func (s *fakeSesn) IsOpen() bool {
+ s.mtx.Lock()
+ defer s.mtx.Unlock()
+
+ return s.isOpen
+}
+
+func (s *fakeSesn) setOpen(open bool) {
+ s.mtx.Lock()
+ defer s.mtx.Unlock()
+
+ s.isOpen = open
+}
+
+func (s *fakeSesn) MtuIn() int { return s.mtu }
+func (s *fakeSesn) MtuOut() int { return s.mtu }
+
+func (s *fakeSesn) MgmtProto() sesn.MgmtProto { return s.proto }
+func (s *fakeSesn) CoapIsTcp() bool { return s.isTcp }
+
+func (s *fakeSesn) AbortRx(nmpSeq uint8) error {
+ s.mtx.Lock()
+ defer s.mtx.Unlock()
+
+ s.abortSeqs = append(s.abortSeqs, nmpSeq)
+ return s.abortErr
+}
+
+func (s *fakeSesn) RxAccept() (sesn.Sesn, *sesn.SesnCfg, error) {
+ return nil, nil, fmt.Errorf("RxAccept not supported by fake session")
+}
+
+func (s *fakeSesn) RxCoap(opt sesn.TxOptions) (coap.Message, error) {
+ return nil, fmt.Errorf("RxCoap not supported by fake session")
+}
+
+func decodeCborMap(b []byte) (map[string]interface{}, error) {
+ m := map[string]interface{}{}
+ dec := codec.NewDecoderBytes(b, new(codec.CborHandle))
+ if err := dec.Decode(&m); err != nil {
+ return nil, err
+ }
+ return m, nil
+}
+
+func (s *fakeSesn) TxRxMgmt(m *nmp.NmpMsg,
+ timeout time.Duration) (nmp.NmpRsp, error) {
+
+ enc, err := mgmt.EncodeMgmt(s, m)
+ if err != nil {
+ return nil, err
+ }
+ plain, err := nmp.EncodeNmpPlain(m)
+ if err != nil {
+ return nil, err
+ }
+ fields, err := decodeCborMap(plain[nmp.NMP_HDR_SIZE:])
+ if err != nil {
+ return nil, err
+ }
+
+ req := fakeReq{
+ Hdr: m.Hdr,
+ Body: m.Body,
+ Plain: plain,
+ Fields: fields,
+ EncLen: len(enc),
+ }
+
+ s.mtx.Lock()
+ open := s.isOpen
+ s.reqs = append(s.reqs, req)
+ h := s.handler
+ strict := s.strictMtu
+ s.mtx.Unlock()
+
+ if !open {
+ return nil, fmt.Errorf("fake session not open")
+ }
+ if strict && len(enc) > s.mtu {
+ return nil, fmt.Errorf("Request too big")
+ }
+ if h == nil {
+ return nil, fmt.Errorf("no handler")
+ }
+
+ return h(req)
+}
+
+// TxRxMgmtAsync behaves like the serial and naked BLE sessions: the
+// transaction is performed synchronously and the result is pushed to the
+// provided channels before returning.
+func (s *fakeSesn) TxRxMgmtAsync(m *nmp.NmpMsg, timeout time.Duration,
+ ch chan nmp.NmpRsp, errc chan error) error {
+
+ rsp, err := s.TxRxMgmt(m, timeout)
+ if err != nil {
+ errc <- err
+ } else {
+ ch <- rsp
+ }
+ return nil
+}
+
+func (s *fakeSesn) ListenCoap(
+ mc nmcoap.MsgCriteria) (*nmcoap.Listener, error) {
+
+ s.mtx.Lock()
+ defer s.mtx.Unlock()
+
+ key := mc.String()
+ if _, ok := s.listeners[key]; ok {
+ return nil, fmt.Errorf("duplicate listener: %s", key)
+ }
+ l := nmcoap.NewListener(mc)
+ s.listeners[key] = l
+ return l, nil
+}
+
+// StopListenCoap only forgets the listener. It does not close it to keep
+// the fake free of timer related races in the CoAP listener.
+func (s *fakeSesn) StopListenCoap(mc nmcoap.MsgCriteria) {
+ s.mtx.Lock()
+ defer s.mtx.Unlock()
+
+ delete(s.listeners, mc.String())
+}
+
+func (s *fakeSesn) TxCoap(m coap.Message) error {
+ s.mtx.Lock()
+ s.coapTx = append(s.coapTx, m)
+ h := s.coapHandler
+ var l *nmcoap.Listener
+ for _, cand := range s.listeners {
+ mc := nmcoap.CriteriaFromMsg(m)
+ if nmcoap.MatchMsgCriteria(cand.Criteria, mc) {
+ l = cand
+ }
+ }
+ s.mtx.Unlock()
+
+ if h == nil {
+ return nil
+ }
+ rsp := h(m)
+ if rsp != nil && l != nil {
+ l.RspChan <- rsp
+ }
+ return nil
+}
+
+func (s *fakeSesn) Filters() (nmcoap.TxMsgFilter, nmcoap.RxMsgFilter) {
+ return s.txFilter, s.rxFilter
+}
+
+func (s *fakeSesn) SetFilters(txFilter nmcoap.TxMsgFilter,
+ rxFilter nmcoap.RxMsgFilter) {
+
+ s.txFilter = txFilter
+ s.rxFilter = rxFilter
+}
+
+// rspFor builds a response to req by encoding fields as CBOR and decoding
+// them with the regular NMP response decoder. This yields the response
+// type a real session would produce.
+func rspFor(req fakeReq, fields map[string]interface{}) (nmp.NmpRsp, error) {
+ body := []byte{}
+ enc := codec.NewEncoderBytes(&body, new(codec.CborHandle))
+ if err := enc.Encode(fields); err != nil {
+ return nil, err
+ }
+
+ hdr := req.Hdr
+ hdr.Op++
+ hdr.Len = uint16(len(body))
+ return nmp.DecodeRspBody(&hdr, body)
+}
+
+// runCmd runs c with a timeout guard.
+func runCmd(t *testing.T, c Cmd, s sesn.Sesn) (Result, error) {
+ t.Helper()
+
+ type result struct {
+ res Result
+ err error
+ }
+ done := make(chan result, 1)
+ go func() {
+ res, err := c.Run(s)
+ done <- result{res, err}
+ }()
+
+ select {
+ case r := <-done:
+ return r.res, r.err
+ case <-time.After(testTimeout):
+ t.Fatalf("%T.Run() did not complete within %v", c, testTimeout)
+ return nil, nil
+ }
+}
diff --git a/nmxact/xact/image_test.go b/nmxact/xact/image_test.go
new file mode 100644
index 0000000..cbd8ac6
--- /dev/null
+++ b/nmxact/xact/image_test.go
@@ -0,0 +1,507 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package xact
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "fmt"
+ "sync"
+ "testing"
+
+ "github.com/runtimeco/go-coap"
+
+ "mynewt.apache.org/newtmgr/nmxact/mgmt"
+ "mynewt.apache.org/newtmgr/nmxact/nmp"
+ "mynewt.apache.org/newtmgr/nmxact/sesn"
+)
+
+func testImage(sz int) []byte {
+ data := make([]byte, sz)
+ for i := range data {
+ data[i] = byte(i*7 + 3)
+ }
+ return data
+}
+
+type protoVariant struct {
+ name string
+ proto sesn.MgmtProto
+ isTcp bool
+}
+
+var protoVariants = []protoVariant{
+ {"nmp", sesn.MGMT_PROTO_NMP, false},
+ {"omp-dgram", sesn.MGMT_PROTO_OMP, false},
+ {"omp-tcp", sesn.MGMT_PROTO_OMP, true},
+}
+
+func newProtoSesn(pv protoVariant, mtu int, h fakeHandler) *fakeSesn {
+ s := newFakeSesn(h)
+ s.proto = pv.proto
+ s.isTcp = pv.isTcp
+ s.mtu = mtu
+ return s
+}
+
+func encLen(t *testing.T, s sesn.Sesn, m *nmp.NmpMsg) int {
+ t.Helper()
+
+ enc, err := mgmt.EncodeMgmt(s, m)
+ if err != nil {
+ t.Fatalf("EncodeMgmt: %v", err)
+ }
+ return len(enc)
+}
+
+func TestBuildImageUploadReq(t *testing.T) {
+ hash := []byte{1, 2, 3}
+ chunk := []byte{4, 5}
+
+ r := buildImageUploadReq(1000, hash, true, chunk, 0, 1, 42)
+ if r.Len != 1000 || !bytes.Equal(r.DataSha, hash) || !r.Upgrade {
+ t.Errorf("off 0: len/sha/upgrade not set: %+v", r)
+ }
+ if r.Off != 0 || !bytes.Equal(r.Data, chunk) || r.ImageNum != 1 {
+ t.Errorf("off 0: wrong off/data/image: %+v", r)
+ }
+ if r.Hdr().Seq != 42 {
+ t.Errorf("seq: got %d want 42", r.Hdr().Seq)
+ }
+
+ // Only the first chunk carries len, sha and upgrade (733feb6).
+ r = buildImageUploadReq(1000, hash, true, chunk, 10, 1, 43)
+ if r.Len != 0 || r.DataSha != nil || r.Upgrade {
+ t.Errorf("off 10: len/sha/upgrade set: %+v", r)
+ }
+ if r.Off != 10 || !bytes.Equal(r.Data, chunk) {
+ t.Errorf("off 10: wrong off/data: %+v", r)
+ }
+}
+
+func TestNextImageUploadReqMtuSweep(t *testing.T) {
+ data := testImage(3000)
+ sha := sha256.Sum256(data)
+
+ for _, pv := range protoVariants {
+ for mtu := 20; mtu <= 1024; mtu++ {
+ // Every MTU around the interesting boundaries; sample the
+ // rest to keep the test fast.
+ if mtu > 300 && mtu%5 != 0 {
+ continue
+ }
+ s := newProtoSesn(pv, mtu, nil)
+
+ for _, off := range []int{0, 1, 600, len(data) - 1} {
+ r, err := nextImageUploadReq(s, false, data, off, 0)
+ if err != nil {
+ // Too small MTU must be reported, not panic.
+ if mtu > 100 {
+ t.Errorf("%s mtu=%d off=%d: unexpected error: %v",
+ pv.name, mtu, off, err)
+ }
+ continue
+ }
+
+ pfx := fmt.Sprintf("%s mtu=%d off=%d", pv.name, mtu, off)
+ if l := encLen(t, s, r.Msg()); l > mtu {
+ t.Errorf("%s: request len %d > mtu", pfx, l)
+ }
+ if len(r.Data) == 0 {
+ t.Errorf("%s: empty chunk", pfx)
+ }
+ if len(r.Data) > IMAGE_UPLOAD_MAX_CHUNK {
+ t.Errorf("%s: chunk %d > %d", pfx, len(r.Data),
+ IMAGE_UPLOAD_MAX_CHUNK)
+ }
+ if int(r.Off) != off {
+ t.Errorf("%s: req off %d", pfx, r.Off)
+ }
+ if !bytes.Equal(r.Data, data[off:off+len(r.Data)]) {
+ t.Errorf("%s: wrong chunk data", pfx)
+ }
+
+ if off == 0 {
+ if int(r.Len) != len(data) {
+ t.Errorf("%s: len %d", pfx, r.Len)
+ }
+ if r.DataSha != nil &&
+ !bytes.Equal(r.DataSha, sha[:]) {
+ t.Errorf("%s: wrong sha", pfx)
+ }
+ // The hash is only dropped if it does not leave
+ // room for a minimal first chunk (aba21b8). The
+ // chunk length calculation may leave up to two
+ // bytes unused (see TestNextImageUploadReqUsesMtu).
+ if r.DataSha == nil &&
+ len(data) >= IMAGE_UPLOAD_MIN_1ST_CHUNK {
+
+ withSha := buildImageUploadReq(len(data), sha[:],
+ false, data[:IMAGE_UPLOAD_MIN_1ST_CHUNK+2], 0,
+ 0, r.Hdr().Seq)
+ if encLen(t, s, withSha.Msg()) <= mtu {
+ t.Errorf("%s: sha dropped needlessly", pfx)
+ }
+ }
+ } else if r.Len != 0 || r.DataSha != nil {
+ t.Errorf("%s: len/sha in non-first chunk", pfx)
+ }
+ }
+ }
+ }
+}
+
+// The chunk length is reduced in multiple rounds until the request fits
+// (c953418); the result must still use the MTU well. The CBOR length
+// prefix of the data shrinks along with the chunk, so up to two bytes may
+// remain unused.
+func TestNextImageUploadReqUsesMtu(t *testing.T) {
+ data := testImage(3000)
+
+ for _, pv := range protoVariants {
+ for mtu := 100; mtu <= 600; mtu++ {
+ s := newProtoSesn(pv, mtu, nil)
+ r, err := nextImageUploadReq(s, false, data, 1000, 0)
+ if err != nil {
+ t.Fatalf("%s mtu=%d: %v", pv.name, mtu, err)
+ }
+ if len(r.Data) == IMAGE_UPLOAD_MAX_CHUNK {
+ continue
+ }
+
+ // Three more bytes of data must not fit.
+ bigger := buildImageUploadReq(len(data), nil, false,
+ data[1000:1000+len(r.Data)+3], 1000, 0, r.Hdr().Seq)
+ if l := encLen(t, s, bigger.Msg()); l <= mtu {
+ t.Errorf("%s mtu=%d: chunk %d not maximal (%d <= %d)",
+ pv.name, mtu, len(r.Data), l, mtu)
+ }
+ }
+ }
+}
+
+func TestNextImageUploadReqSmallMtuDropsSha(t *testing.T) {
+ data := testImage(1000)
+
+ for _, pv := range protoVariants {
+ // Find an MTU at which the first chunk only fits without the hash
+ // (aba21b8).
+ found := false
+ for mtu := 20; mtu <= 200; mtu++ {
+ s := newProtoSesn(pv, mtu, nil)
+ r, err := nextImageUploadReq(s, false, data, 0, 0)
+ if err != nil {
+ continue
+ }
+ if r.DataSha == nil {
+ found = true
+ if len(r.Data) == 0 {
+ t.Errorf("%s mtu=%d: no data", pv.name, mtu)
+ }
+ if int(r.Len) != len(data) {
+ t.Errorf("%s mtu=%d: len missing", pv.name, mtu)
+ }
+ }
+ }
+ if !found {
+ t.Errorf("%s: sha never dropped", pv.name)
+ }
+ }
+}
+
+func TestNextImageUploadReqMtuTooSmall(t *testing.T) {
+ data := testImage(1000)
+
+ for _, pv := range protoVariants {
+ for mtu := 0; mtu < 20; mtu++ {
+ s := newProtoSesn(pv, mtu, nil)
+ for _, off := range []int{0, 500} {
+ if _, err := nextImageUploadReq(s, false, data, off,
+ 0); err == nil {
+
+ t.Errorf("%s mtu=%d off=%d: no error", pv.name, mtu,
+ off)
+ }
+ }
+ }
+ }
+}
+
+func TestNextImageUploadReqFields(t *testing.T) {
+ data := testImage(1000)
+
+ for _, pv := range protoVariants {
+ s := newProtoSesn(pv, 512, nil)
+
+ // Last chunk.
+ r, err := nextImageUploadReq(s, false, data, len(data)-5, 2)
+ if err != nil {
+ t.Fatalf("%s: %v", pv.name, err)
+ }
+ if !bytes.Equal(r.Data, data[len(data)-5:]) {
+ t.Errorf("%s: wrong last chunk: %d bytes", pv.name, len(r.Data))
+ }
+ if r.ImageNum != 2 {
+ t.Errorf("%s: image num %d", pv.name, r.ImageNum)
+ }
+ if r.Upgrade {
+ t.Errorf("%s: upgrade set in non-first chunk", pv.name)
+ }
+
+ // Upgrade flag is only sent in the first chunk, when requested.
+ for _, upgrade := range []bool{false, true} {
+ r, err = nextImageUploadReq(s, upgrade, data, 0, 3)
+ if err != nil {
+ t.Fatalf("%s: %v", pv.name, err)
+ }
+ if r.Upgrade != upgrade {
+ t.Errorf("%s: upgrade %v want %v", pv.name, r.Upgrade,
+ upgrade)
+ }
+ if r.ImageNum != 3 {
+ t.Errorf("%s: image num %d", pv.name, r.ImageNum)
+ }
+ }
+
+ r, err = nextImageUploadReq(s, true, data, 100, 0)
+ if err != nil {
+ t.Fatalf("%s: %v", pv.name, err)
+ }
+ if r.Upgrade {
+ t.Errorf("%s: upgrade set at off 100", pv.name)
+ }
+ }
+}
+
+// growFilter is a CoAP transmit filter which pads every message with a
+// different amount of data unless frozen, similar to an encrypting filter
+// which uses new parameters for each message.
+type growFilter struct {
+ mtx sync.Mutex
+ frozen bool
+ extra int
+ freezes int
+ unfrozen int
+}
+
+func (f *growFilter) Filter(m coap.Message) (coap.Message, error) {
+ f.mtx.Lock()
+ defer f.mtx.Unlock()
+
+ if !f.frozen {
+ f.extra++
+ f.unfrozen++
+ }
+ pl := append([]byte{}, m.Payload()...)
+ m.SetPayload(append(pl, make([]byte, f.extra)...))
+ return m, nil
+}
+
+func (f *growFilter) Freeze() {
+ f.mtx.Lock()
+ defer f.mtx.Unlock()
+
+ f.frozen = true
+ f.freezes++
+ f.extra += 3
+}
+
+func (f *growFilter) Unfreeze() {
+ f.mtx.Lock()
+ defer f.mtx.Unlock()
+
+ f.frozen = false
+}
+
+func TestNextImageUploadReqFreezesFilter(t *testing.T) {
+ data := testImage(3000)
+
+ for _, pv := range protoVariants[1:] {
+ for _, off := range []int{0, 1000} {
+ for mtu := 100; mtu <= 600; mtu += 7 {
+ f := &growFilter{}
+ s := newProtoSesn(pv, mtu, nil)
+ s.txFilter = f
+
+ r, err := nextImageUploadReq(s, false, data, off, 0)
+ if err != nil {
+ t.Fatalf("%s mtu=%d: %v", pv.name, mtu, err)
+ }
+ if f.frozen {
+ t.Errorf("%s mtu=%d: filter left frozen", pv.name, mtu)
+ }
+ if f.freezes != 1 || f.unfrozen != 0 {
+ t.Errorf("%s mtu=%d: freezes=%d unfrozen=%d",
+ pv.name, mtu, f.freezes, f.unfrozen)
+ }
+
+ // Encoding with the parameters used during the chunk
+ // size calculation must fit the MTU (2452835).
+ f.Freeze()
+ f.extra -= 3
+ l := encLen(t, s, r.Msg())
+ f.Unfreeze()
+ if l > mtu {
+ t.Errorf("%s mtu=%d: len %d > mtu", pv.name, mtu, l)
+ }
+ }
+ }
+ }
+}
+
+func TestImageUploadTrackerUpdate(t *testing.T) {
+ tr := ImageUploadIntTracker{RspMap: map[int]int{}}
+
+ tr.UpdateTracker(100, IMAGE_UPLOAD_STATUS_EXPECTED)
+ if tr.RspMap[100] != 1 {
+ t.Errorf("expected: got %d", tr.RspMap[100])
+ }
+ tr.UpdateTracker(100, IMAGE_UPLOAD_STATUS_RQ)
+ if tr.RspMap[100] != 0 {
+ t.Errorf("rq: got %d", tr.RspMap[100])
+ }
+ tr.UpdateTracker(100, IMAGE_UPLOAD_STATUS_RQ)
+ if tr.RspMap[100] != -1 {
+ t.Errorf("repeated rq: got %d", tr.RspMap[100])
+ }
+ tr.UpdateTracker(200, IMAGE_UPLOAD_STATUS_MISSED)
+ if tr.RspMap[200] != IMAGE_UPLOAD_CHUNK_MISSED_WM {
+ t.Errorf("missed: got %d", tr.RspMap[200])
+ }
+}
+
+func TestImageUploadTrackerProcessMissedChunks(t *testing.T) {
+ tr := ImageUploadIntTracker{
+ Off: 500,
+ RspMap: map[int]int{
+ 100: 0, // done
+ 200: 1, // in flight
+ 300: -1, // at watermark: not yet missed
+ 400: -2, // missed
+ },
+ }
+
+ tr.ProcessMissedChunks()
+
+ if tr.Off != 400 {
+ t.Errorf("off: got %d want 400", tr.Off)
+ }
+ want := map[int]int{200: 1, 300: -1}
+ if len(tr.RspMap) != len(want) {
+ t.Errorf("map: got %v want %v", tr.RspMap, want)
+ }
+ for k, v := range want {
+ if tr.RspMap[k] != v {
+ t.Errorf("map[%d]: got %d want %d", k, tr.RspMap[k], v)
+ }
+ }
+}
+
+func TestImageUploadTrackerHandleResponse(t *testing.T) {
+ var cbOffs []uint32
+ c := NewImageUploadCmd()
+ c.MaxWinSz = 2
+ c.ProgressCb = func(_ *ImageUploadCmd, r *nmp.ImageUploadRsp) {
+ cbOffs = append(cbOffs, r.Off)
+ }
+ res := newImageUploadResult()
+
+ tr := ImageUploadIntTracker{
+ TuneWS: true,
+ WCount: 1,
+ WCap: 1,
+ RspMap: map[int]int{100: 1},
+ }
+
+ // Full window gets an open slot -> signal; window grows.
+ if !tr.HandleResponse(c, &nmp.ImageUploadRsp{Off: 100}, res) {
+ t.Errorf("no signal on full -> open transition")
+ }
+ if tr.WCap != 2 || tr.WCount != 0 || tr.MaxRxOff != 100 {
+ t.Errorf("after rsp 1: cap=%d count=%d maxrx=%d", tr.WCap,
+ tr.WCount, tr.MaxRxOff)
+ }
+ if tr.RspMap[100] != 0 {
+ t.Errorf("rsp map: %v", tr.RspMap)
+ }
+
+ // Window not full -> no signal; window capped at MaxWinSz.
+ tr.WCount = 1
+ if tr.HandleResponse(c, &nmp.ImageUploadRsp{Off: 50}, res) {
+ t.Errorf("signal without full window")
+ }
+ if tr.WCap != 2 || tr.WCount != 0 || tr.MaxRxOff != 100 {
+ t.Errorf("after rsp 2: cap=%d count=%d maxrx=%d", tr.WCap,
+ tr.WCount, tr.MaxRxOff)
+ }
+
+ // A nil response only releases the slot.
+ tr.WCount = 2
+ if !tr.HandleResponse(c, nil, res) {
+ t.Errorf("no signal on full -> open transition (nil rsp)")
+ }
+
+ if len(res.Rsps) != 2 || res.Rsps[0].Off != 100 ||
+ res.Rsps[1].Off != 50 {
+
+ t.Errorf("result rsps: %+v", res.Rsps)
+ }
+ if len(cbOffs) != 2 || cbOffs[0] != 100 || cbOffs[1] != 50 {
+ t.Errorf("progress offs: %v", cbOffs)
+ }
+}
+
+func TestImageUploadTrackerHandleError(t *testing.T) {
+ tr := ImageUploadIntTracker{
+ TuneWS: true,
+ WCount: 4,
+ WCap: 4,
+ RspMap: map[int]int{},
+ }
+ err := fmt.Errorf("boom")
+
+ // Window full and shrinking along with the count: no open slot yet.
+ if tr.HandleError(100, err) {
+ t.Errorf("signal although window still full")
+ }
+ if tr.WCap != 3 || tr.WCount != 3 || tr.TuneWS {
+ t.Errorf("after err 1: cap=%d count=%d tune=%v", tr.WCap,
+ tr.WCount, tr.TuneWS)
+ }
+ if tr.RspMap[100] != IMAGE_UPLOAD_CHUNK_MISSED_WM {
+ t.Errorf("rsp map: %v", tr.RspMap)
+ }
+
+ if tr.HandleError(200, err) {
+ t.Errorf("signal although window still full")
+ }
+ if tr.WCap != 2 || tr.WCount != 2 {
+ t.Errorf("after err 2: cap=%d count=%d", tr.WCap, tr.WCount)
+ }
+
+ // The window does not shrink below IMAGE_UPLOAD_START_WS + 1, so
+ // the slot opens now.
+ if !tr.HandleError(300, err) {
+ t.Errorf("no signal on full -> open transition")
+ }
+ if tr.WCap != 2 || tr.WCount != 1 {
+ t.Errorf("after err 3: cap=%d count=%d", tr.WCap, tr.WCount)
+ }
+}
(mynewt-newtmgr) 11/12: nmxact/xact: Add unit tests for CoAP resource commands
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sjanc pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mynewt-newtmgr.git
commit cc643ceb4ba7c5d901f6f4985522883159d12282
Author: Szymon Janc <sz...@codecoup.pl>
AuthorDate: Thu Oct 22 01:08:23 2026 +0200
nmxact/xact: Add unit tests for CoAP resource commands
Check the mapping of CoAP response codes to Status() (all 2.xx codes
are success), run ResCmd against the fake session for datagram and
TCP CoAP (request code, path, token and payload, listener cleanup),
the retransmission on response timeout according to TxOptions.Tries,
and ResNoRxCmd.
Assisted-by: Claude:claude-opus-5-5
---
nmxact/xact/res_test.go | 194 ++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 194 insertions(+)
diff --git a/nmxact/xact/res_test.go b/nmxact/xact/res_test.go
new file mode 100644
index 0000000..2ef18b8
--- /dev/null
+++ b/nmxact/xact/res_test.go
@@ -0,0 +1,194 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package xact
+
+import (
+ "bytes"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/runtimeco/go-coap"
+
+ "mynewt.apache.org/newtmgr/nmxact/nmcoap"
+ "mynewt.apache.org/newtmgr/nmxact/nmxutil"
+)
+
+func coapReply(isTcp bool, req coap.Message,
+ code coap.COAPCode) coap.Message {
+
+ p := coap.MessageParams{
+ Type: coap.Acknowledgement,
+ Code: code,
+ MessageID: req.MessageID(),
+ Token: req.Token(),
+ Payload: []byte{0xa0},
+ }
+ if isTcp {
+ return coap.NewTcpMessage(p)
+ }
+ return coap.NewDgramMessage(p)
+}
+
+// All 2.xx codes are success (5029f07).
+func TestResResultStatus(t *testing.T) {
+ tests := []struct {
+ code coap.COAPCode
+ want int
+ }{
+ {coap.Created, 0},
+ {coap.Deleted, 0},
+ {coap.Valid, 0},
+ {coap.Changed, 0},
+ {coap.Content, 0},
+ {coap.BadRequest, int(coap.BadRequest)},
+ {coap.Unauthorized, int(coap.Unauthorized)},
+ {coap.NotFound, int(coap.NotFound)},
+ {coap.MethodNotAllowed, int(coap.MethodNotAllowed)},
+ {coap.InternalServerError, int(coap.InternalServerError)},
+ }
+
+ for _, tt := range tests {
+ r := &ResResult{
+ Rsp: coap.NewDgramMessage(coap.MessageParams{Code: tt.code}),
+ }
+ if st := r.Status(); st != tt.want {
+ t.Errorf("code %v: status %d, want %d", tt.code, st, tt.want)
+ }
+ }
+}
+
+func TestResCmdRun(t *testing.T) {
+ for _, isTcp := range []bool{false, true} {
+ for _, code := range []coap.COAPCode{coap.Content, coap.NotFound} {
+ s := newFakeSesn(nil)
+ s.isTcp = isTcp
+ s.coapHandler = func(m coap.Message) coap.Message {
+ return coapReply(isTcp, m, code)
+ }
+
+ c := NewResCmd()
+ c.MsgParams = nmcoap.MsgParams{
+ Code: coap.PUT,
+ Uri: "/a/b",
+ Token: []byte{1, 2, 3, 4},
+ Payload: []byte{0xa1, 0x61, 0x78, 0x01},
+ }
+
+ res, err := runCmd(t, c, s)
+ if err != nil {
+ t.Fatalf("tcp %v code %v: %v", isTcp, code, err)
+ }
+ rres := res.(*ResResult)
+ if rres.Rsp.Code() != code {
+ t.Errorf("tcp %v: rsp code %v, want %v", isTcp,
+ rres.Rsp.Code(), code)
+ }
+
+ if len(s.coapTx) != 1 {
+ t.Fatalf("tcp %v: %d messages sent", isTcp, len(s.coapTx))
+ }
+ m := s.coapTx[0]
+ if m.Code() != coap.PUT || m.PathString() != "a/b" ||
+ !bytes.Equal(m.Token(), c.MsgParams.Token) ||
+ !bytes.Equal(m.Payload(), c.MsgParams.Payload) {
+
+ t.Errorf("tcp %v: request code %v path %q token %x",
+ isTcp, m.Code(), m.PathString(), m.Token())
+ }
+ if len(s.listeners) != 0 {
+ t.Errorf("tcp %v: listener not removed", isTcp)
+ }
+ }
+ }
+}
+
+// A request without a response is retried on timeout.
+func TestResCmdRetry(t *testing.T) {
+ tests := []struct {
+ name string
+ tries int
+ drops int
+ wantTx int
+ wantErr bool
+ }{
+ {"no retry", 1, 1, 1, true},
+ {"retry ok", 3, 2, 3, false},
+ {"retries exhausted", 2, 2, 2, true},
+ }
+
+ for _, tt := range tests {
+ var mtx sync.Mutex
+ drops := tt.drops
+
+ s := newFakeSesn(nil)
+ s.coapHandler = func(m coap.Message) coap.Message {
+ mtx.Lock()
+ defer mtx.Unlock()
+
+ if drops > 0 {
+ drops--
+ return nil
+ }
+ return coapReply(false, m, coap.Changed)
+ }
+
+ c := NewResCmd()
+ c.MsgParams = nmcoap.MsgParams{Code: coap.GET, Uri: "/x"}
+ opt := c.TxOptions()
+ opt.Tries = tt.tries
+ opt.Timeout = 20 * time.Millisecond
+ c.SetTxOptions(opt)
+
+ res, err := runCmd(t, c, s)
+ if tt.wantErr {
+ if !nmxutil.IsRspTimeout(err) {
+ t.Errorf("%s: err %v, want timeout", tt.name, err)
+ }
+ } else if err != nil {
+ t.Errorf("%s: %v", tt.name, err)
+ } else if res.Status() != 0 {
+ t.Errorf("%s: status %d", tt.name, res.Status())
+ }
+
+ if len(s.coapTx) != tt.wantTx {
+ t.Errorf("%s: %d messages sent, want %d", tt.name,
+ len(s.coapTx), tt.wantTx)
+ }
+ }
+}
+
+func TestResNoRxCmdRun(t *testing.T) {
+ s := newFakeSesn(nil)
+
+ c := NewResNoRxCmd()
+ c.MsgParams = nmcoap.MsgParams{Code: coap.POST, Uri: "/r"}
+
+ res, err := runCmd(t, c, s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if res.Status() != 0 {
+ t.Errorf("status %d", res.Status())
+ }
+ if len(s.coapTx) != 1 || s.coapTx[0].Code() != coap.POST {
+ t.Errorf("sent %v", s.coapTx)
+ }
+}
(mynewt-newtmgr) 07/12: nmxact/xact: Do not busy-wait at the end of image upload
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sjanc pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mynewt-newtmgr.git
commit f81c256f1abbbc014ccb76627d2f5f7d11549824
Author: Szymon Janc <sz...@codecoup.pl>
AuthorDate: Thu Oct 22 01:03:10 2026 +0200
nmxact/xact: Do not busy-wait at the end of image upload
Once all chunks had been sent, ImageUploadCmd.Run() spun in a tight
loop until the response for the last chunk arrived, burning a CPU core
for up to a round trip per chunk in the window (or the whole response
timeout if a response got lost).
Wait for the next response notification instead. Every change of the
upload state (response, error, missed chunk) is followed by a
notification, so the loop re-evaluates as soon as there is something
to do.
The busy loop itself cannot be observed by a test; add an option to
the fake session to deliver responses asynchronously, like the
transceiver based sessions do, and run uploads with it to cover the
waiting path, including a retransmission.
Assisted-by: Claude:claude-opus-5-5
---
nmxact/xact/fake_sesn_test.go | 24 ++++++++++++++++++++----
nmxact/xact/image.go | 5 +++++
nmxact/xact/image_upload_test.go | 33 +++++++++++++++++++++++++++++++++
3 files changed, 58 insertions(+), 4 deletions(-)
diff --git a/nmxact/xact/fake_sesn_test.go b/nmxact/xact/fake_sesn_test.go
index 0f97a02..1593f8f 100644
--- a/nmxact/xact/fake_sesn_test.go
+++ b/nmxact/xact/fake_sesn_test.go
@@ -84,6 +84,10 @@ type fakeSesn struct {
handler fakeHandler
reqs []fakeReq
+ // If non-zero, TxRxMgmtAsync() delivers the result from a separate
+ // goroutine after this delay, like the transceiver based sessions.
+ asyncDelay time.Duration
+
abortErr error
abortSeqs []uint8
@@ -221,15 +225,27 @@ func (s *fakeSesn) TxRxMgmt(m *nmp.NmpMsg,
// TxRxMgmtAsync behaves like the serial and naked BLE sessions: the
// transaction is performed synchronously and the result is pushed to the
-// provided channels before returning.
+// provided channels before returning. If asyncDelay is set, the result
+// is delivered later from a separate goroutine instead.
func (s *fakeSesn) TxRxMgmtAsync(m *nmp.NmpMsg, timeout time.Duration,
ch chan nmp.NmpRsp, errc chan error) error {
rsp, err := s.TxRxMgmt(m, timeout)
- if err != nil {
- errc <- err
+ deliver := func() {
+ if err != nil {
+ errc <- err
+ } else {
+ ch <- rsp
+ }
+ }
+
+ if s.asyncDelay == 0 {
+ deliver()
} else {
- ch <- rsp
+ go func() {
+ time.Sleep(s.asyncDelay)
+ deliver()
+ }()
}
return nil
}
diff --git a/nmxact/xact/image.go b/nmxact/xact/image.go
index cc021f1..e81a2bd 100644
--- a/nmxact/xact/image.go
+++ b/nmxact/xact/image.go
@@ -381,6 +381,11 @@ func (c *ImageUploadCmd) Run(s sesn.Sesn) (Result, error) {
t.ProcessMissedChunks()
if t.Off == len(c.Data) {
+ // Everything has been sent; wait for a response instead of
+ // spinning.
+ if int(atomic.LoadInt32(&t.MaxRxOff)) < len(c.Data) {
+ <-ch
+ }
continue
}
diff --git a/nmxact/xact/image_upload_test.go b/nmxact/xact/image_upload_test.go
index a27c447..8e81e32 100644
--- a/nmxact/xact/image_upload_test.go
+++ b/nmxact/xact/image_upload_test.go
@@ -25,6 +25,7 @@ import (
"fmt"
"sync"
"testing"
+ "time"
"mynewt.apache.org/newtmgr/nmxact/nmp"
"mynewt.apache.org/newtmgr/nmxact/nmxutil"
@@ -644,3 +645,35 @@ func TestImageUpgradeRunNoProgressCb(t *testing.T) {
}
checkUploaded(t, &dev.fakeImgDev, data)
}
+
+// Responses delivered asynchronously, as with the transceiver based
+// sessions: after the last chunk has been sent, Run() waits for the
+// outstanding responses.
+func TestImageUploadRunAsyncSession(t *testing.T) {
+ data := testImage(3000)
+
+ for _, winSz := range []int{1, 2, 5} {
+ for _, drop := range []bool{false, true} {
+ dev := &fakeImgDev{}
+ if drop {
+ dev.dropOffs = map[uint32]bool{0: true}
+ }
+ s := newFakeSesn(dev.handle)
+ s.mtu = 200
+ s.asyncDelay = time.Millisecond
+
+ c := NewImageUploadCmd()
+ c.Data = data
+ c.MaxWinSz = winSz
+
+ res, err := runCmd(t, c, s)
+ if err != nil {
+ t.Fatalf("win %d drop %v: %v", winSz, drop, err)
+ }
+ if st := res.Status(); st != 0 {
+ t.Errorf("win %d drop %v: status %d", winSz, drop, st)
+ }
+ checkUploaded(t, dev, data)
+ }
+ }
+}
(mynewt-newtmgr) 02/12: nmxact/xact: Fix data races in image upload
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sjanc pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mynewt-newtmgr.git
commit f2f7fab18bee02b72f5d42623a3e4b0912753887
Author: Szymon Janc <sz...@codecoup.pl>
AuthorDate: Thu Oct 22 00:41:54 2026 +0200
nmxact/xact: Fix data races in image upload
ImageUploadCmd.Run() handles responses in goroutines. These update
MaxRxOff under the tracker mutex, but Run() reads it without the mutex
(once atomically, once with a plain read), which is a data race.
Run() also returns the result as soon as the last byte is acknowledged,
while goroutines handling responses to requests still in flight may
keep appending to the very same result. Callers reading the result
(e.g. Status()) race with them.
Store MaxRxOff atomically and return a snapshot of the result, taken
under the tracker mutex. The snapshot also guarantees that the
progress callback for the final response has completed when Run()
returns.
Add tests for ImageUploadCmd and ImageUpgradeCmd running against the
fake session with an emulated device: various image sizes and
protocols, start offset, sequence numbers, progress callbacks,
retransmission after lost responses, abort, and the erase/reconnect
handling of the upgrade command. The race detector reported both
races in these tests. Larger windows are covered separately.
Assisted-by: Claude:claude-opus-5-5
---
nmxact/xact/image.go | 17 +-
nmxact/xact/image_upload_test.go | 505 +++++++++++++++++++++++++++++++++++++++
2 files changed, 518 insertions(+), 4 deletions(-)
diff --git a/nmxact/xact/image.go b/nmxact/xact/image.go
index 95dfea1..3963c89 100644
--- a/nmxact/xact/image.go
+++ b/nmxact/xact/image.go
@@ -272,8 +272,9 @@ func (t *ImageUploadIntTracker) HandleResponse(c *ImageUploadCmd, rsp nmp.NmpRsp
res.Rsps = append(res.Rsps, irsp)
t.UpdateTracker(int(irsp.Off), IMAGE_UPLOAD_STATUS_RQ)
+ // MaxRxOff is also read without the mutex by Run().
if t.MaxRxOff < int32(irsp.Off) {
- t.MaxRxOff = int32(irsp.Off)
+ atomic.StoreInt32(&t.MaxRxOff, int32(irsp.Off))
}
if c.ProgressCb != nil {
c.ProgressCb(c, irsp)
@@ -392,11 +393,19 @@ func (c *ImageUploadCmd) Run(s sesn.Sesn) (Result, error) {
}(int(r.Off))
}
- if int(t.MaxRxOff) == len(c.Data) {
- return res, nil
+ maxRxOff := int(atomic.LoadInt32(&t.MaxRxOff))
+ if maxRxOff == len(c.Data) {
+ // Responses to requests still in flight may be processed after
+ // we return; hand out a snapshot of the result so that the
+ // caller does not race with them.
+ t.Mutex.Lock()
+ defer t.Mutex.Unlock()
+ snap := newImageUploadResult()
+ snap.Rsps = append(snap.Rsps, res.Rsps...)
+ return snap, nil
} else {
return nil, fmt.Errorf("ImageUpload unexpected error after %d/%d bytes",
- t.MaxRxOff, len(c.Data))
+ maxRxOff, len(c.Data))
}
}
diff --git a/nmxact/xact/image_upload_test.go b/nmxact/xact/image_upload_test.go
new file mode 100644
index 0000000..1354cc6
--- /dev/null
+++ b/nmxact/xact/image_upload_test.go
@@ -0,0 +1,505 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package xact
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "fmt"
+ "sync"
+ "testing"
+
+ "mynewt.apache.org/newtmgr/nmxact/nmp"
+ "mynewt.apache.org/newtmgr/nmxact/nmxutil"
+)
+
+// fakeImgDev emulates the image upload handler of a device.
+type fakeImgDev struct {
+ mtx sync.Mutex
+
+ data []byte
+ expLen int
+ sha []byte
+ upgrade bool
+ img int
+
+ // If non-zero, all upload requests are answered with this rc.
+ failRc int
+
+ // Offsets of requests answered with a timeout error, once each.
+ dropOffs map[uint32]bool
+}
+
+func (d *fakeImgDev) handle(req fakeReq) (nmp.NmpRsp, error) {
+ ur, ok := req.Body.(*nmp.ImageUploadReq)
+ if !ok {
+ return nil, fmt.Errorf("unexpected request %T", req.Body)
+ }
+
+ d.mtx.Lock()
+ defer d.mtx.Unlock()
+
+ if d.dropOffs[ur.Off] {
+ delete(d.dropOffs, ur.Off)
+ return nil, nmxutil.NewRspTimeoutError("NMP timeout")
+ }
+
+ if d.failRc != 0 {
+ return &nmp.ImageUploadRsp{Rc: d.failRc}, nil
+ }
+
+ if ur.Off == 0 {
+ d.data = nil
+ d.expLen = int(ur.Len)
+ d.sha = ur.DataSha
+ d.upgrade = ur.Upgrade
+ d.img = int(ur.ImageNum)
+ }
+
+ // Like mcumgr: a request with an unexpected offset is answered with
+ // the offset the device expects.
+ if int(ur.Off) == len(d.data) {
+ d.data = append(d.data, ur.Data...)
+ }
+
+ return &nmp.ImageUploadRsp{Rc: 0, Off: uint32(len(d.data))}, nil
+}
+
+func (d *fakeImgDev) Data() []byte {
+ d.mtx.Lock()
+ defer d.mtx.Unlock()
+
+ return append([]byte(nil), d.data...)
+}
+
+func uploadReqs(t *testing.T, s *fakeSesn) []*nmp.ImageUploadReq {
+ t.Helper()
+
+ var reqs []*nmp.ImageUploadReq
+ for _, r := range s.Requests() {
+ ur, ok := r.Body.(*nmp.ImageUploadReq)
+ if !ok {
+ continue
+ }
+ reqs = append(reqs, ur)
+ }
+ return reqs
+}
+
+func checkUploaded(t *testing.T, dev *fakeImgDev, data []byte) {
+ t.Helper()
+
+ if got := dev.Data(); !bytes.Equal(got, data) {
+ t.Errorf("device got %d bytes, want %d", len(got), len(data))
+ }
+}
+
+func TestImageUploadRun(t *testing.T) {
+ for _, pv := range protoVariants {
+ // Size of the first chunk at an MTU of 256.
+ r, err := nextImageUploadReq(newProtoSesn(pv, 256, nil), false,
+ testImage(1000), 0, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ oneChunk := len(r.Data)
+
+ tests := []struct {
+ name string
+ sz int
+ winSz int
+ }{
+ {"1 byte", 1, 1},
+ {"32 bytes", 32, 1},
+ {"one chunk", oneChunk, 1},
+ {"one chunk + 1", oneChunk + 1, 1},
+ {"many win 1", 10000, 1},
+ }
+
+ for _, tt := range tests {
+ name := pv.name + "/" + tt.name
+ data := testImage(tt.sz)
+ dev := &fakeImgDev{}
+ s := newProtoSesn(pv, 256, dev.handle)
+
+ c := NewImageUploadCmd()
+ c.Data = data
+ c.MaxWinSz = tt.winSz
+ c.ImageNum = 1
+
+ res, err := runCmd(t, c, s)
+ if err != nil {
+ t.Fatalf("%s: %v", name, err)
+ }
+ checkUploaded(t, dev, data)
+
+ ures := res.(*ImageUploadResult)
+ if ures.Status() != 0 {
+ t.Errorf("%s: status %d", name, ures.Status())
+ }
+
+ reqs := uploadReqs(t, s)
+ if len(reqs) == 0 {
+ t.Fatalf("%s: no requests", name)
+ }
+ // XXX: Images shorter than IMAGE_UPLOAD_MIN_1ST_CHUNK are
+ // sent without hash; only check the hash for larger ones.
+ sha := sha256.Sum256(data)
+ if dev.expLen != len(data) || (tt.sz >=
+ IMAGE_UPLOAD_MIN_1ST_CHUNK && !bytes.Equal(dev.sha, sha[:])) {
+
+ t.Errorf("%s: wrong sha/len in first chunk", name)
+ }
+ if dev.img != 1 {
+ t.Errorf("%s: image num %d", name, dev.img)
+ }
+ for i, r := range s.Requests() {
+ if r.EncLen > s.mtu {
+ t.Errorf("%s: req %d len %d > mtu", name, i, r.EncLen)
+ }
+ if i > 0 {
+ if _, ok := r.Fields["len"]; ok {
+ t.Errorf("%s: req %d has len", name, i)
+ }
+ if _, ok := r.Fields["sha"]; ok {
+ t.Errorf("%s: req %d has sha", name, i)
+ }
+ }
+ }
+ if tt.sz <= oneChunk && len(reqs) != 1 {
+ t.Errorf("%s: %d requests, want 1", name, len(reqs))
+ }
+ }
+ }
+}
+
+func TestImageUploadRunEmpty(t *testing.T) {
+ dev := &fakeImgDev{}
+ s := newFakeSesn(dev.handle)
+
+ c := NewImageUploadCmd()
+ c.MaxWinSz = 1
+
+ if _, err := runCmd(t, c, s); err != nil {
+ t.Fatal(err)
+ }
+ if n := len(s.Requests()); n != 0 {
+ t.Errorf("%d requests for empty image", n)
+ }
+}
+
+func TestImageUploadRunSeq(t *testing.T) {
+ dev := &fakeImgDev{}
+ s := newFakeSesn(dev.handle)
+ s.mtu = 128
+
+ c := NewImageUploadCmd()
+ c.Data = testImage(5000)
+ c.MaxWinSz = 1
+
+ if _, err := runCmd(t, c, s); err != nil {
+ t.Fatal(err)
+ }
+
+ // Each transmitted request consumes exactly one sequence number
+ // (d9f7558).
+ reqs := s.Requests()
+ for i := 1; i < len(reqs); i++ {
+ if reqs[i].Hdr.Seq != reqs[i-1].Hdr.Seq+1 {
+ t.Fatalf("req %d seq %d after %d", i, reqs[i].Hdr.Seq,
+ reqs[i-1].Hdr.Seq)
+ }
+ }
+}
+
+func TestImageUploadRunStartOff(t *testing.T) {
+ data := testImage(3000)
+ dev := &fakeImgDev{data: append([]byte(nil), data[:1000]...)}
+ s := newFakeSesn(dev.handle)
+
+ c := NewImageUploadCmd()
+ c.Data = data
+ c.StartOff = 1000
+ c.MaxWinSz = 1
+
+ if _, err := runCmd(t, c, s); err != nil {
+ t.Fatal(err)
+ }
+ checkUploaded(t, dev, data)
+
+ reqs := uploadReqs(t, s)
+ if reqs[0].Off != 1000 {
+ t.Errorf("first req off %d want 1000", reqs[0].Off)
+ }
+ for _, r := range reqs {
+ if r.Off < 1000 || r.Len != 0 || r.DataSha != nil {
+ t.Errorf("unexpected req: off=%d len=%d sha=%x", r.Off, r.Len,
+ r.DataSha)
+ }
+ }
+}
+
+func TestImageUploadRunProgress(t *testing.T) {
+ data := testImage(5000)
+ dev := &fakeImgDev{}
+ s := newFakeSesn(dev.handle)
+ s.mtu = 200
+
+ var mtx sync.Mutex
+ var offs []uint32
+
+ c := NewImageUploadCmd()
+ c.Data = data
+ c.MaxWinSz = 1
+ c.ProgressCb = func(_ *ImageUploadCmd, r *nmp.ImageUploadRsp) {
+ mtx.Lock()
+ defer mtx.Unlock()
+ offs = append(offs, r.Off)
+ }
+
+ if _, err := runCmd(t, c, s); err != nil {
+ t.Fatal(err)
+ }
+
+ mtx.Lock()
+ defer mtx.Unlock()
+
+ if len(offs) != len(s.Requests()) {
+ t.Errorf("%d progress callbacks for %d requests", len(offs),
+ len(s.Requests()))
+ }
+ for i := 1; i < len(offs); i++ {
+ if offs[i] <= offs[i-1] {
+ t.Errorf("progress not increasing: %v", offs)
+ break
+ }
+ }
+}
+
+func TestImageUploadRunRetransmit(t *testing.T) {
+ data := testImage(5000)
+
+ for _, winSz := range []int{1} {
+ s := newFakeSesn(nil)
+ s.mtu = 200
+
+ // Learn the chunk offsets from a clean upload first.
+ clean := &fakeImgDev{}
+ s.handler = clean.handle
+ c := NewImageUploadCmd()
+ c.Data = data
+ c.MaxWinSz = winSz
+ if _, err := runCmd(t, c, s); err != nil {
+ t.Fatal(err)
+ }
+ reqs := uploadReqs(t, s)
+ if len(reqs) < 4 {
+ t.Fatalf("only %d chunks", len(reqs))
+ }
+
+ for _, drop := range []int{0, 1, len(reqs) / 2} {
+ dev := &fakeImgDev{
+ dropOffs: map[uint32]bool{reqs[drop].Off: true},
+ }
+ s := newFakeSesn(dev.handle)
+ s.mtu = 200
+
+ c := NewImageUploadCmd()
+ c.Data = data
+ c.MaxWinSz = winSz
+ if _, err := runCmd(t, c, s); err != nil {
+ t.Fatalf("win %d drop %d: %v", winSz, drop, err)
+ }
+ checkUploaded(t, dev, data)
+ }
+ }
+}
+
+func TestImageUploadRunMtuTooSmall(t *testing.T) {
+ dev := &fakeImgDev{}
+ s := newFakeSesn(dev.handle)
+ s.mtu = 10
+
+ c := NewImageUploadCmd()
+ c.Data = testImage(100)
+ c.MaxWinSz = 1
+
+ if _, err := runCmd(t, c, s); err == nil {
+ t.Errorf("no error with tiny MTU")
+ }
+}
+
+func TestImageUploadRunAborted(t *testing.T) {
+ dev := &fakeImgDev{}
+ s := newFakeSesn(dev.handle)
+
+ c := NewImageUploadCmd()
+ c.Data = testImage(100)
+ c.MaxWinSz = 1
+ if err := c.Abort(); err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err := runCmd(t, c, s); err == nil {
+ t.Errorf("no error after abort")
+ }
+ if n := len(s.Requests()); n != 0 {
+ t.Errorf("%d requests after abort", n)
+ }
+}
+
+// imgUpgradeDev emulates a device handling image erase and upload.
+type imgUpgradeDev struct {
+ fakeImgDev
+
+ s *fakeSesn
+
+ eraseRc int
+ eraseErr error
+
+ // Close the session when the erase request fails.
+ eraseDisconnect bool
+
+ erases int
+}
+
+func (d *imgUpgradeDev) handle(req fakeReq) (nmp.NmpRsp, error) {
+ if req.Hdr.Group == nmp.NMP_GROUP_IMAGE &&
+ req.Hdr.Id == nmp.NMP_ID_IMAGE_ERASE {
+
+ d.mtx.Lock()
+ d.erases++
+ d.mtx.Unlock()
+
+ if d.eraseErr != nil {
+ if d.eraseDisconnect {
+ d.s.setOpen(false)
+ }
+ return nil, d.eraseErr
+ }
+ return rspFor(req, map[string]interface{}{"rc": d.eraseRc})
+ }
+
+ return d.fakeImgDev.handle(req)
+}
+
+func TestImageUpgradeRun(t *testing.T) {
+ tests := []struct {
+ name string
+ noErase bool
+ eraseRc int
+ eraseErr error
+ disconnect bool
+ openErr error
+ wantErr bool
+ wantErases int
+ wantOpens int
+ }{
+ {name: "erase ok", wantErases: 1},
+ {name: "no erase", noErase: true},
+ {name: "erase rc", eraseRc: nmp.NMP_ERR_ENOMEM, wantErases: 1},
+ {
+ name: "erase error while connected",
+ eraseErr: fmt.Errorf("erase failed"),
+ wantErr: true,
+ wantErases: 1,
+ },
+ {
+ name: "erase disconnect reconnect ok",
+ eraseErr: fmt.Errorf("disconnected"),
+ disconnect: true,
+ wantErases: 1,
+ wantOpens: 1,
+ },
+ {
+ name: "erase disconnect reconnect fails",
+ eraseErr: fmt.Errorf("disconnected"),
+ disconnect: true,
+ openErr: fmt.Errorf("cannot connect"),
+ wantErr: true,
+ wantErases: 1,
+ wantOpens: 1,
+ },
+ }
+
+ for _, tt := range tests {
+ data := testImage(2000)
+ dev := &imgUpgradeDev{
+ eraseRc: tt.eraseRc,
+ eraseErr: tt.eraseErr,
+ eraseDisconnect: tt.disconnect,
+ }
+ s := newFakeSesn(dev.handle)
+ s.openErr = tt.openErr
+ dev.s = s
+
+ var mtx sync.Mutex
+ var last uint32
+ c := NewImageUpgradeCmd()
+ c.Data = data
+ c.NoErase = tt.noErase
+ c.MaxWinSz = 1
+ c.ProgressCb = func(_ *ImageUploadCmd, r *nmp.ImageUploadRsp) {
+ mtx.Lock()
+ defer mtx.Unlock()
+ last = r.Off
+ }
+
+ res, err := runCmd(t, c, s)
+ if dev.erases != tt.wantErases {
+ t.Errorf("%s: %d erases, want %d", tt.name, dev.erases,
+ tt.wantErases)
+ }
+ if s.openCount != tt.wantOpens {
+ t.Errorf("%s: %d opens, want %d", tt.name, s.openCount,
+ tt.wantOpens)
+ }
+ if tt.wantErr {
+ if err == nil {
+ t.Errorf("%s: no error", tt.name)
+ }
+ continue
+ }
+ if err != nil {
+ t.Fatalf("%s: %v", tt.name, err)
+ }
+
+ checkUploaded(t, &dev.fakeImgDev, data)
+ ures := res.(*ImageUpgradeResult)
+ if ures.Status() != 0 || ures.UploadRes == nil {
+ t.Errorf("%s: status %d", tt.name, ures.Status())
+ }
+ if tt.noErase != (ures.EraseRes == nil) {
+ t.Errorf("%s: erase result %+v", tt.name, ures.EraseRes)
+ }
+ if !tt.noErase && !tt.disconnect &&
+ ures.EraseRes.Status() != tt.eraseRc {
+
+ t.Errorf("%s: erase status %d", tt.name,
+ ures.EraseRes.Status())
+ }
+
+ mtx.Lock()
+ if int(last) != len(data) {
+ t.Errorf("%s: last progress off %d", tt.name, last)
+ }
+ mtx.Unlock()
+ }
+}
(mynewt-newtmgr) 12/12: nmxact/sesn: Add unit tests for transaction helpers
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sjanc pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mynewt-newtmgr.git
commit c76e288e6cf48d1233e496075cbcc32a3ce026de
Author: Szymon Janc <sz...@codecoup.pl>
AuthorDate: Thu Oct 22 01:09:21 2026 +0200
nmxact/sesn: Add unit tests for transaction helpers
Test the retry loops of TxRxMgmt, TxRxMgmtAsync and TxRxCoap with a
scripted session: only response timeouts are retried, Tries of 0 or 1
means a single attempt, other errors end the transaction immediately.
Also cover TxCoap (message type, fields, token generation), RxCoap
(response, error, timeout), TxOptions and MgmtProto.String().
Assisted-by: Claude:claude-opus-5-5
---
nmxact/sesn/sesn_util_test.go | 355 ++++++++++++++++++++++++++++++++++++++++++
1 file changed, 355 insertions(+)
diff --git a/nmxact/sesn/sesn_util_test.go b/nmxact/sesn/sesn_util_test.go
new file mode 100644
index 0000000..63ac15b
--- /dev/null
+++ b/nmxact/sesn/sesn_util_test.go
@@ -0,0 +1,355 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package sesn
+
+import (
+ "bytes"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/runtimeco/go-coap"
+
+ "mynewt.apache.org/newtmgr/nmxact/nmcoap"
+ "mynewt.apache.org/newtmgr/nmxact/nmp"
+ "mynewt.apache.org/newtmgr/nmxact/nmxutil"
+)
+
+// stubSesn is a minimal scripted session. Each management transaction
+// consumes the next error from errs; once errs is exhausted, transactions
+// succeed.
+type stubSesn struct {
+ errs []error
+ calls int
+ timeouts []time.Duration
+
+ isTcp bool
+ coapTx []coap.Message
+ txErr error
+ listenc []nmcoap.MsgCriteria
+ stopped []nmcoap.MsgCriteria
+ lner *nmcoap.Listener
+
+ // Called for each transmitted CoAP message.
+ onTxCoap func(m coap.Message)
+}
+
+func (s *stubSesn) nextErr(timeout time.Duration) error {
+ s.calls++
+ s.timeouts = append(s.timeouts, timeout)
+ if len(s.errs) == 0 {
+ return nil
+ }
+ err := s.errs[0]
+ s.errs = s.errs[1:]
+ return err
+}
+
+func (s *stubSesn) Open() error { return nil }
+func (s *stubSesn) Close() error { return nil }
+func (s *stubSesn) IsOpen() bool { return true }
+func (s *stubSesn) MtuIn() int { return 512 }
+func (s *stubSesn) MtuOut() int { return 512 }
+func (s *stubSesn) MgmtProto() MgmtProto { return MGMT_PROTO_NMP }
+func (s *stubSesn) CoapIsTcp() bool { return s.isTcp }
+func (s *stubSesn) AbortRx(nmpSeq uint8) error { return nil }
+
+func (s *stubSesn) RxAccept() (Sesn, *SesnCfg, error) {
+ return nil, nil, fmt.Errorf("not supported")
+}
+
+func (s *stubSesn) RxCoap(opt TxOptions) (coap.Message, error) {
+ return nil, fmt.Errorf("not supported")
+}
+
+func (s *stubSesn) TxRxMgmt(m *nmp.NmpMsg,
+ timeout time.Duration) (nmp.NmpRsp, error) {
+
+ if err := s.nextErr(timeout); err != nil {
+ return nil, err
+ }
+ return nmp.NewEchoRsp(), nil
+}
+
+func (s *stubSesn) TxRxMgmtAsync(m *nmp.NmpMsg, timeout time.Duration,
+ ch chan nmp.NmpRsp, errc chan error) error {
+
+ return s.nextErr(timeout)
+}
+
+func (s *stubSesn) ListenCoap(
+ mc nmcoap.MsgCriteria) (*nmcoap.Listener, error) {
+
+ s.listenc = append(s.listenc, mc)
+ s.lner = nmcoap.NewListener(mc)
+ return s.lner, nil
+}
+
+func (s *stubSesn) StopListenCoap(mc nmcoap.MsgCriteria) {
+ s.stopped = append(s.stopped, mc)
+}
+
+func (s *stubSesn) TxCoap(m coap.Message) error {
+ s.coapTx = append(s.coapTx, m)
+ if s.txErr != nil {
+ return s.txErr
+ }
+ if s.onTxCoap != nil {
+ s.onTxCoap(m)
+ }
+ return nil
+}
+
+func (s *stubSesn) Filters() (nmcoap.TxMsgFilter, nmcoap.RxMsgFilter) {
+ return nil, nil
+}
+
+func (s *stubSesn) SetFilters(txFilter nmcoap.TxMsgFilter,
+ rxFilter nmcoap.RxMsgFilter) {
+}
+
+func tmoErr() error {
+ return nmxutil.NewRspTimeoutError("timeout")
+}
+
+var retryTests = []struct {
+ name string
+ tries int
+ errs []error
+ wantCalls int
+ wantErr bool
+}{
+ {"success", 1, nil, 1, false},
+ {"zero tries means one attempt", 0, []error{tmoErr()}, 1, true},
+ {"one try", 1, []error{tmoErr()}, 1, true},
+ {"retry after timeout", 3, []error{tmoErr(), tmoErr()}, 3, false},
+ {"retries exhausted", 2, []error{tmoErr(), tmoErr(), tmoErr()}, 2,
+ true},
+ {"other error not retried", 3, []error{fmt.Errorf("boom")}, 1, true},
+ {"other error after timeout", 3,
+ []error{tmoErr(), fmt.Errorf("boom")}, 2, true},
+ {"closed not retried", 3,
+ []error{nmxutil.NewSesnClosedError("closed")}, 1, true},
+}
+
+func TestTxRxMgmtRetry(t *testing.T) {
+ for _, tt := range retryTests {
+ s := &stubSesn{errs: append([]error(nil), tt.errs...)}
+ opt := TxOptions{Timeout: 7 * time.Second, Tries: tt.tries}
+
+ rsp, err := TxRxMgmt(s, nmp.NewEchoReq().Msg(), opt)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("%s: err %v", tt.name, err)
+ }
+ if (rsp == nil) != tt.wantErr {
+ t.Errorf("%s: rsp %v", tt.name, rsp)
+ }
+ if s.calls != tt.wantCalls {
+ t.Errorf("%s: %d calls, want %d", tt.name, s.calls,
+ tt.wantCalls)
+ }
+ for _, tmo := range s.timeouts {
+ if tmo != opt.Timeout {
+ t.Errorf("%s: timeout %v", tt.name, tmo)
+ }
+ }
+ }
+}
+
+func TestTxRxMgmtAsyncRetry(t *testing.T) {
+ for _, tt := range retryTests {
+ s := &stubSesn{errs: append([]error(nil), tt.errs...)}
+ opt := TxOptions{Timeout: 7 * time.Second, Tries: tt.tries}
+
+ err := TxRxMgmtAsync(s, nmp.NewEchoReq().Msg(), opt, nil, nil)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("%s: err %v", tt.name, err)
+ }
+ if s.calls != tt.wantCalls {
+ t.Errorf("%s: %d calls, want %d", tt.name, s.calls,
+ tt.wantCalls)
+ }
+ }
+}
+
+func TestTxOptions(t *testing.T) {
+ opt := NewTxOptions()
+ if opt != DfltTxOptions || opt.Tries != 1 || opt.Timeout <= 0 {
+ t.Errorf("default options %+v", opt)
+ }
+
+ opt.Timeout = 0
+ if opt.AfterTimeout() != nil {
+ t.Errorf("zero timeout yields a timer")
+ }
+
+ opt.Timeout = time.Millisecond
+ select {
+ case <-opt.AfterTimeout():
+ case <-time.After(5 * time.Second):
+ t.Fatal("timeout did not fire")
+ }
+}
+
+func TestMgmtProtoString(t *testing.T) {
+ tests := map[MgmtProto]string{
+ MGMT_PROTO_NMP: "nmp",
+ MGMT_PROTO_OMP: "omp",
+ MGMT_PROTO_COAP_SERVER: "coapserver",
+ }
+ for p, want := range tests {
+ if p.String() != want {
+ t.Errorf("%d: %q, want %q", p, p.String(), want)
+ }
+ }
+}
+
+func TestTxCoap(t *testing.T) {
+ for _, isTcp := range []bool{false, true} {
+ s := &stubSesn{isTcp: isTcp}
+ mp := nmcoap.MsgParams{
+ Code: coap.PUT,
+ Uri: "/x/y",
+ Token: []byte{9, 8},
+ Payload: []byte{1, 2, 3},
+ }
+ if err := TxCoap(s, mp); err != nil {
+ t.Fatalf("tcp %v: %v", isTcp, err)
+ }
+ if len(s.coapTx) != 1 {
+ t.Fatalf("tcp %v: %d messages", isTcp, len(s.coapTx))
+ }
+ m := s.coapTx[0]
+ _, isTcpMsg := m.(*coap.TcpMessage)
+ if isTcpMsg != isTcp {
+ t.Errorf("tcp %v: message type %T", isTcp, m)
+ }
+ if m.Code() != coap.PUT || m.PathString() != "x/y" ||
+ !bytes.Equal(m.Token(), mp.Token) ||
+ !bytes.Equal(m.Payload(), mp.Payload) {
+
+ t.Errorf("tcp %v: wrong message", isTcp)
+ }
+ }
+
+ // A missing token is generated.
+ get := nmcoap.MsgParams{Code: coap.GET, Uri: "/r"}
+ s := &stubSesn{}
+ if err := TxCoap(s, get); err != nil {
+ t.Fatal(err)
+ }
+ if len(s.coapTx[0].Token()) == 0 {
+ t.Errorf("no token generated")
+ }
+
+ s = &stubSesn{txErr: fmt.Errorf("tx failed")}
+ if err := TxCoap(s, get); err == nil {
+ t.Errorf("tx error not reported")
+ }
+}
+
+func TestRxCoap(t *testing.T) {
+ msg := coap.NewDgramMessage(coap.MessageParams{Code: coap.Content})
+ rxErr := fmt.Errorf("rx failed")
+
+ for _, tmo := range []time.Duration{0, 5 * time.Second} {
+ l := nmcoap.NewListener(nmcoap.MsgCriteria{})
+ l.RspChan <- msg
+ rsp, err := RxCoap(l, tmo)
+ if err != nil || rsp != msg {
+ t.Errorf("tmo %v: rsp %v err %v", tmo, rsp, err)
+ }
+
+ l = nmcoap.NewListener(nmcoap.MsgCriteria{})
+ l.ErrChan <- rxErr
+ rsp, err = RxCoap(l, tmo)
+ if err != rxErr || rsp != nil {
+ t.Errorf("tmo %v: rsp %v err %v", tmo, rsp, err)
+ }
+ }
+
+ l := nmcoap.NewListener(nmcoap.MsgCriteria{})
+ rsp, err := RxCoap(l, time.Millisecond)
+ if !nmxutil.IsRspTimeout(err) || rsp != nil {
+ t.Errorf("timeout: rsp %v err %v", rsp, err)
+ }
+}
+
+func TestTxRxCoap(t *testing.T) {
+ tests := []struct {
+ name string
+ tries int
+ drops int
+ wantTx int
+ wantErr bool
+ }{
+ {"reply", 1, 0, 1, false},
+ {"no reply", 1, 1, 1, true},
+ {"zero tries", 0, 1, 1, true},
+ {"retry", 3, 2, 3, false},
+ {"retries exhausted", 2, 5, 2, true},
+ }
+
+ for _, tt := range tests {
+ s := &stubSesn{}
+ drops := tt.drops
+ s.onTxCoap = func(m coap.Message) {
+ if drops > 0 {
+ drops--
+ return
+ }
+ s.lner.RspChan <- coap.NewDgramMessage(coap.MessageParams{
+ Code: coap.Content,
+ Token: m.Token(),
+ })
+ }
+
+ mp := nmcoap.MsgParams{Code: coap.GET, Uri: "/r", Token: []byte{1}}
+ opt := TxOptions{Timeout: 10 * time.Millisecond, Tries: tt.tries}
+
+ rsp, err := TxRxCoap(s, mp, opt)
+ if tt.wantErr {
+ if !nmxutil.IsRspTimeout(err) || rsp != nil {
+ t.Errorf("%s: rsp %v err %v", tt.name, rsp, err)
+ }
+ } else if err != nil || rsp == nil || rsp.Code() != coap.Content {
+ t.Errorf("%s: rsp %v err %v", tt.name, rsp, err)
+ }
+
+ if len(s.coapTx) != tt.wantTx {
+ t.Errorf("%s: %d messages sent, want %d", tt.name,
+ len(s.coapTx), tt.wantTx)
+ }
+ if len(s.listenc) != 1 || len(s.stopped) != 1 ||
+ !bytes.Equal(s.listenc[0].Token, mp.Token) {
+
+ t.Errorf("%s: listen %v stop %v", tt.name, s.listenc,
+ s.stopped)
+ }
+ }
+
+ // A transmit error ends the transaction without retries.
+ s := &stubSesn{txErr: fmt.Errorf("tx failed")}
+ _, err := TxRxCoap(s, nmcoap.MsgParams{Code: coap.GET, Uri: "/r"},
+ TxOptions{Timeout: time.Second, Tries: 3})
+ if err == nil || len(s.coapTx) != 1 || len(s.stopped) != 1 {
+ t.Errorf("tx error: err %v, %d sent", err, len(s.coapTx))
+ }
+}
(mynewt-newtmgr) 09/12: nmxact/xact: Fix Status() of results without responses
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sjanc pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mynewt-newtmgr.git
commit e3ca36d9da240147333ffa8d50bd858d26cf0514
Author: Szymon Janc <sz...@codecoup.pl>
AuthorDate: Thu Oct 22 01:06:16 2026 +0200
nmxact/xact: Fix Status() of results without responses
FsDownloadResult, FsUploadResult and CoreLoadResult returned the rc of
the last response without checking that there is one. FsUploadCmd
does not send any request for empty data, so calling Status() on the
result of uploading an empty file panicked with an index out of range.
Return NMP_ERR_EUNKNOWN for an empty result, as ImageUploadResult and
LogShowFullResult already do.
Assisted-by: Claude:claude-opus-5-5
---
nmxact/xact/fs.go | 14 ++++++++++----
nmxact/xact/fs_test.go | 28 ++++++++++++++++++++++++++++
nmxact/xact/image.go | 7 +++++--
3 files changed, 43 insertions(+), 6 deletions(-)
diff --git a/nmxact/xact/fs.go b/nmxact/xact/fs.go
index be12879..7c0d581 100644
--- a/nmxact/xact/fs.go
+++ b/nmxact/xact/fs.go
@@ -53,8 +53,11 @@ func newFsDownloadResult() *FsDownloadResult {
}
func (r *FsDownloadResult) Status() int {
- rsp := r.Rsps[len(r.Rsps)-1]
- return rsp.Rc
+ if len(r.Rsps) > 0 {
+ return r.Rsps[len(r.Rsps)-1].Rc
+ } else {
+ return nmp.NMP_ERR_EUNKNOWN
+ }
}
func (c *FsDownloadCmd) Run(s sesn.Sesn) (Result, error) {
@@ -119,8 +122,11 @@ func newFsUploadResult() *FsUploadResult {
}
func (r *FsUploadResult) Status() int {
- rsp := r.Rsps[len(r.Rsps)-1]
- return rsp.Rc
+ if len(r.Rsps) > 0 {
+ return r.Rsps[len(r.Rsps)-1].Rc
+ } else {
+ return nmp.NMP_ERR_EUNKNOWN
+ }
}
func buildFsUploadReq(name string, fileSz int, chunk []byte,
diff --git a/nmxact/xact/fs_test.go b/nmxact/xact/fs_test.go
index 81798da..90f2f37 100644
--- a/nmxact/xact/fs_test.go
+++ b/nmxact/xact/fs_test.go
@@ -481,3 +481,31 @@ func TestFsDownloadRunTxError(t *testing.T) {
t.Errorf("no error")
}
}
+
+// Status() of a result without responses (e.g. uploading an empty file,
+// which sends no request) must not panic.
+func TestMultiRspResultStatusEmpty(t *testing.T) {
+ results := []Result{
+ &FsDownloadResult{},
+ &FsUploadResult{},
+ &CoreLoadResult{},
+ &ImageUploadResult{},
+ &LogShowFullResult{},
+ }
+ for _, r := range results {
+ if st := r.Status(); st != nmp.NMP_ERR_EUNKNOWN {
+ t.Errorf("%T: status %d", r, st)
+ }
+ }
+
+ s := newFakeSesn(newFakeFsDev().handle)
+ c := NewFsUploadCmd()
+ c.Name = "/f"
+ res, err := runCmd(t, c, s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if st := res.Status(); st != nmp.NMP_ERR_EUNKNOWN {
+ t.Errorf("empty upload: status %d", st)
+ }
+}
diff --git a/nmxact/xact/image.go b/nmxact/xact/image.go
index e81a2bd..f212a47 100644
--- a/nmxact/xact/image.go
+++ b/nmxact/xact/image.go
@@ -783,8 +783,11 @@ func newCoreLoadResult() *CoreLoadResult {
}
func (r *CoreLoadResult) Status() int {
- rsp := r.Rsps[len(r.Rsps)-1]
- return rsp.Rc
+ if len(r.Rsps) > 0 {
+ return r.Rsps[len(r.Rsps)-1].Rc
+ } else {
+ return nmp.NMP_ERR_EUNKNOWN
+ }
}
func (c *CoreLoadCmd) Run(s sesn.Sesn) (Result, error) {
(mynewt-newtmgr) 04/12: nmxact/xact: Stop image upload on device error
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sjanc pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mynewt-newtmgr.git
commit 7770b41f3f077850e01ab5ff5cd2ff5d28ed9b33
Author: Szymon Janc <sz...@codecoup.pl>
AuthorDate: Thu Oct 22 00:59:43 2026 +0200
nmxact/xact: Stop image upload on device error
ImageUploadCmd ignored the rc of upload responses. When the device
rejected a chunk (e.g. flash write error, image too large), the
response carries no useful offset, so MaxRxOff never reached the image
size and Run() kept looping forever. "newtmgr image upload" hung
instead of reporting the error.
Stop sending further chunks once a response with a non-zero rc arrives
and return the result, like the other multi-request commands (fs
upload/download, core load) do. Responses to requests still in flight
are ignored after the error so that the error response stays the last
one in the result and Status() reports the device's rc. The CLI then
prints "Error: <rc>" as it does for other failed commands.
Assisted-by: Claude:claude-opus-5-5
---
nmxact/xact/image.go | 42 +++++++++++++++++------
nmxact/xact/image_upload_test.go | 73 ++++++++++++++++++++++++++++++++++++++--
2 files changed, 102 insertions(+), 13 deletions(-)
diff --git a/nmxact/xact/image.go b/nmxact/xact/image.go
index 7de5745..7548074 100644
--- a/nmxact/xact/image.go
+++ b/nmxact/xact/image.go
@@ -65,6 +65,9 @@ type ImageUploadIntTracker struct {
WCap int
Off int
MaxRxOff int32
+
+ // Set when the device answered with a non-zero rc.
+ rspFailed bool
}
type ImageUploadResult struct {
@@ -267,14 +270,23 @@ func (t *ImageUploadIntTracker) HandleResponse(c *ImageUploadCmd, rsp nmp.NmpRsp
defer t.Mutex.Unlock()
wFull := false
- if rsp != nil {
+ // Once the device reported an error, responses to requests which
+ // were still in flight are ignored. This keeps the error response
+ // last in the result, so that Status() reports it.
+ if rsp != nil && !t.rspFailed {
irsp := rsp.(*nmp.ImageUploadRsp)
res.Rsps = append(res.Rsps, irsp)
- t.UpdateTracker(int(irsp.Off), IMAGE_UPLOAD_STATUS_RQ)
- // MaxRxOff is also read without the mutex by Run().
- if t.MaxRxOff < int32(irsp.Off) {
- atomic.StoreInt32(&t.MaxRxOff, int32(irsp.Off))
+ if irsp.Rc != 0 {
+ // The device rejected the request; stop the upload.
+ t.rspFailed = true
+ } else {
+ t.UpdateTracker(int(irsp.Off), IMAGE_UPLOAD_STATUS_RQ)
+
+ // MaxRxOff is also read without the mutex by Run().
+ if t.MaxRxOff < int32(irsp.Off) {
+ atomic.StoreInt32(&t.MaxRxOff, int32(irsp.Off))
+ }
}
if c.ProgressCb != nil {
c.ProgressCb(c, irsp)
@@ -351,6 +363,14 @@ func (c *ImageUploadCmd) Run(s sesn.Sesn) (Result, error) {
<-ch
}
+ // Stop if the device reported an error.
+ t.Mutex.Lock()
+ failed := t.rspFailed
+ t.Mutex.Unlock()
+ if failed {
+ break
+ }
+
t.ProcessMissedChunks()
if t.Off == len(c.Data) {
@@ -394,19 +414,21 @@ func (c *ImageUploadCmd) Run(s sesn.Sesn) (Result, error) {
}(int(r.Off))
}
- maxRxOff := int(atomic.LoadInt32(&t.MaxRxOff))
- if maxRxOff == len(c.Data) {
+ t.Mutex.Lock()
+ defer t.Mutex.Unlock()
+
+ // On a non-zero rc from the device, the result is returned as well;
+ // its Status() reports the device's rc.
+ if t.rspFailed || int(t.MaxRxOff) == len(c.Data) {
// Responses to requests still in flight may be processed after
// we return; hand out a snapshot of the result so that the
// caller does not race with them.
- t.Mutex.Lock()
- defer t.Mutex.Unlock()
snap := newImageUploadResult()
snap.Rsps = append(snap.Rsps, res.Rsps...)
return snap, nil
} else {
return nil, fmt.Errorf("ImageUpload unexpected error after %d/%d bytes",
- maxRxOff, len(c.Data))
+ t.MaxRxOff, len(c.Data))
}
}
diff --git a/nmxact/xact/image_upload_test.go b/nmxact/xact/image_upload_test.go
index f3c928c..39e76fc 100644
--- a/nmxact/xact/image_upload_test.go
+++ b/nmxact/xact/image_upload_test.go
@@ -40,8 +40,10 @@ type fakeImgDev struct {
upgrade bool
img int
- // If non-zero, all upload requests are answered with this rc.
- failRc int
+ // If non-zero, upload requests with an offset of at least failOff
+ // are answered with this rc.
+ failRc int
+ failOff uint32
// Offsets of requests answered with a timeout error, once each.
dropOffs map[uint32]bool
@@ -61,7 +63,7 @@ func (d *fakeImgDev) handle(req fakeReq) (nmp.NmpRsp, error) {
return nil, nmxutil.NewRspTimeoutError("NMP timeout")
}
- if d.failRc != 0 {
+ if d.failRc != 0 && ur.Off >= d.failOff {
return &nmp.ImageUploadRsp{Rc: d.failRc}, nil
}
@@ -531,3 +533,68 @@ func TestImageUpgradeRun(t *testing.T) {
mtx.Unlock()
}
}
+
+// A non-zero rc from the device must end the upload and be reported via
+// the result's status instead of making Run() loop forever.
+func TestImageUploadRunDeviceError(t *testing.T) {
+ data := testImage(5000)
+
+ for _, winSz := range []int{1, 5} {
+ for _, failOff := range []uint32{0, 1} {
+ dev := &fakeImgDev{
+ failRc: nmp.NMP_ERR_ENOMEM,
+ failOff: failOff,
+ }
+ s := newFakeSesn(dev.handle)
+ s.mtu = 200
+
+ var mtx sync.Mutex
+ var cbRcs []int
+ c := NewImageUploadCmd()
+ c.Data = data
+ c.MaxWinSz = winSz
+ c.ProgressCb = func(_ *ImageUploadCmd, r *nmp.ImageUploadRsp) {
+ mtx.Lock()
+ defer mtx.Unlock()
+ cbRcs = append(cbRcs, r.Rc)
+ }
+
+ res, err := runCmd(t, c, s)
+ if err != nil {
+ t.Fatalf("win %d fail at %d: %v", winSz, failOff, err)
+ }
+ if st := res.Status(); st != nmp.NMP_ERR_ENOMEM {
+ t.Errorf("win %d fail at %d: status %d", winSz, failOff,
+ st)
+ }
+
+ mtx.Lock()
+ if len(cbRcs) == 0 || cbRcs[len(cbRcs)-1] != nmp.NMP_ERR_ENOMEM {
+ t.Errorf("win %d fail at %d: progress rcs %v", winSz,
+ failOff, cbRcs)
+ }
+ mtx.Unlock()
+ }
+ }
+}
+
+func TestImageUpgradeRunDeviceError(t *testing.T) {
+ dev := &imgUpgradeDev{}
+ dev.failRc = nmp.NMP_ERR_ENOMEM
+ dev.failOff = 1
+ s := newFakeSesn(dev.handle)
+ dev.s = s
+
+ c := NewImageUpgradeCmd()
+ c.Data = testImage(3000)
+ c.MaxWinSz = 1
+ c.ProgressCb = func(*ImageUploadCmd, *nmp.ImageUploadRsp) {}
+
+ res, err := runCmd(t, c, s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if st := res.Status(); st != nmp.NMP_ERR_ENOMEM {
+ t.Errorf("status %d", st)
+ }
+}
(mynewt-newtmgr) 05/12: nmxact/xact: Default image upload window size
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sjanc pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mynewt-newtmgr.git
commit eb4fb87e9bc21383c95f8c94e16ccbd4cbba48de
Author: Szymon Janc <sz...@codecoup.pl>
AuthorDate: Thu Oct 22 01:00:17 2026 +0200
nmxact/xact: Default image upload window size
NewImageUploadCmd() and NewImageUpgradeCmd() leave MaxWinSz at zero,
which ImageUploadCmd.Run() uses as the capacity of the response and
error channels. With sessions which deliver the response from within
TxRxMgmtAsync() (serial, naked BLE), the send on the unbuffered channel
blocks before any receiver exists and the upload deadlocks on the
first chunk. The CLI is not affected as it always sets MaxWinSz, but
library users relying on the constructors hang.
Treat a MaxWinSz of zero or less as IMAGE_UPLOAD_DEF_MAX_WS, the same
default the CLI uses.
Assisted-by: Claude:claude-opus-5-5
---
nmxact/xact/image.go | 7 +++++++
nmxact/xact/image_upload_test.go | 26 ++++++++++++++++++++++++++
2 files changed, 33 insertions(+)
diff --git a/nmxact/xact/image.go b/nmxact/xact/image.go
index 7548074..f164ef6 100644
--- a/nmxact/xact/image.go
+++ b/nmxact/xact/image.go
@@ -340,6 +340,13 @@ func (t *ImageUploadIntTracker) HandleError(off int, err error) bool {
}
func (c *ImageUploadCmd) Run(s sesn.Sesn) (Result, error) {
+ // The window size is also the capacity of the response channels.
+ // Unbuffered channels deadlock with sessions which deliver the
+ // response before TxRxMgmtAsync() returns.
+ if c.MaxWinSz <= 0 {
+ c.MaxWinSz = IMAGE_UPLOAD_DEF_MAX_WS
+ }
+
res := newImageUploadResult()
// Signalled (without blocking) whenever a response or error has been
diff --git a/nmxact/xact/image_upload_test.go b/nmxact/xact/image_upload_test.go
index 39e76fc..9918602 100644
--- a/nmxact/xact/image_upload_test.go
+++ b/nmxact/xact/image_upload_test.go
@@ -598,3 +598,29 @@ func TestImageUpgradeRunDeviceError(t *testing.T) {
t.Errorf("status %d", st)
}
}
+
+// Commands created by the constructors must work without setting
+// MaxWinSz explicitly.
+func TestImageUploadRunDefaultWindow(t *testing.T) {
+ data := testImage(3000)
+
+ dev := &fakeImgDev{}
+ s := newFakeSesn(dev.handle)
+ uc := NewImageUploadCmd()
+ uc.Data = data
+ if _, err := runCmd(t, uc, s); err != nil {
+ t.Fatal(err)
+ }
+ checkUploaded(t, dev, data)
+
+ udev := &imgUpgradeDev{}
+ s = newFakeSesn(udev.handle)
+ udev.s = s
+ gc := NewImageUpgradeCmd()
+ gc.Data = data
+ gc.ProgressCb = func(*ImageUploadCmd, *nmp.ImageUploadRsp) {}
+ if _, err := runCmd(t, gc, s); err != nil {
+ t.Fatal(err)
+ }
+ checkUploaded(t, &udev.fakeImgDev, data)
+}
(mynewt-newtmgr) 10/12: nmxact/xact: Add unit tests for management commands
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sjanc pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mynewt-newtmgr.git
commit beee811bbe3cad4a19ee6b0ae056cc4cacefe94f
Author: Szymon Janc <sz...@codecoup.pl>
AuthorDate: Thu Oct 22 01:07:49 2026 +0200
nmxact/xact: Add unit tests for management commands
Add a table driven test running each single request command (echo,
datetime, config, stat, crash, reset, run, shell, mpstat, taskstat,
image state/erase, core list/erase and the log commands) against the
fake session. It checks the request header (op, group, id) and the
encoded body fields, that Status() reports the rc of the response
and that transport errors are returned.
Also cover the retry on response timeout via TxOptions.Tries, command
abort, and the multi request commands LogShowFullCmd (continues while
rc is 1, at the index after the last entry) and CoreLoadCmd (continues
until no data is returned, stops on rc != 0).
Assisted-by: Claude:claude-opus-5-5
---
nmxact/xact/cmds_test.go | 631 +++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 631 insertions(+)
diff --git a/nmxact/xact/cmds_test.go b/nmxact/xact/cmds_test.go
new file mode 100644
index 0000000..400c818
--- /dev/null
+++ b/nmxact/xact/cmds_test.go
@@ -0,0 +1,631 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package xact
+
+import (
+ "bytes"
+ "fmt"
+ "testing"
+
+ "mynewt.apache.org/newtmgr/nmxact/nmp"
+ "mynewt.apache.org/newtmgr/nmxact/nmxutil"
+)
+
+// rcDev answers every request with a response of the matching type
+// carrying the given rc.
+func rcDev(rc int) fakeHandler {
+ return func(req fakeReq) (nmp.NmpRsp, error) {
+ return rspFor(req, map[string]interface{}{"rc": rc})
+ }
+}
+
+func TestSimpleCmds(t *testing.T) {
+ hash := []byte{0xde, 0xad, 0xbe, 0xef}
+
+ tests := []struct {
+ name string
+ newCmd func() Cmd
+ op uint8
+ group uint16
+ id uint8
+ fields map[string]string
+
+ // Status() ignores the rc.
+ noRc bool
+ }{
+ {
+ name: "echo",
+ newCmd: func() Cmd {
+ c := NewEchoCmd()
+ c.Payload = "hello"
+ return c
+ },
+ op: nmp.NMP_OP_WRITE,
+ group: nmp.NMP_GROUP_DEFAULT,
+ id: nmp.NMP_ID_DEF_ECHO,
+ fields: map[string]string{"d": "hello"},
+ },
+ {
+ name: "datetime read",
+ newCmd: func() Cmd { return NewDateTimeReadCmd() },
+ op: nmp.NMP_OP_READ,
+ group: nmp.NMP_GROUP_DEFAULT,
+ id: nmp.NMP_ID_DEF_DATETIME_STR,
+ fields: map[string]string{},
+ },
+ {
+ name: "datetime write",
+ newCmd: func() Cmd {
+ c := NewDateTimeWriteCmd()
+ c.DateTime = "2026-10-22T10:00:00"
+ return c
+ },
+ op: nmp.NMP_OP_WRITE,
+ group: nmp.NMP_GROUP_DEFAULT,
+ id: nmp.NMP_ID_DEF_DATETIME_STR,
+ fields: map[string]string{"datetime": "2026-10-22T10:00:00"},
+ },
+ {
+ name: "config read",
+ newCmd: func() Cmd {
+ c := NewConfigReadCmd()
+ c.Name = "id/serial"
+ return c
+ },
+ op: nmp.NMP_OP_READ,
+ group: nmp.NMP_GROUP_CONFIG,
+ id: nmp.NMP_ID_CONFIG_VAL,
+ fields: map[string]string{"name": "id/serial"},
+ },
+ {
+ name: "config write",
+ newCmd: func() Cmd {
+ c := NewConfigWriteCmd()
+ c.Name = "a/b"
+ c.Val = "42"
+ c.Save = true
+ return c
+ },
+ op: nmp.NMP_OP_WRITE,
+ group: nmp.NMP_GROUP_CONFIG,
+ id: nmp.NMP_ID_CONFIG_VAL,
+ fields: map[string]string{
+ "name": "a/b",
+ "val": "42",
+ "save": "true",
+ },
+ },
+ {
+ name: "stat read",
+ newCmd: func() Cmd {
+ c := NewStatReadCmd()
+ c.Name = "ble_phy"
+ return c
+ },
+ op: nmp.NMP_OP_READ,
+ group: nmp.NMP_GROUP_STAT,
+ id: nmp.NMP_ID_STAT_READ,
+ fields: map[string]string{"name": "ble_phy"},
+ },
+ {
+ name: "stat list",
+ newCmd: func() Cmd { return NewStatListCmd() },
+ op: nmp.NMP_OP_READ,
+ group: nmp.NMP_GROUP_STAT,
+ id: nmp.NMP_ID_STAT_LIST,
+ fields: map[string]string{},
+ },
+ {
+ name: "crash",
+ newCmd: func() Cmd {
+ c := NewCrashCmd()
+ c.CrashType = CRASH_TYPE_ASSERT
+ return c
+ },
+ op: nmp.NMP_OP_WRITE,
+ group: nmp.NMP_GROUP_CRASH,
+ id: nmp.NMP_ID_CRASH_TRIGGER,
+ fields: map[string]string{"t": "assert"},
+ },
+ {
+ name: "reset",
+ newCmd: func() Cmd { return NewResetCmd() },
+ op: nmp.NMP_OP_WRITE,
+ group: nmp.NMP_GROUP_DEFAULT,
+ id: nmp.NMP_ID_DEF_RESET,
+ fields: map[string]string{},
+ noRc: true,
+ },
+ {
+ name: "run test",
+ newCmd: func() Cmd {
+ c := NewRunTestCmd()
+ c.Testname = "all"
+ c.Token = "tok"
+ return c
+ },
+ op: nmp.NMP_OP_WRITE,
+ group: nmp.NMP_GROUP_RUN,
+ id: nmp.NMP_ID_RUN_TEST,
+ fields: map[string]string{
+ "testname": "all",
+ "token": "tok",
+ },
+ },
+ {
+ name: "run list",
+ newCmd: func() Cmd { return NewRunListCmd() },
+ op: nmp.NMP_OP_READ,
+ group: nmp.NMP_GROUP_RUN,
+ id: nmp.NMP_ID_RUN_LIST,
+ fields: map[string]string{},
+ },
+ {
+ name: "shell exec",
+ newCmd: func() Cmd {
+ c := NewShellExecCmd()
+ c.Argv = []string{"echo", "hi"}
+ return c
+ },
+ op: nmp.NMP_OP_WRITE,
+ group: nmp.NMP_GROUP_SHELL,
+ id: nmp.NMP_ID_SHELL_EXEC,
+ fields: map[string]string{"argv": "[echo hi]"},
+ },
+ {
+ name: "mpstat",
+ newCmd: func() Cmd { return NewMempoolStatCmd() },
+ op: nmp.NMP_OP_READ,
+ group: nmp.NMP_GROUP_DEFAULT,
+ id: nmp.NMP_ID_DEF_MPSTAT,
+ fields: map[string]string{},
+ },
+ {
+ name: "taskstat",
+ newCmd: func() Cmd { return NewTaskStatCmd() },
+ op: nmp.NMP_OP_READ,
+ group: nmp.NMP_GROUP_DEFAULT,
+ id: nmp.NMP_ID_DEF_TASKSTAT,
+ fields: map[string]string{},
+ },
+ {
+ name: "image state read",
+ newCmd: func() Cmd { return NewImageStateReadCmd() },
+ op: nmp.NMP_OP_READ,
+ group: nmp.NMP_GROUP_IMAGE,
+ id: nmp.NMP_ID_IMAGE_STATE,
+ fields: map[string]string{},
+ },
+ {
+ name: "image state write",
+ newCmd: func() Cmd {
+ c := NewImageStateWriteCmd()
+ c.Hash = hash
+ c.Confirm = true
+ return c
+ },
+ op: nmp.NMP_OP_WRITE,
+ group: nmp.NMP_GROUP_IMAGE,
+ id: nmp.NMP_ID_IMAGE_STATE,
+ fields: map[string]string{
+ "hash": fmt.Sprint(hash),
+ "confirm": "true",
+ },
+ },
+ {
+ name: "image erase",
+ newCmd: func() Cmd { return NewImageEraseCmd() },
+ op: nmp.NMP_OP_WRITE,
+ group: nmp.NMP_GROUP_IMAGE,
+ id: nmp.NMP_ID_IMAGE_ERASE,
+ fields: map[string]string{},
+ },
+ {
+ name: "core list",
+ newCmd: func() Cmd { return NewCoreListCmd() },
+ op: nmp.NMP_OP_READ,
+ group: nmp.NMP_GROUP_IMAGE,
+ id: nmp.NMP_ID_IMAGE_CORELIST,
+ fields: map[string]string{},
+ },
+ {
+ name: "core erase",
+ newCmd: func() Cmd { return NewCoreEraseCmd() },
+ op: nmp.NMP_OP_WRITE,
+ group: nmp.NMP_GROUP_IMAGE,
+ id: nmp.NMP_ID_IMAGE_CORELOAD,
+ fields: map[string]string{},
+ },
+ {
+ name: "log show",
+ newCmd: func() Cmd {
+ c := NewLogShowCmd()
+ c.Name = "reboot_log"
+ c.Timestamp = 123
+ c.Index = 7
+ return c
+ },
+ op: nmp.NMP_OP_READ,
+ group: nmp.NMP_GROUP_LOG,
+ id: nmp.NMP_ID_LOG_SHOW,
+ fields: map[string]string{
+ "log_name": "reboot_log",
+ "ts": "123",
+ "index": "7",
+ },
+ },
+ {
+ name: "log list",
+ newCmd: func() Cmd { return NewLogListCmd() },
+ op: nmp.NMP_OP_READ,
+ group: nmp.NMP_GROUP_LOG,
+ id: nmp.NMP_ID_LOG_LIST,
+ fields: map[string]string{},
+ },
+ {
+ name: "log module list",
+ newCmd: func() Cmd { return NewLogModuleListCmd() },
+ op: nmp.NMP_OP_READ,
+ group: nmp.NMP_GROUP_LOG,
+ id: nmp.NMP_ID_LOG_MODULE_LIST,
+ fields: map[string]string{},
+ },
+ {
+ name: "log level list",
+ newCmd: func() Cmd { return NewLogLevelListCmd() },
+ op: nmp.NMP_OP_READ,
+ group: nmp.NMP_GROUP_LOG,
+ id: nmp.NMP_ID_LOG_LEVEL_LIST,
+ fields: map[string]string{},
+ },
+ {
+ name: "log clear",
+ newCmd: func() Cmd { return NewLogClearCmd() },
+ op: nmp.NMP_OP_WRITE,
+ group: nmp.NMP_GROUP_LOG,
+ id: nmp.NMP_ID_LOG_CLEAR,
+ fields: map[string]string{},
+ },
+ }
+
+ for _, tt := range tests {
+ for _, rc := range []int{0, nmp.NMP_ERR_EINVAL} {
+ s := newFakeSesn(rcDev(rc))
+
+ res, err := runCmd(t, tt.newCmd(), s)
+ if err != nil {
+ t.Errorf("%s rc %d: %v", tt.name, rc, err)
+ continue
+ }
+
+ wantRc := rc
+ if tt.noRc {
+ wantRc = 0
+ }
+ if st := res.Status(); st != wantRc {
+ t.Errorf("%s rc %d: status %d", tt.name, rc, st)
+ }
+
+ reqs := s.Requests()
+ if len(reqs) != 1 {
+ t.Fatalf("%s: %d requests", tt.name, len(reqs))
+ }
+ r := reqs[0]
+ if r.Hdr.Op != tt.op || r.Hdr.Group != tt.group ||
+ r.Hdr.Id != tt.id {
+
+ t.Errorf("%s: hdr op %d group %d id %d", tt.name,
+ r.Hdr.Op, r.Hdr.Group, r.Hdr.Id)
+ }
+ if len(r.Fields) != len(tt.fields) {
+ t.Errorf("%s: fields %v, want %v", tt.name, r.Fields,
+ tt.fields)
+ }
+ for k, v := range tt.fields {
+ if got := fmt.Sprint(r.Fields[k]); got != v {
+ t.Errorf("%s: field %q = %s, want %s", tt.name, k,
+ got, v)
+ }
+ }
+ }
+
+ // Transport errors are returned to the caller.
+ s := newFakeSesn(func(fakeReq) (nmp.NmpRsp, error) {
+ return nil, fmt.Errorf("tx failed")
+ })
+ if res, err := runCmd(t, tt.newCmd(), s); err == nil ||
+ res != nil {
+
+ t.Errorf("%s: tx error: res %v err %v", tt.name, res, err)
+ }
+ }
+}
+
+// Requests are retried on timeout (according to TxOptions.Tries) and
+// only on timeout.
+func TestCmdRetries(t *testing.T) {
+ tests := []struct {
+ name string
+ tries int
+ failures int
+ err error
+ wantReqs int
+ wantErr bool
+ }{
+ {"one try timeout", 1, 1, nmxutil.NewRspTimeoutError("t"), 1, true},
+ {"zero tries", 0, 1, nmxutil.NewRspTimeoutError("t"), 1, true},
+ {"retry ok", 3, 2, nmxutil.NewRspTimeoutError("t"), 3, false},
+ {"retries exhausted", 3, 3, nmxutil.NewRspTimeoutError("t"), 3,
+ true},
+ {"no retry on other error", 3, 1, fmt.Errorf("x"), 1, true},
+ }
+
+ for _, tt := range tests {
+ fails := tt.failures
+ s := newFakeSesn(func(req fakeReq) (nmp.NmpRsp, error) {
+ if fails > 0 {
+ fails--
+ return nil, tt.err
+ }
+ return rspFor(req, map[string]interface{}{"rc": 0})
+ })
+
+ c := NewEchoCmd()
+ opt := c.TxOptions()
+ opt.Tries = tt.tries
+ c.SetTxOptions(opt)
+
+ _, err := runCmd(t, c, s)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("%s: err %v", tt.name, err)
+ }
+ if n := len(s.Requests()); n != tt.wantReqs {
+ t.Errorf("%s: %d requests, want %d", tt.name, n, tt.wantReqs)
+ }
+ }
+}
+
+func TestCmdAbort(t *testing.T) {
+ s := newFakeSesn(rcDev(0))
+
+ c := NewEchoCmd()
+ if err := c.Abort(); err != nil {
+ t.Fatal(err)
+ }
+ _, err := runCmd(t, c, s)
+ if err == nil || err.Error() != "Command aborted" {
+ t.Errorf("err %v", err)
+ }
+ if n := len(s.Requests()); n != 0 {
+ t.Errorf("%d requests after abort", n)
+ }
+ if len(s.abortSeqs) != 0 {
+ t.Errorf("AbortRx called without a transaction in progress")
+ }
+
+ // A transaction in progress gets its receive aborted.
+ c = NewEchoCmd()
+ c.curSesn = s
+ c.curNmpSeq = 7
+ if err := c.Abort(); err != nil {
+ t.Fatal(err)
+ }
+ if len(s.abortSeqs) != 1 || s.abortSeqs[0] != 7 {
+ t.Errorf("AbortRx seqs %v", s.abortSeqs)
+ }
+
+ // A failing AbortRx is reported and does not mark the command
+ // aborted.
+ s.abortErr = fmt.Errorf("cannot abort")
+ c = NewEchoCmd()
+ c.curSesn = s
+ if err := c.Abort(); err == nil {
+ t.Errorf("AbortRx error not reported")
+ }
+ c.curSesn = nil
+ if _, err := runCmd(t, c, s); err != nil {
+ t.Errorf("command marked aborted: %v", err)
+ }
+}
+
+func TestCmdTxOptions(t *testing.T) {
+ c := NewEchoCmd()
+ if c.TxOptions() != NewEchoCmd().TxOptions() {
+ t.Errorf("default options differ")
+ }
+
+ opt := c.TxOptions()
+ opt.Tries = 5
+ opt.Timeout = 123
+ c.SetTxOptions(opt)
+ if c.TxOptions() != opt {
+ t.Errorf("options %+v, want %+v", c.TxOptions(), opt)
+ }
+}
+
+func logShowRsp(rc int, idxs ...uint32) *nmp.LogShowRsp {
+ rsp := &nmp.LogShowRsp{Rc: rc}
+ if idxs == nil {
+ return rsp
+ }
+
+ l := nmp.LogShowLog{Name: "log"}
+ for _, i := range idxs {
+ l.Entries = append(l.Entries, nmp.LogEntry{Index: i})
+ }
+ rsp.Logs = []nmp.LogShowLog{l}
+ return rsp
+}
+
+func TestLogShowFullRun(t *testing.T) {
+ tests := []struct {
+ name string
+ rsps []*nmp.LogShowRsp
+ wantIdxs []uint32
+ }{
+ {
+ name: "done at once",
+ rsps: []*nmp.LogShowRsp{logShowRsp(0, 3, 4)},
+ wantIdxs: []uint32{10},
+ },
+ {
+ name: "more logs",
+ rsps: []*nmp.LogShowRsp{
+ logShowRsp(1, 10, 11, 12),
+ logShowRsp(1, 13, 20),
+ logShowRsp(0, 21),
+ },
+ wantIdxs: []uint32{10, 13, 21},
+ },
+ {
+ name: "rc 1 without logs",
+ rsps: []*nmp.LogShowRsp{
+ logShowRsp(1, 10),
+ logShowRsp(1),
+ },
+ wantIdxs: []uint32{10, 11},
+ },
+ {
+ name: "rc 1 without entries",
+ rsps: []*nmp.LogShowRsp{
+ {Rc: 1, Logs: []nmp.LogShowLog{{Name: "log"}}},
+ },
+ wantIdxs: []uint32{10},
+ },
+ {
+ name: "error",
+ rsps: []*nmp.LogShowRsp{logShowRsp(nmp.NMP_ERR_ENOENT)},
+ wantIdxs: []uint32{10},
+ },
+ }
+
+ for _, tt := range tests {
+ i := 0
+ s := newFakeSesn(func(req fakeReq) (nmp.NmpRsp, error) {
+ if i >= len(tt.rsps) {
+ return nil, fmt.Errorf("unexpected request")
+ }
+ i++
+ return tt.rsps[i-1], nil
+ })
+
+ var cbs int
+ c := NewLogShowFullCmd()
+ c.Name = "log"
+ c.Index = 10
+ c.ProgressCb = func(*LogShowFullCmd, *nmp.LogShowRsp) { cbs++ }
+
+ res, err := runCmd(t, c, s)
+ if err != nil {
+ t.Fatalf("%s: %v", tt.name, err)
+ }
+
+ reqs := s.Requests()
+ if len(reqs) != len(tt.wantIdxs) {
+ t.Fatalf("%s: %d requests, want %d", tt.name, len(reqs),
+ len(tt.wantIdxs))
+ }
+ for j, r := range reqs {
+ lr := r.Body.(*nmp.LogShowReq)
+ if lr.Index != tt.wantIdxs[j] || lr.Name != "log" {
+ t.Errorf("%s: req %d: name %q index %d, want %d", tt.name,
+ j, lr.Name, lr.Index, tt.wantIdxs[j])
+ }
+ }
+
+ lres := res.(*LogShowFullResult)
+ if len(lres.Rsps) != len(reqs) || cbs != len(reqs) {
+ t.Errorf("%s: %d rsps, %d callbacks for %d requests",
+ tt.name, len(lres.Rsps), cbs, len(reqs))
+ }
+ if st := res.Status(); st != tt.rsps[len(tt.rsps)-1].Rc {
+ t.Errorf("%s: status %d", tt.name, st)
+ }
+ }
+}
+
+func TestCoreLoadRun(t *testing.T) {
+ core := testImage(1050)
+ chunk := 100
+
+ for _, failOff := range []int{-1, 0, 500} {
+ s := newFakeSesn(func(req fakeReq) (nmp.NmpRsp, error) {
+ r := req.Body.(*nmp.CoreLoadReq)
+ off := int(r.Off)
+ if failOff >= 0 && off >= failOff {
+ return &nmp.CoreLoadRsp{Rc: nmp.NMP_ERR_ENOENT}, nil
+ }
+ end := off + chunk
+ if end > len(core) {
+ end = len(core)
+ }
+ return &nmp.CoreLoadRsp{
+ Off: r.Off,
+ Len: uint32(len(core)),
+ Data: core[off:end],
+ }, nil
+ })
+
+ var got []byte
+ var cbs int
+ c := NewCoreLoadCmd()
+ c.ProgressCb = func(_ *CoreLoadCmd, r *nmp.CoreLoadRsp) {
+ cbs++
+ got = append(got, r.Data...)
+ }
+
+ res, err := runCmd(t, c, s)
+ if err != nil {
+ t.Fatalf("fail at %d: %v", failOff, err)
+ }
+
+ want := core
+ wantSt := 0
+ wantReqs := (len(core)+chunk-1)/chunk + 1
+ if failOff >= 0 {
+ want = core[:failOff]
+ wantSt = nmp.NMP_ERR_ENOENT
+ wantReqs = failOff/chunk + 1
+ }
+ if !bytes.Equal(got, want) {
+ t.Errorf("fail at %d: got %d bytes, want %d", failOff,
+ len(got), len(want))
+ }
+ if st := res.Status(); st != wantSt {
+ t.Errorf("fail at %d: status %d", failOff, st)
+ }
+ reqs := s.Requests()
+ if len(reqs) != wantReqs || cbs != wantReqs {
+ t.Errorf("fail at %d: %d requests, %d callbacks, want %d",
+ failOff, len(reqs), cbs, wantReqs)
+ }
+ for i, r := range reqs {
+ wantOff := i * chunk
+ if wantOff > len(core) {
+ wantOff = len(core)
+ }
+ if int(r.Body.(*nmp.CoreLoadReq).Off) != wantOff ||
+ r.Hdr.Op != nmp.NMP_OP_READ {
+
+ t.Errorf("fail at %d: req %d: %+v", failOff, i, r.Hdr)
+ }
+ }
+ }
+}
(mynewt-newtmgr) 08/12: nmxact/xact: Add unit tests for file upload and download
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sjanc pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mynewt-newtmgr.git
commit 72eca308ad011c051df7300aa073120287995d42
Author: Szymon Janc <sz...@codecoup.pl>
AuthorDate: Thu Oct 22 01:05:51 2026 +0200
nmxact/xact: Add unit tests for file upload and download
Cover the file upload request building with an MTU sweep for all
protocol variants (requests fit the MTU, chunks carry the right data,
name and len are always present, the final chunk is not padded) and
run FsUploadCmd and FsDownloadCmd against an emulated device: multi
chunk transfers, following the offset reported by the device, device
errors (rc != 0) ending the transfer, transport errors, too small MTU
and downloads continuing until the device returns no data.
Assisted-by: Claude:claude-opus-5-5
---
nmxact/xact/fs_test.go | 483 +++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 483 insertions(+)
diff --git a/nmxact/xact/fs_test.go b/nmxact/xact/fs_test.go
new file mode 100644
index 0000000..81798da
--- /dev/null
+++ b/nmxact/xact/fs_test.go
@@ -0,0 +1,483 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package xact
+
+import (
+ "bytes"
+ "fmt"
+ "sync"
+ "testing"
+
+ "mynewt.apache.org/newtmgr/nmxact/nmp"
+)
+
+func TestNextFsUploadReqMtuSweep(t *testing.T) {
+ data := testImage(3000)
+ name := "/cfg/some/file.bin"
+
+ for _, pv := range protoVariants {
+ for mtu := 0; mtu <= 1024; mtu++ {
+ if mtu > 300 && mtu%5 != 0 {
+ continue
+ }
+ s := newProtoSesn(pv, mtu, nil)
+
+ for _, off := range []int{0, 1, 1000, len(data) - 3,
+ len(data) - 1} {
+
+ pfx := fmt.Sprintf("%s mtu=%d off=%d", pv.name, mtu, off)
+
+ r, err := nextFsUploadReq(s, name, data, off)
+ if err != nil {
+ if mtu > 100 {
+ t.Errorf("%s: unexpected error: %v", pfx, err)
+ }
+ continue
+ }
+
+ if l := encLen(t, s, r.Msg()); l > mtu {
+ t.Errorf("%s: request len %d > mtu", pfx, l)
+ }
+ if len(r.Data) == 0 {
+ t.Errorf("%s: empty chunk", pfx)
+ }
+ if int(r.Off) != off {
+ t.Errorf("%s: off %d", pfx, r.Off)
+ }
+ if off+len(r.Data) > len(data) ||
+ !bytes.Equal(r.Data, data[off:off+len(r.Data)]) {
+
+ t.Errorf("%s: wrong chunk data", pfx)
+ }
+
+ // Name and length are mandatory (89f487a).
+ if r.Name != name || int(r.Len) != len(data) {
+ t.Errorf("%s: name %q len %d", pfx, r.Name, r.Len)
+ }
+ }
+ }
+ }
+}
+
+// The final chunk must not be padded (cdc971c).
+func TestNextFsUploadReqFinalChunk(t *testing.T) {
+ data := testImage(1000)
+
+ for _, pv := range protoVariants {
+ s := newProtoSesn(pv, 512, nil)
+
+ r, err := nextFsUploadReq(s, "f", data, len(data)-7)
+ if err != nil {
+ t.Fatalf("%s: %v", pv.name, err)
+ }
+ if !bytes.Equal(r.Data, data[len(data)-7:]) {
+ t.Errorf("%s: final chunk %d bytes, want 7", pv.name,
+ len(r.Data))
+ }
+
+ // Whole file fits a single request.
+ r, err = nextFsUploadReq(s, "f", data[:100], 0)
+ if err != nil {
+ t.Fatalf("%s: %v", pv.name, err)
+ }
+ if !bytes.Equal(r.Data, data[:100]) {
+ t.Errorf("%s: single chunk %d bytes, want 100", pv.name,
+ len(r.Data))
+ }
+ }
+}
+
+func TestNextFsUploadReqFields(t *testing.T) {
+ data := testImage(1000)
+ s := newFakeSesn(nil)
+
+ for _, off := range []int{0, 500} {
+ r, err := nextFsUploadReq(s, "/a/b", data, off)
+ if err != nil {
+ t.Fatal(err)
+ }
+ plain, err := nmp.EncodeNmpPlain(r.Msg())
+ if err != nil {
+ t.Fatal(err)
+ }
+ fields, err := decodeCborMap(plain[nmp.NMP_HDR_SIZE:])
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, k := range []string{"name", "len", "off", "data"} {
+ if _, ok := fields[k]; !ok {
+ t.Errorf("off %d: field %q missing: %v", off, k, fields)
+ }
+ }
+ }
+}
+
+// fakeFsDev emulates the file system handlers of a device.
+type fakeFsDev struct {
+ mtx sync.Mutex
+
+ files map[string][]byte
+
+ // Upload state.
+ upName string
+ upLen int
+
+ // Maximum amount of data per download response.
+ chunk int
+
+ // If non-zero, requests with an offset of at least failOff are
+ // answered with this rc.
+ failRc int
+ failOff uint32
+
+ // Number of requests handled.
+ reqs int
+}
+
+func newFakeFsDev() *fakeFsDev {
+ return &fakeFsDev{
+ files: map[string][]byte{},
+ chunk: 100,
+ }
+}
+
+func (d *fakeFsDev) handle(req fakeReq) (nmp.NmpRsp, error) {
+ d.mtx.Lock()
+ defer d.mtx.Unlock()
+
+ d.reqs++
+
+ switch r := req.Body.(type) {
+ case *nmp.FsUploadReq:
+ if d.failRc != 0 && r.Off >= d.failOff {
+ return &nmp.FsUploadRsp{Rc: d.failRc}, nil
+ }
+ if r.Off == 0 {
+ d.upName = r.Name
+ d.upLen = int(r.Len)
+ d.files[r.Name] = nil
+ }
+ f := d.files[r.Name]
+ if int(r.Off) == len(f) {
+ f = append(f, r.Data...)
+ d.files[r.Name] = f
+ }
+ return &nmp.FsUploadRsp{Off: uint32(len(f))}, nil
+
+ case *nmp.FsDownloadReq:
+ if d.failRc != 0 && r.Off >= d.failOff {
+ return &nmp.FsDownloadRsp{Rc: d.failRc}, nil
+ }
+ f, ok := d.files[r.Name]
+ if !ok {
+ return &nmp.FsDownloadRsp{Rc: nmp.NMP_ERR_ENOENT}, nil
+ }
+ off := int(r.Off)
+ if off > len(f) {
+ return &nmp.FsDownloadRsp{Rc: nmp.NMP_ERR_EINVAL}, nil
+ }
+ end := off + d.chunk
+ if end > len(f) {
+ end = len(f)
+ }
+ rsp := &nmp.FsDownloadRsp{
+ Off: r.Off,
+ Data: append([]byte{}, f[off:end]...),
+ }
+ if off == 0 {
+ rsp.Len = uint32(len(f))
+ }
+ return rsp, nil
+
+ default:
+ return nil, fmt.Errorf("unexpected request %T", req.Body)
+ }
+}
+
+func (d *fakeFsDev) file(name string) []byte {
+ d.mtx.Lock()
+ defer d.mtx.Unlock()
+
+ return d.files[name]
+}
+
+func TestFsUploadRun(t *testing.T) {
+ for _, pv := range protoVariants {
+ for _, sz := range []int{1, 100, 3000} {
+ data := testImage(sz)
+ dev := newFakeFsDev()
+ s := newProtoSesn(pv, 128, dev.handle)
+
+ var offs []uint32
+ c := NewFsUploadCmd()
+ c.Name = "/f"
+ c.Data = data
+ c.ProgressCb = func(_ *FsUploadCmd, r *nmp.FsUploadRsp) {
+ offs = append(offs, r.Off)
+ }
+
+ res, err := runCmd(t, c, s)
+ if err != nil {
+ t.Fatalf("%s sz %d: %v", pv.name, sz, err)
+ }
+ if st := res.Status(); st != 0 {
+ t.Errorf("%s sz %d: status %d", pv.name, sz, st)
+ }
+ if !bytes.Equal(dev.file("/f"), data) || dev.upLen != sz {
+ t.Errorf("%s sz %d: device has %d bytes, len %d", pv.name,
+ sz, len(dev.file("/f")), dev.upLen)
+ }
+
+ reqs := s.Requests()
+ if len(offs) != len(reqs) ||
+ int(offs[len(offs)-1]) != len(data) {
+
+ t.Errorf("%s sz %d: progress %v for %d requests",
+ pv.name, sz, offs, len(reqs))
+ }
+ for i, r := range reqs {
+ if r.EncLen > s.mtu {
+ t.Errorf("%s sz %d: req %d len %d > mtu", pv.name, sz,
+ i, r.EncLen)
+ }
+ }
+ }
+ }
+}
+
+// The next request uses the offset reported by the device.
+func TestFsUploadRunFollowsDeviceOff(t *testing.T) {
+ data := testImage(1000)
+ dev := newFakeFsDev()
+ s := newFakeSesn(nil)
+ s.mtu = 128
+
+ first := true
+ s.handler = func(req fakeReq) (nmp.NmpRsp, error) {
+ r := req.Body.(*nmp.FsUploadReq)
+ if first && r.Off > 0 {
+ // Pretend the device lost the previous chunk once.
+ first = false
+ return &nmp.FsUploadRsp{Off: 0}, nil
+ }
+ return dev.handle(req)
+ }
+
+ c := NewFsUploadCmd()
+ c.Name = "/f"
+ c.Data = data
+ if _, err := runCmd(t, c, s); err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(dev.file("/f"), data) {
+ t.Errorf("device has %d bytes", len(dev.file("/f")))
+ }
+
+ reqs := s.Requests()
+ if len(reqs) < 3 {
+ t.Fatalf("%d requests", len(reqs))
+ }
+ if reqs[2].Body.(*nmp.FsUploadReq).Off != 0 {
+ t.Errorf("request after rewind has off %d",
+ reqs[2].Body.(*nmp.FsUploadReq).Off)
+ }
+}
+
+func TestFsUploadRunDeviceError(t *testing.T) {
+ dev := newFakeFsDev()
+ dev.failRc = nmp.NMP_ERR_ENOMEM
+ dev.failOff = 1
+ s := newFakeSesn(dev.handle)
+ s.mtu = 128
+
+ c := NewFsUploadCmd()
+ c.Name = "/f"
+ c.Data = testImage(1000)
+
+ res, err := runCmd(t, c, s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if st := res.Status(); st != nmp.NMP_ERR_ENOMEM {
+ t.Errorf("status %d", st)
+ }
+ if n := len(s.Requests()); n != 2 {
+ t.Errorf("%d requests, want 2", n)
+ }
+}
+
+func TestFsUploadRunTxError(t *testing.T) {
+ s := newFakeSesn(func(fakeReq) (nmp.NmpRsp, error) {
+ return nil, fmt.Errorf("tx failed")
+ })
+
+ c := NewFsUploadCmd()
+ c.Name = "/f"
+ c.Data = testImage(10)
+ if _, err := runCmd(t, c, s); err == nil {
+ t.Errorf("no error")
+ }
+}
+
+func TestFsUploadRunMtuTooSmall(t *testing.T) {
+ dev := newFakeFsDev()
+ s := newFakeSesn(dev.handle)
+ s.mtu = 10
+
+ c := NewFsUploadCmd()
+ c.Name = "/f"
+ c.Data = testImage(10)
+ if _, err := runCmd(t, c, s); err == nil {
+ t.Errorf("no error")
+ }
+ if n := len(s.Requests()); n != 0 {
+ t.Errorf("%d requests", n)
+ }
+}
+
+func TestFsDownloadRun(t *testing.T) {
+ tests := []struct {
+ name string
+ sz int
+ chunk int
+ }{
+ {"empty", 0, 100},
+ {"one chunk", 50, 100},
+ {"exact chunks", 300, 100},
+ {"many chunks", 1234, 100},
+ }
+
+ for _, tt := range tests {
+ data := testImage(tt.sz)
+ dev := newFakeFsDev()
+ dev.chunk = tt.chunk
+ dev.files["/f"] = data
+ s := newFakeSesn(dev.handle)
+
+ var got []byte
+ c := NewFsDownloadCmd()
+ c.Name = "/f"
+ c.ProgressCb = func(_ *FsDownloadCmd, r *nmp.FsDownloadRsp) {
+ got = append(got, r.Data...)
+ }
+
+ res, err := runCmd(t, c, s)
+ if err != nil {
+ t.Fatalf("%s: %v", tt.name, err)
+ }
+ if st := res.Status(); st != 0 {
+ t.Errorf("%s: status %d", tt.name, st)
+ }
+
+ // The download continues until the device returns no data
+ // (e4c84d1).
+ if !bytes.Equal(got, data) {
+ t.Errorf("%s: got %d bytes, want %d", tt.name, len(got),
+ len(data))
+ }
+ var all []byte
+ for _, r := range res.(*FsDownloadResult).Rsps {
+ all = append(all, r.Data...)
+ }
+ if !bytes.Equal(all, data) {
+ t.Errorf("%s: result has %d bytes, want %d", tt.name,
+ len(all), len(data))
+ }
+
+ wantReqs := (tt.sz+tt.chunk-1)/tt.chunk + 1
+ reqs := s.Requests()
+ if len(reqs) != wantReqs {
+ t.Errorf("%s: %d requests, want %d", tt.name, len(reqs),
+ wantReqs)
+ }
+ for i, r := range reqs {
+ wantOff := i * tt.chunk
+ if wantOff > tt.sz {
+ wantOff = tt.sz
+ }
+ dr := r.Body.(*nmp.FsDownloadReq)
+ if dr.Name != "/f" || int(dr.Off) != wantOff {
+ t.Errorf("%s: req %d: name %q off %d", tt.name, i,
+ dr.Name, dr.Off)
+ }
+ if r.Hdr.Op != nmp.NMP_OP_READ ||
+ r.Hdr.Group != nmp.NMP_GROUP_FS ||
+ r.Hdr.Id != nmp.NMP_ID_FS_FILE {
+
+ t.Errorf("%s: req %d: hdr %+v", tt.name, i, r.Hdr)
+ }
+ }
+ }
+}
+
+func TestFsDownloadRunDeviceError(t *testing.T) {
+ for _, failOff := range []uint32{0, 100} {
+ dev := newFakeFsDev()
+ dev.files["/f"] = testImage(1000)
+ dev.failRc = nmp.NMP_ERR_EINVAL
+ dev.failOff = failOff
+ s := newFakeSesn(dev.handle)
+
+ var cbs int
+ c := NewFsDownloadCmd()
+ c.Name = "/f"
+ c.ProgressCb = func(*FsDownloadCmd, *nmp.FsDownloadRsp) { cbs++ }
+
+ res, err := runCmd(t, c, s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if st := res.Status(); st != nmp.NMP_ERR_EINVAL {
+ t.Errorf("fail at %d: status %d", failOff, st)
+ }
+ want := int(failOff)/dev.chunk + 1
+ if n := len(s.Requests()); n != want {
+ t.Errorf("fail at %d: %d requests, want %d", failOff, n, want)
+ }
+ // No progress callback for the error response.
+ if cbs != want-1 {
+ t.Errorf("fail at %d: %d callbacks", failOff, cbs)
+ }
+ }
+
+ // Missing file.
+ s := newFakeSesn(newFakeFsDev().handle)
+ c := NewFsDownloadCmd()
+ c.Name = "/nope"
+ res, err := runCmd(t, c, s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if st := res.Status(); st != nmp.NMP_ERR_ENOENT {
+ t.Errorf("missing file: status %d", st)
+ }
+}
+
+func TestFsDownloadRunTxError(t *testing.T) {
+ s := newFakeSesn(func(fakeReq) (nmp.NmpRsp, error) {
+ return nil, fmt.Errorf("tx failed")
+ })
+
+ c := NewFsDownloadCmd()
+ c.Name = "/f"
+ if _, err := runCmd(t, c, s); err == nil {
+ t.Errorf("no error")
+ }
+}
(mynewt-newtmgr) 03/12: nmxact/xact: Fix image upload window deadlock
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sjanc pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mynewt-newtmgr.git
commit ec0007b2a64ab77518c2fade28eefc1fb09207c2
Author: Szymon Janc <sz...@codecoup.pl>
AuthorDate: Thu Oct 22 00:58:22 2026 +0200
nmxact/xact: Fix image upload window deadlock
The image upload main loop blocked on an unbuffered channel send when
the window was full, and a response handler received from it only if
it observed the transition from a full window to one with a free slot.
With sessions which deliver responses quickly (serial, naked BLE, or
any session under load), a handler often saw the full window before
the main loop got to check it. The handler then blocked as a stale
receiver while the main loop found a free slot and went on. The next
time the window was full, the stale receiver let the main loop send one
request too many. With the window size growing by one per response
while the count of outstanding requests shrank by one, no handler saw
WCap == WCount anymore and the main loop waited forever: "newtmgr image
upload" with a window size > 1 occasionally hung (and leaked a
goroutine per stale receiver).
Replace the handshake with a non-blocking notification on a channel
with a buffer of one: each handler signals after processing a response
or error and the main loop re-checks the window after every wake-up.
A notification is never lost, as a pending one is kept in the buffer,
and handlers no longer block.
Add window sizes 2 and 5 to the upload tests and a stress test which
reliably hung before this change.
Assisted-by: Claude:claude-opus-5-5
---
nmxact/xact/image.go | 27 ++++++++++++++-------------
nmxact/xact/image_upload_test.go | 30 +++++++++++++++++++++++++++++-
2 files changed, 43 insertions(+), 14 deletions(-)
diff --git a/nmxact/xact/image.go b/nmxact/xact/image.go
index 3963c89..7de5745 100644
--- a/nmxact/xact/image.go
+++ b/nmxact/xact/image.go
@@ -329,7 +329,10 @@ func (t *ImageUploadIntTracker) HandleError(off int, err error) bool {
func (c *ImageUploadCmd) Run(s sesn.Sesn) (Result, error) {
res := newImageUploadResult()
- ch := make(chan int)
+
+ // Signalled (without blocking) whenever a response or error has been
+ // processed and a window slot may have been freed.
+ ch := make(chan int, 1)
rspc := make(chan nmp.NmpRsp, c.MaxWinSz)
errc := make(chan error, c.MaxWinSz)
@@ -344,8 +347,8 @@ func (c *ImageUploadCmd) Run(s sesn.Sesn) (Result, error) {
for int(atomic.LoadInt32(&t.MaxRxOff)) < len(c.Data) {
// Block if window is full
- if !t.CheckWindow() {
- ch <- 1
+ for !t.CheckWindow() {
+ <-ch
}
t.ProcessMissedChunks()
@@ -378,17 +381,15 @@ func (c *ImageUploadCmd) Run(s sesn.Sesn) (Result, error) {
go func(off int) {
select {
case err := <-errc:
- sig := t.HandleError(off, err)
- if sig {
- <-ch
- }
- return
+ t.HandleError(off, err)
case rsp := <-rspc:
- sig := t.HandleResponse(c, rsp, res)
- if sig {
- <-ch
- }
- return
+ t.HandleResponse(c, rsp, res)
+ }
+
+ // Wake up the main loop if it is waiting for a free slot.
+ select {
+ case ch <- 1:
+ default:
}
}(int(r.Off))
}
diff --git a/nmxact/xact/image_upload_test.go b/nmxact/xact/image_upload_test.go
index 1354cc6..f3c928c 100644
--- a/nmxact/xact/image_upload_test.go
+++ b/nmxact/xact/image_upload_test.go
@@ -131,6 +131,8 @@ func TestImageUploadRun(t *testing.T) {
{"one chunk", oneChunk, 1},
{"one chunk + 1", oneChunk + 1, 1},
{"many win 1", 10000, 1},
+ {"many win 2", 10000, 2},
+ {"many win 5", 10000, 5},
}
for _, tt := range tests {
@@ -296,7 +298,7 @@ func TestImageUploadRunProgress(t *testing.T) {
func TestImageUploadRunRetransmit(t *testing.T) {
data := testImage(5000)
- for _, winSz := range []int{1} {
+ for _, winSz := range []int{1, 5} {
s := newFakeSesn(nil)
s.mtu = 200
@@ -332,6 +334,32 @@ func TestImageUploadRunRetransmit(t *testing.T) {
}
}
+// Window based uploads used to deadlock occasionally: a response
+// handler could signal a free slot while the main loop was not waiting,
+// leaving a stale signal behind which let the loop overfill the window.
+// With the window then growing while the count shrank, no handler
+// observed a full window anymore and the main loop waited forever.
+// The deadlock depends on goroutine scheduling, so run many uploads.
+func TestImageUploadRunWindowStress(t *testing.T) {
+ data := testImage(2000)
+
+ for _, winSz := range []int{2, 5} {
+ for i := 0; i < 50; i++ {
+ dev := &fakeImgDev{}
+ s := newFakeSesn(dev.handle)
+ s.mtu = 128
+
+ c := NewImageUploadCmd()
+ c.Data = data
+ c.MaxWinSz = winSz
+ if _, err := runCmd(t, c, s); err != nil {
+ t.Fatalf("win %d iter %d: %v", winSz, i, err)
+ }
+ checkUploaded(t, dev, data)
+ }
+ }
+}
+
func TestImageUploadRunMtuTooSmall(t *testing.T) {
dev := &fakeImgDev{}
s := newFakeSesn(dev.handle)
(mynewt-newtmgr) 06/12: nmxact/xact: Allow image upgrade without progress callback
Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
sjanc pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mynewt-newtmgr.git
commit 2d03981a4951631b2d46d11f625dcd77b63981ef
Author: Szymon Janc <sz...@codecoup.pl>
AuthorDate: Thu Oct 22 01:00:42 2026 +0200
nmxact/xact: Allow image upgrade without progress callback
ImageUpgradeCmd wraps the user's progress callback to track the offset
for retries after a reconnect, but called the user's callback without
checking it for nil. Running an ImageUpgradeCmd without ProgressCb
(the default from NewImageUpgradeCmd()) crashed with a nil pointer
dereference on the first response. ImageUploadCmd already handles a
nil ProgressCb.
Assisted-by: Claude:claude-opus-5-5
---
nmxact/xact/image.go | 4 +++-
nmxact/xact/image_upload_test.go | 20 ++++++++++++++++++++
2 files changed, 23 insertions(+), 1 deletion(-)
diff --git a/nmxact/xact/image.go b/nmxact/xact/image.go
index f164ef6..cc021f1 100644
--- a/nmxact/xact/image.go
+++ b/nmxact/xact/image.go
@@ -533,7 +533,9 @@ func (c *ImageUpgradeCmd) runUpload(s sesn.Sesn) (*ImageUploadResult, error) {
if r.Rc == 0 {
startOff = int(r.Off)
}
- c.ProgressCb(uc, r)
+ if c.ProgressCb != nil {
+ c.ProgressCb(uc, r)
+ }
}
for {
diff --git a/nmxact/xact/image_upload_test.go b/nmxact/xact/image_upload_test.go
index 9918602..a27c447 100644
--- a/nmxact/xact/image_upload_test.go
+++ b/nmxact/xact/image_upload_test.go
@@ -624,3 +624,23 @@ func TestImageUploadRunDefaultWindow(t *testing.T) {
}
checkUploaded(t, &udev.fakeImgDev, data)
}
+
+func TestImageUpgradeRunNoProgressCb(t *testing.T) {
+ data := testImage(3000)
+ dev := &imgUpgradeDev{}
+ s := newFakeSesn(dev.handle)
+ dev.s = s
+
+ c := NewImageUpgradeCmd()
+ c.Data = data
+ c.MaxWinSz = 1
+
+ res, err := runCmd(t, c, s)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if st := res.Status(); st != 0 {
+ t.Errorf("status %d", st)
+ }
+ checkUploaded(t, &dev.fakeImgDev, data)
+}