1package sheet23import (4 "bytes"5 "strings"6 "testing"7)89func TestProtect(t *testing.T) {10 s := New()11 s.Protect(Protection{Range: rng("B2:C4"), Desc: "Totals"})12 if p, ok := s.Protecting(rng("C4:D9")); !ok || p.Desc != "Totals" {13 t.Errorf("Protecting overlap = %+v, %v", p, ok)14 }15 if _, ok := s.Protecting(rng("A1:A9")); ok {16 t.Error("A1:A9 protected")17 }18 // Protections follow inserted and deleted rows, and undo.19 s.InsertRows(0, 1)20 if got := s.Protections(); len(got) != 1 || got[0].Range != rng("B3:C5") {21 t.Errorf("after insert %+v", got)22 }23 s.DeleteRows(2, 3)24 if got := s.Protections(); len(got) != 0 {25 t.Errorf("all rows deleted, still %+v", got)26 }27 s.Undo()28 s.Undo()29 if got := s.Protections(); len(got) != 1 || got[0].Range != rng("B2:C4") {30 t.Errorf("after undo %+v", got)31 }32 // The whole sheet: everything is protected, once.33 s.Protect(Protection{Sheet: true})34 s.Protect(Protection{Sheet: true, Desc: "Final"})35 if got := s.Protections(); len(got) != 2 || got[1].Label() != "Final" {36 t.Errorf("sheet protections %+v", got)37 }38 if _, ok := s.Protecting(rng("Z99")); !ok {39 t.Error("sheet protection doesn't cover Z99")40 }41 if n := s.UnprotectRange(rng("A1")); n != 1 {42 t.Errorf("UnprotectRange(A1) = %d", n)43 }44 s.Unprotect(0)45 if len(s.Protections()) != 0 {46 t.Errorf("left %+v", s.Protections())47 }48 s.Undo()49 if len(s.Protections()) != 1 {50 t.Errorf("undo unprotect %+v", s.Protections())51 }52}5354func TestProtectFile(t *testing.T) {55 s := New()56 s.Set(at("A1"), "x")57 s.Protect(Protection{Range: rng("A1:B2"), Desc: "Inputs"})58 s.Protect(Protection{Sheet: true})59 var b bytes.Buffer60 if err := s.Write(&b); err != nil {61 t.Fatal(err)62 }63 if !strings.Contains(b.String(), `"protected": [{"range":"A1:B2","description":"Inputs"},{"sheet":true}]`) || !strings.Contains(b.String(), `"version": 2`) {64 t.Errorf("file:\n%s", b.String())65 }66 got, err := Read(&b)67 if err != nil {68 t.Fatal(err)69 }70 if ps := got.Protections(); len(ps) != 2 || ps[0].Range != rng("A1:B2") || !ps[1].Sheet {71 t.Errorf("read back %+v", ps)72 }73}