fakeprinter

package
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Package fakeprinter is printers that are not there, for tests and for trying bdf print and bdf printd without paper. A Printer takes jobs over IPP (it is an http.Handler that answers as an IPP Everywhere printer does), over the raw port 9100, over LPD and over a serial line, keeps what it is sent, and can be told what to support, what to refuse and how to fail: it stops, forgets its jobs, restarts its job ids, cuts a connection, answers slowly. A CUPS is a CUPS server of such printers, with classes. Presets are printers of the kinds bdf prints to; the package readback turns what they received back into pages.

The command tools/fakeprinter runs a farm of them from a YAML file, with a page of what they received.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewUUID

func NewUUID() string

NewUUID returns a fresh urn:uuid, for a printer or a job.

func OpenPTY

func OpenPTY() (far *os.File, name string, err error)

OpenPTY opens a pseudo-terminal: its far end, which a serial printer reads (ServeSerial), and the name of the terminal a client opens as the printer's serial port. Both ends are raw: every byte arrives as it was sent.

func PJL

func PJL(data []byte) (lines []string, doc []byte, ok bool)

PJL returns the lines of the PJL header of a document, and the document in it; ok is false for a document without one.

func Sniff

func Sniff(b []byte) string

Sniff tells the format of a document from its first bytes: a MIME type for what IPP knows (application/pdf, application/postscript, image/pwg-raster, image/urf, image/jpeg, image/png), a language of print/pdl for labels and receipts ("zpl", "sbpl", "tpcl", "escpos", "escp"), "pcl", or "". A PJL header is looked through.

func Start

func Start(t testing.TB, p *Printer) string

Start serves the printer over IPP on the loopback until the test ends, and returns its URL.

func StartCUPS

func StartCUPS(t testing.TB, c *CUPS) string

StartCUPS serves the CUPS server on the loopback until the test ends, and returns its URL (ipp://127.0.0.1:port).

func StartSerial

func StartSerial(t testing.TB, p *Printer) string

StartSerial makes the printer read a pseudo-terminal until the test ends, and returns the terminal's name (what serial:// names); the test is skipped where there are none.

func StartTLS

func StartTLS(t testing.TB, p *Printer) string

StartTLS serves the printer over ipps on the loopback until the test ends, and returns its URL.

Types

type CUPS

type CUPS struct {
	// contains filtered or unexported fields
}

CUPS is a CUPS server of fake printers, as CUPS clients see one: each printer at /printers/<name>, each class at /classes/<name> (a job sent to a class goes to a member that is idle and accepting, in turn), and CUPS's own operations: CUPS-Get-Printers, CUPS-Get-Classes, CUPS-Get-Default, CUPS-Move-Job, CUPS-Accept-Jobs and CUPS-Reject-Jobs. The printers share one count of job ids, as CUPS's queues do.

func CUPSPreset

func CUPSPreset() *CUPS

CUPSPreset is a CUPS server of three printers and a class: "office" (office-mfp), "laser" (pwg-only) and "ps" (ps-office); the class "floor" of office and laser. office is the default.

func NewCUPS

func NewCUPS() *CUPS

NewCUPS returns a CUPS server without printers.

func (*CUPS) Add

func (c *CUPS) Add(ps ...*Printer)

Add adds printers. Their job ids are the server's from now.

func (*CUPS) AddClass

func (c *CUPS) AddClass(name string, members ...string)

AddClass adds a class of the printers named.

func (*CUPS) Printer

func (c *CUPS) Printer(name string) *Printer

Printer returns a printer by name, or nil.

func (*CUPS) Printers

func (c *CUPS) Printers() []*Printer

Printers returns the printers of the server.

func (*CUPS) Serve

func (c *CUPS) Serve(addr string) (*Server, error)

Serve serves the CUPS server at addr.

func (*CUPS) ServeHTTP

func (c *CUPS) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP answers an IPP request to the server, a printer or a class.

func (*CUPS) SetDefault

func (c *CUPS) SetDefault(name string)

SetDefault makes a printer or a class the default destination.

type Event

type Event struct {
	// Kind is "job" (a job came or changed), "jobs" (they were dropped)
	// or "state".
	Kind    string
	Printer string
	Job     int32
}

Event tells a watcher of a printer that something changed.

type Fault

type Fault struct {
	// AfterJobs waits for so many more jobs to be received (their last
	// document) before the fault happens; 0 does not wait.
	AfterJobs int `yaml:"after-jobs" json:"after-jobs,omitempty"`
	// After waits so long, from when the fault is injected or from its
	// last job.
	After time.Duration `yaml:"after" json:"after,omitempty"`

	// Stop stops the printer for these reasons (media-empty-error,
	// media-jam-error, door-open-error, toner-empty-error …); For resumes
	// it after so long (0: until Resume).
	Stop []string      `yaml:"stop" json:"stop,omitempty"`
	For  time.Duration `yaml:"for" json:"for,omitempty"`
	// Resume makes a stopped printer idle again.
	Resume bool `yaml:"resume" json:"resume,omitempty"`
	// Reject makes the printer refuse new jobs (not-accepting-jobs, and
	// LPD's refusal); Accept takes them again.
	Reject bool `yaml:"reject" json:"reject,omitempty"`
	Accept bool `yaml:"accept" json:"accept,omitempty"`
	// Forget drops the jobs the printer knows; Restart also counts the
	// job ids from 1 again.
	Forget  bool `yaml:"forget" json:"forget,omitempty"`
	Restart bool `yaml:"restart" json:"restart,omitempty"`
	// Abort makes the next job aborted.
	Abort bool `yaml:"abort" json:"abort,omitempty"`
	// CutAfter cuts the connection of the next document after so many
	// bytes (-1 or unset: not).
	CutAfter *int64 `yaml:"cut-after" json:"cut-after,omitempty"`
	// DropCreate cuts the connection of the next Create-Job before its
	// answer, once the job is made.
	DropCreate bool `yaml:"drop-create" json:"drop-create,omitempty"`
	// Busy refuses so many of the next jobs with server-error-busy.
	Busy int `yaml:"busy" json:"busy,omitempty"`
	// Latency and Bandwidth, when set, replace the printer's.
	Latency   *time.Duration `yaml:"latency" json:"latency,omitempty"`
	Bandwidth *int           `yaml:"bandwidth" json:"bandwidth,omitempty"`
	// NeverComplete, when set, keeps the jobs processing (or lets them
	// complete again).
	NeverComplete *bool `yaml:"never-complete" json:"never-complete,omitempty"`
	// NewCertificate makes the printer present a new self-signed
	// certificate over ipps (a client that pinned the old one refuses
	// it); ExpiredCertificate one that has expired.
	NewCertificate     bool `yaml:"new-certificate" json:"new-certificate,omitempty"`
	ExpiredCertificate bool `yaml:"expired-certificate" json:"expired-certificate,omitempty"`
	// contains filtered or unexported fields
}

Fault is something that happens to a printer: when it happens (after a number of jobs, after a time, or both: the time counts from the last of the jobs) and what happens. The tests and the farm's YAML write the same faults, so that a failure happens in the same order every time.

type Job

type Job struct {
	ID int32
	// Transport is "ipp", "socket", "lpd" or "serial".
	Transport string
	// Printer is the name of the printer that has it.
	Printer string
	Name    string
	User    string
	// Format is the document-format of the last document (IPP), or what
	// the data was told to be (raw: a language, "postscript", "pdf" …).
	Format string
	// Attrs are the job template attributes of an IPP job.
	Attrs     []ipp.Attribute
	Documents [][]byte
	// Queue and Control are the queue and the control file of an LPD job.
	Queue, Control string
	Created        time.Time
	UUID           string
	// contains filtered or unexported fields
}

Job is a job a printer received, over any transport.

func (*Job) Attr

func (j *Job) Attr(name string) string

Attr returns a job template attribute of an IPP job as a string, or "".

func (*Job) Data

func (j *Job) Data() []byte

Data returns the documents of a job, one after the other: what a raw printer was sent.

func (*Job) Document

func (j *Job) Document(n int) []byte

Document returns the bytes of a document of a job, for a test to look at.

type Listener

type Listener struct {
	// URL is the printer's URL: socket://host:port or lpd://host:port/queue.
	URL string
	// contains filtered or unexported fields
}

Listener is a raw transport of a printer on a port: the raw port 9100 or LPD.

func StartLPD

func StartLPD(t testing.TB, p *Printer, queue string) *Listener

StartLPD serves the printer as an LPD queue on the loopback until the test ends.

func StartSocket

func StartSocket(t testing.TB, p *Printer) *Listener

StartSocket serves the printer on a raw port (9100) of the loopback until the test ends.

func (*Listener) Addr

func (l *Listener) Addr() string

Addr is the address the printer listens at.

func (*Listener) Close

func (l *Listener) Close()

Close stops the listener: connections to it are refused.

func (*Listener) Reopen

func (l *Listener) Reopen() error

Reopen listens again at the address of a listener that was closed.

type Preset

type Preset struct {
	Name, Title string
	// Transport is how the kind is reached: "ipp", "socket", "lpd" or
	// "serial".
	Transport string
	// contains filtered or unexported fields
}

Preset is a kind of printer bdf prints to.

func LookupPreset

func LookupPreset(name string) (Preset, bool)

LookupPreset finds a preset by name.

func Presets

func Presets() []Preset

Presets are the presets, by name.

func (Preset) New

func (ps Preset) New(name string) *Printer

New makes a printer of the preset, named name.

type Printer

type Printer struct {
	// Name is printer-name; Info, Location and MakeModel the printer's
	// description; UUID printer-uuid.
	Name, Info, Location, MakeModel string
	UUID                            string
	// Formats are document-format-supported.
	Formats []string
	// Reject are formats refused with client-error-document-format-
	// not-supported although listed, to test a client's fallback.
	Reject      []string
	Media       []string
	MediaReady  []string
	Sources     []string // media-source-supported
	Types       []string // media-type-supported
	Sides       []string
	ColorModes  []string
	Qualities   []int
	Resolutions []ipp.Resolution
	Copies      ipp.Range
	PageRanges  bool
	Finishings  []int
	Scaling     []string
	OutputBins  []string

	PWGRasterTypes       []string
	PWGRasterResolutions []ipp.Resolution
	SheetBack            string
	URF                  []string
	// PCLmStripHeight, when not 0, makes the printer say it takes PCLm,
	// with these strips, back side, resolutions and compressions.
	PCLmStripHeight int
	PCLmBackSide    string
	PCLmResolutions []ipp.Resolution
	PCLmCompression []string

	// Language is what the printer takes on its raw transports (9100,
	// LPD, serial): a language of print/pdl ("zpl", "escpos" …),
	// "postscript", "pdf", "pcl", or "" for anything. With Width and DPI
	// (its dots across and resolution) it tells readback how to read a
	// job, and it makes the printer answer the status queries of its
	// language (ZPL ~HS, ESC/POS DLE EOT).
	Language   string
	Width, DPI int
	// Profile is the print/pdl profile a printer of a language is of
	// ("zd421-203"), which a client names in its URL (?profile=).
	Profile string

	State     ipp.PrinterState
	Reasons   []string
	Accepting bool

	// Username and Password, when set, are required as Basic
	// authentication.
	Username, Password string
	// IgnoreUnsupported takes a job whose attributes the printer does not
	// support without ipp-attribute-fidelity, ignoring them
	// (successful-ok-ignored-or-substituted-attributes), as RFC 8011
	// says; by default the printer refuses it, as many printers do.
	IgnoreUnsupported bool
	// NoCustom makes the printer one that knows no attribute of one's
	// own (x-…): such an attribute is unsupported.
	NoCustom bool
	// Only11 refuses IPP/2.x with server-error-version-not-supported.
	Only11 bool
	// NoChunked refuses requests without a length (chunked), with HTTP
	// 411, as old printers do.
	NoChunked bool
	// Processing is how long a job stays processing after its last
	// document before it is completed.
	Processing time.Duration
	// Busy refuses so many of the next Create-Job and Print-Job with
	// server-error-busy, as a printer that is printing for others does.
	Busy int
	// Latency delays each IPP answer and each raw connection's first
	// byte; Bandwidth (bytes a second, 0 for no bound) slows what the
	// printer reads, as a slow printer's buffer does.
	Latency   time.Duration
	Bandwidth int
	// NeverComplete keeps every job processing.
	NeverComplete bool
	// Dir saves each document to a file "<job>-<n>.<ext>" when set.
	Dir string
	// Limits bound the decoding of requests.
	Limits *ipp.Limits
	// MaxDocument bounds a document the printer keeps (256 MiB when 0).
	MaxDocument int64

	// Requests counts the operations received, by name.
	Requests map[string]int
	// contains filtered or unexported fields
}

Printer is a printer that is not there. New gives one with the capabilities of a plain office printer; change the fields before it is served, and through the methods while it is.

func FromProfile

func FromProfile(prof pdl.Profile) *Printer

FromProfile makes a printer of a profile of print/pdl: its language, dots and resolution, over the raw transports.

func New

func New() *Printer

New returns a printer with the capabilities of a plain office printer: PDF, PWG Raster and JPEG, A4, Letter, B5 and A3, two-sided, colour, 300 and 600 dpi, up to 99 copies.

func (*Printer) Abort

func (p *Printer) Abort(id int32)

Abort makes a job aborted, to test a client's handling.

func (*Printer) AbortNext

func (p *Printer) AbortNext()

AbortNext makes the next job the printer receives aborted.

func (*Printer) Back

func (p *Printer) Back(back string)

Back sets what a printer of the raw port says back once it has a job.

func (*Printer) Certificate

func (p *Printer) Certificate() *x509.Certificate

Certificate is the certificate the printer presents over ipps now, or nil.

func (*Printer) CutAfter

func (p *Printer) CutAfter(n int64)

CutAfter cuts the connection of the next document sent after n bytes of it (n >= 0), as a network that fails does; the job keeps no document. Over LPD the connection is cut once the data file is sent, before the control file, whatever n is.

func (*Printer) CutControl

func (p *Printer) CutControl()

CutControl cuts the connection of the next LPD job in its control file.

func (*Printer) DropCreateResponse

func (p *Printer) DropCreateResponse()

DropCreateResponse makes the next Create-Job make its job and then cut the connection before answering: the client does not learn the job.

func (*Printer) Forget

func (p *Printer) Forget()

Forget drops the jobs the printer knows, as a printer that keeps no history does: their ids are not reused.

func (*Printer) Inject

func (p *Printer) Inject(f Fault)

Inject adds a fault to the printer: it happens at once, or when its jobs have come and its time has passed.

func (*Printer) Job

func (p *Printer) Job(id int32) *Job

Job returns a job by id, or nil.

func (*Printer) JobState

func (p *Printer) JobState(j *Job) ipp.JobState

JobState returns the state of a job now.

func (*Printer) Jobs

func (p *Printer) Jobs() []*Job

Jobs returns the jobs received, oldest first.

func (*Printer) ListenLPD

func (p *Printer) ListenLPD(addr, queue string) (*Listener, error)

ListenLPD serves the printer as an LPD queue (RFC 1179) at addr.

func (*Printer) ListenSocket

func (p *Printer) ListenSocket(addr string) (*Listener, error)

ListenSocket serves the printer on the raw port (9100) at addr ("127.0.0.1:0" for any free port of the loopback).

func (*Printer) Refuse

func (p *Printer) Refuse(refuse bool)

Refuse makes the printer refuse jobs on LPD (its queue is disabled), or take them again.

func (*Printer) Restart

func (p *Printer) Restart()

Restart forgets the jobs and counts the job ids from 1 again, as a printer that was switched off and on does: a client that kept a job id finds another job, or none, under it.

func (*Printer) Resume

func (p *Printer) Resume()

Resume makes a stopped printer idle again.

func (*Printer) ServeHTTP

func (p *Printer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP answers an IPP request at any path.

func (*Printer) ServeIPP

func (p *Printer) ServeIPP(addr string) (*Server, error)

ServeIPP serves the printer over IPP at addr ("127.0.0.1:0" for any free port of the loopback), at /ipp/print.

func (*Printer) ServeIPPS

func (p *Printer) ServeIPPS(addr string) (*Server, error)

ServeIPPS serves the printer over ipps at addr with a self-signed certificate for localhost (a fault can change it: NewCertificate, ExpiredCertificate).

func (*Printer) ServeLPD

func (p *Printer) ServeLPD(c net.Conn)

ServeLPD takes a receive-job command (RFC 1179) and its files on a connection.

func (*Printer) ServeSerial

func (p *Printer) ServeSerial(rw io.ReadWriter, idle time.Duration) error

ServeSerial reads jobs from a serial line (the far end of a pseudo-terminal): a job ends when nothing comes for idle (a serial printer has no end of job but the gap after it).

func (*Printer) ServeSocket

func (p *Printer) ServeSocket(c net.Conn)

ServeSocket serves a connection of the raw port: everything sent until the sender closes its side is a job. A connection that sends nothing is a check, not a job.

func (*Printer) SetAccepting

func (p *Printer) SetAccepting(ok bool)

SetAccepting makes the printer take jobs or refuse them (server-error-not-accepting-jobs, and LPD's refusal).

func (*Printer) Snapshot

func (p *Printer) Snapshot() Status

Snapshot returns the printer's state now.

func (*Printer) Stop

func (p *Printer) Stop(reasons ...string)

Stop stops the printer for reasons ("media-empty-error" …): it answers as stopped and does not finish its jobs until Resume.

func (*Printer) Watch

func (p *Printer) Watch(c chan<- Event) (stop func())

Watch sends the printer's events to c until stop is called; an event that c has no room for is dropped.

type Raw

type Raw struct {
	*Printer
	*Listener
}

Raw is a printer served on a raw transport: what it received, how it fails (the Printer's), and where it is (the Listener's URL).

func NewLPD

func NewLPD(t testing.TB, queue string) *Raw

NewLPD starts a printer that takes anything as an LPD queue on the loopback, until the test ends.

func NewSocket

func NewSocket(t testing.TB) *Raw

NewSocket starts a printer that takes anything on a raw port (9100) of the loopback, until the test ends.

type Server

type Server struct {
	// URL is the printer's URL (ipp://host:port/ipp/print, or ipps://),
	// or the CUPS server's (ipp://host:port).
	URL  string
	Addr string
	// contains filtered or unexported fields
}

Server is a printer (or a CUPS) served over IPP on a port.

func (*Server) Close

func (s *Server) Close() error

Close stops the server.

type Status

type Status struct {
	State     ipp.PrinterState
	Reasons   []string
	Accepting bool
}

Status is a printer's state at a moment.

Directories

Path Synopsis
Package readback turns what a fake printer received back into pages: the images of PWG Raster and Apple Raster as they are, PDF and PCLm drawn (converter/pdf, then raster/imagebdf), PostScript drawn by Ghostscript where it is, JPEG and PNG decoded, and the label, receipt and dot-matrix languages read as their printers print them (print/pdl): their dots, and the commands of the printer's own barcodes.
Package readback turns what a fake printer received back into pages: the images of PWG Raster and Apple Raster as they are, PDF and PCLm drawn (converter/pdf, then raster/imagebdf), PostScript drawn by Ghostscript where it is, JPEG and PNG decoded, and the label, receipt and dot-matrix languages read as their printers print them (print/pdl): their dots, and the commands of the printer's own barcodes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL