Documentation
¶
Overview ¶
Package graphmock provides a typed fake Microsoft Graph endpoint for tests.
Handlers return Go values rather than JSON strings, so a response is built through the same marshaling the production code uses. A hand-written string literal cannot drift-check against a model: rename a field or change a tag and the literal keeps parsing, so the test keeps passing while the code is wrong.
The second purpose matters more. A fake that agrees with everything is a mirror, not a test. Real Graph refuses filters that OData permits, pages delta far smaller than callers expect, and omits headers callers assume are there. ExchangeMail encodes those refusals, so a request the service would reject is rejected here too, at the speed of a unit test.
Index ¶
- Constants
- Variables
- func Decode[T any](tb testing.TB, r *Request) T
- type Constraint
- func CapPageSize(maxSize int) Constraint
- func CapTop(pathFragment string, maxTop int) Constraint
- func ExchangeCalendar() []Constraint
- func ExchangeMail() []Constraint
- func ExchangeOutlook() []Constraint
- func IgnoreMismatchedMessageFilter() Constraint
- func RejectAscendingMessageSort() Constraint
- func RejectFilterOnCalendarView() Constraint
- func RejectRecipientLambdas() Constraint
- func RejectSearchSort() Constraint
- func RejectSelectOnMessages() Constraint
- func RejectStaleETag(current string) Constraint
- func RejectUnsupportedChannelMessageOptions() Constraint
- func RejectUnsupportedFilterFunctions(extra ...string) Constraint
- func RejectUnsupportedMessageSortProperty(sortable ...string) Constraint
- func RequireAllDayAtMidnight() Constraint
- func RequireAuthorization() Constraint
- func RequireCalendarWindow() Constraint
- func RequireHeader(name, code, message string) Constraint
- func RequireRuleSequence() Constraint
- func RequireScopes(granted ...string) Constraint
- func RequireSearchEntityTypes(required ...string) Constraint
- func RequireSortableFilter(sortable ...string) Constraint
- func Teams() []Constraint
- type Handler
- type Option
- type Query
- type Recorded
- type Request
- type Response
- func Collection[T any](items []T, nextLink string) Response
- func Created[T any](value T) Response
- func Delta[T any](items []T, deltaLink string) Response
- func Empty(status int) Response
- func Fault(status int, code, message string) Response
- func Item[T any](value T) Response
- func OutlookChunkAccepted(receivedSoFar int64) Response
- func OutlookChunkComplete[T any](attachment T) Response
- func Raw(status int, contentType string, body []byte) Response
- func Throttled(retryAfterSeconds int) Response
- type Server
- func (s *Server) Client(opts ...msgraph.Option) *msgraph.Client
- func (s *Server) Handle(pattern string, handler Handler)
- func (s *Server) Link(path string, query ...string) string
- func (s *Server) Requests() []Recorded
- func (s *Server) Reset()
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Server) URL() string
- type Shaper
- func DropSenderOnSystemEvents() Shaper
- func DropTopicOnOneOnOneChats() Shaper
- func HideEnumsWithoutPrefer() Shaper
- func NameZonesTheWindowsWay(zone string) Shaper
- func PageExpandedReplies(limit int) Shaper
- func PopulateOnlyJoinedTeamsFields() Shaper
- func RootChannelMessagesOnly() Shaper
- func StripHeader(name string) Shaper
- func TeamsShapers() []Shaper
- func TruncateExpandedMembers(limit int) Shaper
Constants ¶
const ( // TeamsChatPageCap is the largest page the chat listing serves. TeamsChatPageCap = 50 // TeamsMessagePageCap is the largest page a chat or channel message // listing serves. TeamsMessagePageCap = 50 // TeamsChannelMessageDefaultPageSize is what a channel message listing // returns when $top says nothing, which is well under the cap. TeamsChannelMessageDefaultPageSize = 20 // TeamsExpandedMemberCap is how many members $expand=members returns, // however many the chat has and whatever $top asks for. There is no // continuation link for the rest. TeamsExpandedMemberCap = 25 // TeamsExpandedReplyCap is how many replies $expand=replies returns // before paging the remainder through a per-message link. TeamsExpandedReplyCap = 200 // TeamsSearchPageCap is the largest message search page. TeamsSearchPageCap = 25 )
Page and expansion limits the Teams endpoints apply.
None of these is announced. Every one is a number the service silently substitutes for whatever was asked, so a caller that gets exactly this many items cannot tell a truncated answer from a complete one.
const ExchangeCalendarPageCap = 1000
ExchangeCalendarPageCap is the largest page Exchange returns for a calendar view, whatever odata.maxpagesize asks for.
const ExchangeMailDeltaDefaultPageSize = 10
ExchangeMailDeltaDefaultPageSize is how many messages a delta query returns when no page size is requested. It is small enough that walking a large mailbox without asking for more takes tens of thousands of requests.
const ExchangeMailPageCap = 512
ExchangeMailPageCap is the largest page Exchange will return for mail, whatever odata.maxpagesize asks for.
Variables ¶
var ExchangeMailSortableFields = []string{
"isRead",
"isDraft",
"receivedDateTime",
"sentDateTime",
"categories",
}
ExchangeMailSortableFields are the message properties Exchange will filter on while also sorting. Filtering on anything else alongside an $orderby is refused, because no index serves both at once.
var TeamsMessageSortableFields = []string{"createdDateTime", "lastModifiedDateTime"}
TeamsMessageSortableFields are the only two properties a message listing will order by. Both are timestamps, and neither can be ordered ascending.
var WindowsTimeZones = []string{
"Pacific Standard Time",
"Eastern Standard Time",
"GMT Standard Time",
"W. Europe Standard Time",
"Tokyo Standard Time",
"E. South America Standard Time",
}
WindowsTimeZones are the names Graph uses when a request asks for a zone. None is an IANA name, so none resolves through Go's time package: a client that assumes otherwise computes the wrong instant without an error anywhere.
Functions ¶
Types ¶
type Constraint ¶
A Constraint inspects a request and returns a rejection, or nil to let it through. Constraints exist so the fake refuses what the real service refuses: every one here was established by running the request against a live mailbox and reading the error back.
func CapPageSize ¶
func CapPageSize(maxSize int) Constraint
CapPageSize truncates an oversized odata.maxpagesize request rather than failing it, which is what Graph does.
func CapTop ¶ added in v0.13.0
func CapTop(pathFragment string, maxTop int) Constraint
CapTop clamps an oversized $top on any path containing the fragment, the way Teams does.
It is a clamp and not a rejection because the service serves fewer items without comment. A caller that asked for two hundred and received fifty has no way to distinguish that from a chat holding fifty messages, which is why a client needs to be told the number it asked for was not honored rather than inferring completeness from a short page.
func ExchangeCalendar ¶ added in v0.10.0
func ExchangeCalendar() []Constraint
ExchangeCalendar returns the constraints a real Outlook calendar applies.
The calendar rules differ from the mail ones in kind, not just in detail: a calendar view is a distinct resource with required parameters rather than a filtered collection, and getting that wrong produces an empty or wrong answer rather than an error.
func ExchangeMail ¶
func ExchangeMail() []Constraint
ExchangeMail returns the constraints a real Outlook mailbox applies.
Using these turns a class of production-only failure into a test failure: a filter Exchange cannot serve is rejected here with the same error code.
func ExchangeOutlook ¶ added in v0.11.0
func ExchangeOutlook() []Constraint
ExchangeOutlook returns the constraints that apply across an Outlook mailbox, beyond the mail and calendar sets.
Each one here was a bug before it was a constraint. The service does not refuse these in a way anyone would guess, so a fake that answered optimistically let the mistake through and the suite stayed green.
func IgnoreMismatchedMessageFilter ¶ added in v0.13.0
func IgnoreMismatchedMessageFilter() Constraint
IgnoreMismatchedMessageFilter drops a $filter that names a property the $orderby does not, the way a Teams message listing does.
This is the most dangerous behavior in the Teams API and the reason this bundle exists. The service does not refuse the request and does not warn: it discards the filter and answers the whole collection, successfully. A caller asking for the last day of a chat gets a year of it and renders the lot as today. A filter with no $orderby at all is discarded the same way.
So this drops the filter rather than rejecting the request. Rejecting would be easier to test against and would be fiction -- a failure mode production never exhibits -- and a client written against a fake that refuses would still be wrong against the service that does not.
func RejectAscendingMessageSort ¶ added in v0.13.0
func RejectAscendingMessageSort() Constraint
RejectAscendingMessageSort refuses an ascending order on a message listing.
Descending is the only direction served. This one the service does refuse, so a caller wanting oldest-first has to page the whole range and reverse it -- worth discovering in a test rather than after building a transcript view around an ordering that does not exist.
func RejectFilterOnCalendarView ¶ added in v0.10.0
func RejectFilterOnCalendarView() Constraint
RejectFilterOnCalendarView refuses a $filter on start or end in a calendar view.
The window is what selects events; expressing it as a filter as well is a misunderstanding the service does not correct, because it silently ignores the filter and returns the whole window.
func RejectRecipientLambdas ¶
func RejectRecipientLambdas() Constraint
RejectRecipientLambdas refuses any/all over a recipient collection, which Exchange answers with ErrorInvalidUrlQueryFilter however it is written.
func RejectSearchSort ¶ added in v0.13.0
func RejectSearchSort() Constraint
RejectSearchSort refuses sortProperties on a chatMessage search.
Message hits come back in relevance order and nothing can change that. A caller building a chronological view from search results has to sort them itself, and finding that out here is cheaper than finding it out after the view exists.
func RejectSelectOnMessages ¶ added in v0.13.0
func RejectSelectOnMessages() Constraint
RejectSelectOnMessages refuses $select and $expand on a message listing.
Unlike the filter, these are genuinely refused, which is the distinction worth encoding: a caller may reasonably expect $select to trim a chat message and it returns 400 instead. The one exception is expanding replies on a channel message collection, which is supported and is the only way to read a thread in one request.
func RejectStaleETag ¶ added in v0.11.0
func RejectStaleETag(current string) Constraint
RejectStaleETag refuses a conditional write whose If-Match does not name the current version.
Exchange answers a stale mail tag with 400 and ErrorInvalidChangeKey, not the 412 the header implies, so the obvious precondition check misses it and the write looks like an ordinary bad request.
func RejectUnsupportedChannelMessageOptions ¶ added in v0.13.1
func RejectUnsupportedChannelMessageOptions() Constraint
RejectUnsupportedChannelMessageOptions keeps the channel collection and reply collection distinct from chat messages. Channel roots support $top and $expand=replies; replies support $top. Continuation links may also carry $skiptoken. Neither endpoint accepts the chat listing's $filter or $orderby.
func RejectUnsupportedFilterFunctions ¶
func RejectUnsupportedFilterFunctions(extra ...string) Constraint
RejectUnsupportedFilterFunctions refuses filter functions Exchange does not implement. endswith is the notable one: it is valid OData and valid on other Graph resources, but on mail it answers ErrorInvalidUrlQueryFilter, so a "sender is at this domain" filter can never work.
func RejectUnsupportedMessageSortProperty ¶ added in v0.13.0
func RejectUnsupportedMessageSortProperty(sortable ...string) Constraint
RejectUnsupportedMessageSortProperty refuses an $orderby on anything but the two timestamps a message listing indexes.
func RequireAllDayAtMidnight ¶ added in v0.11.0
func RequireAllDayAtMidnight() Constraint
RequireAllDayAtMidnight refuses an all-day event whose ends are not midnight.
An all-day event is a pair of calendar dates rather than instants, and the service enforces that by requiring both ends at midnight. It reports the refusal without naming which end was wrong, and a client reading dates in a local zone produces exactly this shape without noticing.
func RequireAuthorization ¶
func RequireAuthorization() Constraint
RequireAuthorization refuses a request without a bearer token, which is the single most embarrassing thing for a client to get wrong.
func RequireCalendarWindow ¶ added in v0.10.0
func RequireCalendarWindow() Constraint
RequireCalendarWindow refuses a calendar view that does not name the range it wants.
The service treats startDateTime and endDateTime as required parameters of the resource, not as an optional filter, and answers a request without them with ErrorInvalidArgument.
func RequireHeader ¶
func RequireHeader(name, code, message string) Constraint
RequireHeader refuses a request that does not carry a header, for asserting that a client always sends one.
func RequireRuleSequence ¶ added in v0.11.0
func RequireRuleSequence() Constraint
RequireRuleSequence refuses a new inbox rule that does not say where it runs in the order.
The service requires a positive sequence and will not choose one. It answers a rule without it with a MessageRuleValidationError naming the field and not the remedy, so every rule created with a default-constructed body failed -- which is every rule, until something tried it against a real mailbox.
func RequireScopes ¶ added in v0.8.0
func RequireScopes(granted ...string) Constraint
RequireScopes refuses a request whose resource needs a permission the token was not granted, the way the service does.
This exists because of a bug that reached a real mailbox. A token is issued for the scopes a client *requests*, not for everything the user has consented to. Every command asked for the default mail scopes, so the mailbox settings commands were refused even though consent covered them -- and the error told the user to grant a permission they already held. A fake that answered every path identically could not have caught it: the whole bug lived in the difference between paths.
The refusal is deliberately as unhelpful as the real one. Graph answers a missing delegated permission with ErrorAccessDenied and names neither the permission nor the resource, so a caller that only works when the error is descriptive will not work in production either.
func RequireSearchEntityTypes ¶ added in v0.13.0
func RequireSearchEntityTypes(required ...string) Constraint
RequireSearchEntityTypes refuses a search body that does not name one of the entity types, so a mis-built request fails here instead of succeeding with an empty-looking result that reads as "nothing matched".
func RequireSortableFilter ¶
func RequireSortableFilter(sortable ...string) Constraint
RequireSortableFilter refuses a request that both sorts and filters on a property outside the sortable set, the way Exchange answers InefficientFilter.
This is the constraint that broke most of the CLI's filters in production while every test passed: the default newest-first ordering meant almost any filter was paired with a sort.
func Teams ¶ added in v0.13.0
func Teams() []Constraint
Teams returns the constraints a real Teams tenant applies.
It is worth reading alongside ExchangeMail, because the two fail in opposite ways. Exchange refuses what it cannot serve, so the Exchange bundle is constraints: a bad request comes back as an error a test can see. Teams mostly answers anyway. An unservable filter is dropped, an oversized page is quietly trimmed, an enum the request did not opt into is replaced with a placeholder -- all with 200 OK and a body that parses.
That is why the Teams half of this fake lives mostly in TeamsShapers, and why using these constraints without those shapers reproduces the easy failures and none of the dangerous ones.
type Option ¶
type Option func(*Server)
Option configures a Server.
func WithConstraints ¶
func WithConstraints(constraints ...Constraint) Option
WithConstraints makes the fake reject requests the real service would.
func WithShapers ¶ added in v0.12.0
WithShapers rewrites responses on their way out. Use it to reproduce how the service presents an answer, as distinct from whether it refuses one.
type Query ¶
type Query struct {
Select []string
Filter string
OrderBy []string
Search string
Top int
Skip int
Count bool
SkipToken string
DeltaToken string
Raw url.Values
}
Query is the parsed OData query string.
type Request ¶
type Request struct {
Method string
// Path is the escaped request path.
Path string
Query Query
Header http.Header
Body []byte
// contains filtered or unexported fields
}
Request is what a handler is given.
func (*Request) EffectivePageSize ¶
EffectivePageSize is the number of items a request should yield, applying the service's default and cap. Handlers use it to page realistically.
func (*Request) PageSize ¶
PageSize returns the odata.maxpagesize the caller asked for, and whether one was sent at all.
type Response ¶
Response is what a handler returns.
func Collection ¶
Collection responds with a Graph collection page. A non-empty nextLink is echoed as @odata.nextLink; use Delta for a terminal delta page.
func Delta ¶
Delta responds with a delta page carrying a deltaLink, marking the end of a change set.
func Empty ¶
Empty responds with a status and no body, for the 202 and 204 replies Graph gives to sends, moves, and deletes.
func OutlookChunkAccepted ¶ added in v0.12.0
OutlookChunkAccepted is what an Outlook upload session answers for a chunk that is not the last one.
It is 200 with the ranges it still wants, not the 202 an upload session suggests. Reading the status as completion truncates the attachment at the first chunk, and a fake that answered 202 encoded that mistake so well the suite stayed green while real uploads lost data. The body decides, not the status.
func OutlookChunkComplete ¶ added in v0.12.0
OutlookChunkComplete is what the session answers for the final chunk: 201 with the attachment it created.
func Raw ¶ added in v0.6.3
Raw responds with an arbitrary body and content type, for the endpoints that do not speak JSON — a message's MIME representation, or an attachment's bytes.
func (Response) WithHeader ¶
WithHeader adds a response header.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is a fake Graph endpoint.
func (*Server) Handle ¶
Handle registers a handler for a method-and-path pattern using the standard library's routing syntax, so "GET /me/messages/{id}" captures an id.
func (*Server) Link ¶
Link builds an absolute link back into this server, for a nextLink or a deltaLink. The Graph client refuses to follow a link to another host, so a test must not invent one.
type Shaper ¶ added in v0.12.0
A Shaper rewrites a response on its way out, so the fake can reproduce how the service presents an answer rather than only whether it gives one.
Constraints cover refusals. This covers the other half: a service that answers successfully but in a shape a client does not expect. Graph naming zones with Windows identifiers is the example -- nothing is refused, and a client that assumes IANA names silently computes the wrong instant.
func DropSenderOnSystemEvents ¶ added in v0.13.0
func DropSenderOnSystemEvents() Shaper
DropSenderOnSystemEvents removes from wherever eventDetail is present.
Nothing sent a system event message: the service generated it, and from is null. A fake that helpfully supplies a sender lets a client dereference it unconditionally and pass, then panic or render a blank name against a real chat on the first membership change.
func DropTopicOnOneOnOneChats ¶ added in v0.13.0
func DropTopicOnOneOnOneChats() Shaper
DropTopicOnOneOnOneChats removes topic from every one-on-one chat.
The service sends null, because a one-on-one chat has no name of its own -- its name is the other participant, which the caller has to assemble from the members. A fake that supplies a topic renders a tidy chat list in tests and a column of blank rows in production, where most chats are one-on-one.
func HideEnumsWithoutPrefer ¶ added in v0.13.0
func HideEnumsWithoutPrefer() Shaper
HideEnumsWithoutPrefer replaces every messageType outside the base set with unknownFutureValue unless the request asked to see evolvable enum members.
This is the most valuable shaper in the bundle. messageType is an evolvable enum, so a request that does not send Prefer: include-unknown-enum-members gets systemEventMessage reported as unknownFutureValue -- with no error, and with eventDetail still populated. In a real chat, member joins, renames and call notices are a large minority of the history, so a client switching on the type renders a substantial part of every conversation as nothing at all.
It is also the only check that proves the header survives the network. A client can set the directive perfectly and have a proxy strip it; nothing else in a test suite would notice.
func NameZonesTheWindowsWay ¶ added in v0.12.0
NameZonesTheWindowsWay rewrites every timeZone in a response to a Windows identifier, the way Graph does once a request asks for a zone.
This is a shaper rather than a constraint because nothing is refused. The response is perfectly valid and the client still gets it wrong, which is the harder failure to find: a calendar that renders confidently and is hours or a day out. Rendering an all-day event this way showed every holiday on the wrong date.
func PageExpandedReplies ¶ added in v0.13.0
PageExpandedReplies cuts an expanded replies array to the cap and injects the per-message continuation link the service sends.
This is a second pagination nested inside the first. The collection's own @odata.nextLink pages root messages and says nothing about replies, so a client that follows only the outer link -- which is every client written against every other Graph collection -- truncates each long thread and displays a conversation that stops mid-argument, with no error and no gap.
func PopulateOnlyJoinedTeamsFields ¶ added in v0.13.0
func PopulateOnlyJoinedTeamsFields() Shaper
PopulateOnlyJoinedTeamsFields nulls the team properties that listing joined teams does not fill in.
The response carries the whole team shape, so it looks complete. It is not: webUrl, visibility, internalId and the settings all come back null, and only a Get on the individual team populates them. A client reading visibility off a listing sees an empty string and concludes the team is public, which is a different claim from "not loaded".
func RootChannelMessagesOnly ¶ added in v0.13.0
func RootChannelMessagesOnly() Shaper
RootChannelMessagesOnly drops replies from a channel message collection.
A channel listing returns root messages and nothing else, however deep the paging goes. A transcript built from it alone shows every conversation opener and none of the conversation, so a fake that mixes replies into the collection hides the need to expand them or fetch them per message.
func StripHeader ¶ added in v0.12.0
StripHeader removes a response header the real service does not send.
Mail is the case worth reproducing: there is no ETag header on a message, the version is the @odata.etag body property, and a client reading the header finds nothing and silently turns every conditional write into an unconditional one.
func TeamsShapers ¶ added in v0.13.0
func TeamsShapers() []Shaper
TeamsShapers returns the shapers that present a Teams answer the way the service presents it.
These matter more than the constraints. Everything here answers 200 with a body that parses, and every one of them has a client-side failure that no amount of error handling catches: a third of a chat rendered as blank lines, a member list that stops at twenty-five without saying so, a thread that ends mid-argument. A fake that returns the convenient shape agrees with the client and proves nothing.
func TruncateExpandedMembers ¶ added in v0.13.0
TruncateExpandedMembers cuts an expanded members array to the cap and emits no continuation link.
The absent link is the point. Everywhere else in Graph a truncated collection carries a nextLink, so a client that follows links everywhere is correct everywhere -- except here, where it silently reports a two hundred person chat as having twenty-five members and no indication otherwise.