Compare commits
29 Commits
Author | SHA1 | Date |
---|---|---|
Adphi | 76b69b7acd | |
Adphi | 90081d6e8f | |
Adphi | 5d284c1ad8 | |
Adphi | 5a9b0d715c | |
Adphi | 85ab4b93f0 | |
Adphi | 3cf8fdec75 | |
adphi | 7022842ce1 | |
adphi | f3a7e601b4 | |
Adphi | 535664608a | |
Adphi | ba43e1dcbb | |
Adphi | 04fe0dc872 | |
Adphi | 061dc12713 | |
adphi | a9c13d5422 | |
Adphi | 6deeb69b90 | |
adphi | 018fc569d3 | |
adphi | bb0b884521 | |
Adphi | 0551ffbca1 | |
Adphi | a54ee4c2e6 | |
Adphi | 2d66aa5161 | |
Adphi | 3e33481fb4 | |
Adphi | 4925b52a0e | |
Adphi | 014ac7ff7e | |
Adphi | 2953afd160 | |
Adphi | dd062fe989 | |
Adphi | 4f50c4817a | |
Adphi | 014a0c6653 | |
Adphi | 557d7213c3 | |
Adphi | c793018d74 | |
Adphi | 91d59033fb |
|
@ -1,17 +1,12 @@
|
|||
image: golang:1.9
|
||||
image: golang:1.12
|
||||
|
||||
stages:
|
||||
- test
|
||||
|
||||
before_script:
|
||||
- go get -u golang.org/x/lint/golint
|
||||
- go get -u github.com/kardianos/govendor
|
||||
- mkdir -p /go/src/gitlab.bertha.cloud/partitio/Nextcloud-Partitio
|
||||
- cp -r $CI_PROJECT_DIR /go/src/gitlab.bertha.cloud/partitio/Nextcloud-Partitio
|
||||
- cd /go/src/gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud
|
||||
#- sed -i -e 's/$NEXTCLOUD_URL/'${NEXTCLOUD_URL//\//\\/}'/g' config.yml
|
||||
#- sed -i -e 's/$NEXTCLOUD_PASSWORD/'${NEXTCLOUD_PASSWORD}'/g' config.yml
|
||||
#- sed -i -e 's/$NEXTCLOUD_EMAIL/'${NEXTCLOUD_EMAIL}'/g' config.yml
|
||||
- make dep
|
||||
|
||||
unit_tests:
|
||||
|
@ -40,4 +35,5 @@ lint_code:
|
|||
tags:
|
||||
- docker
|
||||
script:
|
||||
- make lint
|
||||
- go get -u golang.org/x/lint/golint
|
||||
- make lint
|
||||
|
|
11
Makefile
11
Makefile
|
@ -11,22 +11,21 @@ lint: ## Lint the files
|
|||
@golint -set_exit_status ${PKG_LIST}
|
||||
|
||||
test: ## Run unittests
|
||||
@go test -v .
|
||||
@GO111MODULE=on go test -mod=vendor -v .
|
||||
|
||||
race: dep ## Run data race detector
|
||||
@go test -v -race ${PKG_LIST}
|
||||
@GO111MODULE=on go test -mod=vendor -v -race ${PKG_LIST}
|
||||
|
||||
msan: dep ## Run memory sanitizer
|
||||
@go test -msan -short ${PKG_LIST}
|
||||
@GO111MODULE=on go test -mod=vendor -msan -short ${PKG_LIST}
|
||||
|
||||
coverage: ## Generate global code coverage report
|
||||
@mkdir -p cover
|
||||
@touch cover/${PROJECT_NAME}cov
|
||||
go tool cover -html=cover/${PROJECT_NAME}cov -o coverage.html
|
||||
@go tool cover -html=cover/${PROJECT_NAME}cov -o coverage.html
|
||||
|
||||
dep: ## Get the dependencies
|
||||
@mkdir -p vendor
|
||||
@govendor add +external
|
||||
@GO111MODULE=on go mod vendor
|
||||
|
||||
push: dep lint test coverage ## Push to git repository
|
||||
@git push origin master
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package types
|
||||
package gonextcloud
|
||||
|
||||
//App
|
||||
// App is a nextcloud application (plugin)
|
||||
type App struct {
|
||||
ID string `json:"id"`
|
||||
Ocsid string `json:"ocsid"`
|
|
@ -1,29 +1,29 @@
|
|||
package gonextcloud
|
||||
|
||||
import (
|
||||
req "github.com/levigross/grequests"
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
|
||||
"net/http"
|
||||
|
||||
req "github.com/levigross/grequests"
|
||||
)
|
||||
|
||||
//Apps contains all Apps available actions
|
||||
type Apps struct {
|
||||
c *Client
|
||||
//apps contains all apps available actions
|
||||
type apps struct {
|
||||
c *client
|
||||
}
|
||||
|
||||
//List return the list of the Nextcloud Apps
|
||||
func (a *Apps) List() ([]string, error) {
|
||||
//List return the list of the Nextcloud apps
|
||||
func (a *apps) List() ([]string, error) {
|
||||
res, err := a.c.baseRequest(http.MethodGet, routes.apps, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.AppListResponse
|
||||
var r appListResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data.Apps, nil
|
||||
}
|
||||
|
||||
//ListEnabled lists the enabled apps
|
||||
func (a *Apps) ListEnabled() ([]string, error) {
|
||||
func (a *apps) ListEnabled() ([]string, error) {
|
||||
ro := &req.RequestOptions{
|
||||
Params: map[string]string{"filter": "enabled"},
|
||||
}
|
||||
|
@ -31,13 +31,13 @@ func (a *Apps) ListEnabled() ([]string, error) {
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.AppListResponse
|
||||
var r appListResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data.Apps, nil
|
||||
}
|
||||
|
||||
//ListDisabled lists the disabled apps
|
||||
func (a *Apps) ListDisabled() ([]string, error) {
|
||||
func (a *apps) ListDisabled() ([]string, error) {
|
||||
ro := &req.RequestOptions{
|
||||
Params: map[string]string{"filter": "disabled"},
|
||||
}
|
||||
|
@ -45,30 +45,30 @@ func (a *Apps) ListDisabled() ([]string, error) {
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.AppListResponse
|
||||
var r appListResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data.Apps, nil
|
||||
}
|
||||
|
||||
//Infos return the app's details
|
||||
func (a *Apps) Infos(name string) (types.App, error) {
|
||||
func (a *apps) Infos(name string) (App, error) {
|
||||
res, err := a.c.baseRequest(http.MethodGet, routes.apps, nil, name)
|
||||
if err != nil {
|
||||
return types.App{}, err
|
||||
return App{}, err
|
||||
}
|
||||
var r types.AppResponse
|
||||
var r appResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data, nil
|
||||
}
|
||||
|
||||
//Enable enables an app
|
||||
func (a *Apps) Enable(name string) error {
|
||||
func (a *apps) Enable(name string) error {
|
||||
_, err := a.c.baseRequest(http.MethodPost, routes.apps, nil, name)
|
||||
return err
|
||||
}
|
||||
|
||||
//Disable disables an app
|
||||
func (a *Apps) Disable(name string) error {
|
||||
func (a *apps) Disable(name string) error {
|
||||
_, err := a.c.baseRequest(http.MethodDelete, routes.apps, nil, name)
|
||||
return err
|
||||
}
|
|
@ -1,52 +1,52 @@
|
|||
package gonextcloud
|
||||
|
||||
import (
|
||||
req "github.com/levigross/grequests"
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
req "github.com/levigross/grequests"
|
||||
)
|
||||
|
||||
//AppsConfig contains all Apps Configuration available actions
|
||||
type AppsConfig struct {
|
||||
c *Client
|
||||
//appsConfig contains all apps Configuration available actions
|
||||
type appsConfig struct {
|
||||
c *client
|
||||
}
|
||||
|
||||
//List lists all the available apps
|
||||
func (a *AppsConfig) List() (apps []string, err error) {
|
||||
func (a *appsConfig) List() (apps []string, err error) {
|
||||
res, err := a.c.baseRequest(http.MethodGet, routes.appsConfig, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.AppConfigResponse
|
||||
var r appConfigResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data.Data, nil
|
||||
}
|
||||
|
||||
//Keys returns the app's config keys
|
||||
func (a *AppsConfig) Keys(id string) (keys []string, err error) {
|
||||
func (a *appsConfig) Keys(id string) (keys []string, err error) {
|
||||
res, err := a.c.baseRequest(http.MethodGet, routes.appsConfig, nil, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.AppConfigResponse
|
||||
var r appConfigResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data.Data, nil
|
||||
}
|
||||
|
||||
//Value get the config value for the given app's key
|
||||
func (a *AppsConfig) Value(id, key string) (string, error) {
|
||||
func (a *appsConfig) Value(id, key string) (string, error) {
|
||||
res, err := a.c.baseRequest(http.MethodGet, routes.appsConfig, nil, id, key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var r types.AppcConfigValueResponse
|
||||
var r appcConfigValueResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data.Data, nil
|
||||
}
|
||||
|
||||
//SetValue set the config value for the given app's key
|
||||
func (a *AppsConfig) SetValue(id, key, value string) error {
|
||||
func (a *appsConfig) SetValue(id, key, value string) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"value": value,
|
||||
|
@ -57,13 +57,13 @@ func (a *AppsConfig) SetValue(id, key, value string) error {
|
|||
}
|
||||
|
||||
//DeleteValue delete the config value and (!! be careful !!) the key
|
||||
func (a *AppsConfig) DeleteValue(id, key, value string) error {
|
||||
func (a *appsConfig) DeleteValue(id, key, value string) error {
|
||||
_, err := a.c.baseRequest(http.MethodDelete, routes.appsConfig, nil, id, key)
|
||||
return err
|
||||
}
|
||||
|
||||
//Get returns all apps AppConfigDetails
|
||||
func (a *AppsConfig) Get() (map[string]map[string]string, error) {
|
||||
func (a *appsConfig) Get() (map[string]map[string]string, error) {
|
||||
config := map[string]map[string]string{}
|
||||
m := sync.Mutex{}
|
||||
appsIDs, err := a.List()
|
||||
|
@ -88,7 +88,7 @@ func (a *AppsConfig) Get() (map[string]map[string]string, error) {
|
|||
}
|
||||
|
||||
//Details returns all the config's key, values pair of the app
|
||||
func (a *AppsConfig) Details(appID string) (map[string]string, error) {
|
||||
func (a *appsConfig) Details(appID string) (map[string]string, error) {
|
||||
config := map[string]string{}
|
||||
m := sync.Mutex{}
|
||||
var err error
|
|
@ -2,14 +2,14 @@ package gonextcloud
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
req "github.com/levigross/grequests"
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
|
||||
)
|
||||
|
||||
var errUnauthorized = fmt.Errorf("login first")
|
||||
|
||||
// Login perform login and create a session with the Nextcloud API.
|
||||
func (c *Client) Login(username string, password string) error {
|
||||
func (c *client) Login(username string, password string) error {
|
||||
c.username = username
|
||||
c.password = password
|
||||
options := req.RequestOptions{
|
||||
|
@ -23,21 +23,23 @@ func (c *Client) Login(username string, password string) error {
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var r types.CapabilitiesResponse
|
||||
var r capabilitiesResponse
|
||||
res.JSON(&r)
|
||||
// No need to check for Ocs.Meta.StatusCode as capabilities are always returned
|
||||
// No need to check for Ocs.meta.StatusCode as capabilities are always returned
|
||||
c.capabilities = &r.Ocs.Data.Capabilities
|
||||
c.version = &r.Ocs.Data.Version
|
||||
// Check if authentication failed
|
||||
if !c.loggedIn() {
|
||||
e := types.APIError{Message: "authentication failed"}
|
||||
e := APIError{Message: "authentication failed"}
|
||||
return &e
|
||||
}
|
||||
// Create webdav client
|
||||
c.webdav = newWebDav(c.baseURL.String()+"/remote.php/webdav", c.username, c.password)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Logout logs out from the Nextcloud API, close the session and delete session's cookie
|
||||
func (c *Client) Logout() error {
|
||||
func (c *client) Logout() error {
|
||||
c.session.CloseIdleConnections()
|
||||
c.session.HTTPClient.Jar = nil
|
||||
// Clear capabilities as it is used to check for valid authentication
|
||||
|
@ -45,7 +47,7 @@ func (c *Client) Logout() error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) loggedIn() bool {
|
||||
func (c *client) loggedIn() bool {
|
||||
// When authentication failed, capabilities doesn't contains core information
|
||||
if c.capabilities == nil {
|
||||
return false
|
|
@ -1,6 +1,6 @@
|
|||
package types
|
||||
package gonextcloud
|
||||
|
||||
//Capabilities
|
||||
// Capabilities is the capabilities provided by the Nextcloud server
|
||||
type Capabilities struct {
|
||||
Core struct {
|
||||
Pollinterval int `json:"pollinterval"`
|
88
client.go
88
client.go
|
@ -1,88 +0,0 @@
|
|||
package gonextcloud
|
||||
|
||||
import (
|
||||
req "github.com/levigross/grequests"
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// Client is the API client that performs all operations against a Nextcloud server.
|
||||
type Client struct {
|
||||
baseURL *url.URL
|
||||
username string
|
||||
password string
|
||||
session *req.Session
|
||||
headers map[string]string
|
||||
capabilities *types.Capabilities
|
||||
version *types.Version
|
||||
|
||||
apps *Apps
|
||||
appsConfig *AppsConfig
|
||||
groupFolders *GroupFolders
|
||||
notifications *Notifications
|
||||
shares *Shares
|
||||
users *Users
|
||||
groups *Groups
|
||||
}
|
||||
|
||||
// NewClient create a new Client from the Nextcloud Instance URL
|
||||
func NewClient(hostname string) (*Client, error) {
|
||||
baseURL, err := url.ParseRequestURI(hostname)
|
||||
if err != nil {
|
||||
baseURL, err = url.ParseRequestURI("https://" + hostname)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
c := &Client{
|
||||
baseURL: baseURL,
|
||||
headers: map[string]string{
|
||||
"OCS-APIREQUEST": "true",
|
||||
"Accept": "application/json",
|
||||
},
|
||||
}
|
||||
c.apps = &Apps{c}
|
||||
c.appsConfig = &AppsConfig{c}
|
||||
c.groupFolders = &GroupFolders{c}
|
||||
c.notifications = &Notifications{c}
|
||||
c.shares = &Shares{c}
|
||||
c.users = &Users{c}
|
||||
c.groups = &Groups{c}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
//Apps return the Apps client Interface
|
||||
func (c *Client) Apps() types.Apps {
|
||||
return c.apps
|
||||
}
|
||||
|
||||
//AppsConfig return the AppsConfig client Interface
|
||||
func (c *Client) AppsConfig() types.AppsConfig {
|
||||
return c.appsConfig
|
||||
}
|
||||
|
||||
//GroupFolders return the GroupFolders client Interface
|
||||
func (c *Client) GroupFolders() types.GroupFolders {
|
||||
return c.groupFolders
|
||||
}
|
||||
|
||||
//Notifications return the Notifications client Interface
|
||||
func (c *Client) Notifications() types.Notifications {
|
||||
return c.notifications
|
||||
}
|
||||
|
||||
//Shares return the Shares client Interface
|
||||
func (c *Client) Shares() types.Shares {
|
||||
return c.shares
|
||||
}
|
||||
|
||||
//Users return the Users client Interface
|
||||
func (c *Client) Users() types.Users {
|
||||
return c.users
|
||||
}
|
||||
|
||||
//Groups return the Groups client Interface
|
||||
func (c *Client) Groups() types.Groups {
|
||||
return c.groups
|
||||
}
|
|
@ -0,0 +1,99 @@
|
|||
package gonextcloud
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
|
||||
req "github.com/levigross/grequests"
|
||||
"gitlab.bertha.cloud/adphi/gowebdav"
|
||||
)
|
||||
|
||||
// client is the API client that performs all operations against a Nextcloud server.
|
||||
type client struct {
|
||||
baseURL *url.URL
|
||||
username string
|
||||
password string
|
||||
session *req.Session
|
||||
headers map[string]string
|
||||
capabilities *Capabilities
|
||||
version *Version
|
||||
|
||||
apps *apps
|
||||
appsConfig *appsConfig
|
||||
groupFolders *groupFolders
|
||||
notifications *notifications
|
||||
shares *shares
|
||||
users *users
|
||||
groups *groups
|
||||
webdav *webDav
|
||||
}
|
||||
|
||||
// newClient create a new client from the Nextcloud Instance URL
|
||||
func newClient(hostname string) (*client, error) {
|
||||
baseURL, err := url.ParseRequestURI(hostname)
|
||||
if err != nil {
|
||||
baseURL, err = url.ParseRequestURI("https://" + hostname)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
c := &client{
|
||||
baseURL: baseURL,
|
||||
headers: map[string]string{
|
||||
"OCS-APIREQUEST": "true",
|
||||
"Accept": "application/json",
|
||||
},
|
||||
}
|
||||
|
||||
c.apps = &apps{c}
|
||||
c.appsConfig = &appsConfig{c}
|
||||
c.groupFolders = &groupFolders{c}
|
||||
c.notifications = ¬ifications{c}
|
||||
c.shares = &shares{c}
|
||||
c.users = &users{c}
|
||||
c.groups = &groups{c}
|
||||
// Create empty webdav client
|
||||
// It will be replaced after login
|
||||
c.webdav = &webDav{Client: &gowebdav.Client{}}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// apps return the apps client Interface
|
||||
func (c *client) Apps() Apps {
|
||||
return c.apps
|
||||
}
|
||||
|
||||
// appsConfig return the appsConfig client Interface
|
||||
func (c *client) AppsConfig() AppsConfig {
|
||||
return c.appsConfig
|
||||
}
|
||||
|
||||
// groupFolders return the groupFolders client Interface
|
||||
func (c *client) GroupFolders() GroupFolders {
|
||||
return c.groupFolders
|
||||
}
|
||||
|
||||
// notifications return the notifications client Interface
|
||||
func (c *client) Notifications() Notifications {
|
||||
return c.notifications
|
||||
}
|
||||
|
||||
// shares return the shares client Interface
|
||||
func (c *client) Shares() Shares {
|
||||
return c.shares
|
||||
}
|
||||
|
||||
// users return the users client Interface
|
||||
func (c *client) Users() Users {
|
||||
return c.users
|
||||
}
|
||||
|
||||
// groups return the groups client Interface
|
||||
func (c *client) Groups() Groups {
|
||||
return c.groups
|
||||
}
|
||||
|
||||
// WebDav return the WebDav client Interface
|
||||
func (c *client) WebDav() WebDav {
|
||||
return c.webdav
|
||||
}
|
|
@ -5,4 +5,5 @@ app-name: testapp
|
|||
share-folder: /Documents
|
||||
not-existing-user: this-user-should-not-exist
|
||||
not-existing-group: this-group-should-not-exist
|
||||
email: $NEXTCLOUD_EMAIL
|
||||
not-existing-folder: this-folder-should-not-exist
|
||||
email: $NEXTCLOUD_EMAIL
|
||||
|
|
4
doc.go
4
doc.go
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
Package gonextcloud is a Go client for the Nextcloud Provisioning API.
|
||||
Package gonextcloud is a simple Go Client for Nextcloud's API.
|
||||
|
||||
For more information about the Provisioning API, see the documentation:
|
||||
https://docs.nextcloud.com/server/13/admin_manual/configuration_user/user_provisioning_api.html
|
||||
|
@ -34,7 +34,7 @@ For example, to list all the Nextcloud's instance users:
|
|||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Println("Users :", users)
|
||||
fmt.Println("users :", users)
|
||||
}
|
||||
*/
|
||||
package gonextcloud
|
||||
|
|
1566
docs/README.md
1566
docs/README.md
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,58 @@
|
|||
package gonextcloud
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// APIError contains the returned error code and message from the Nextcloud's API
|
||||
type APIError struct {
|
||||
Code int
|
||||
Message string
|
||||
}
|
||||
|
||||
//errorFromMeta return a types.APIError from the Response's types.meta
|
||||
func errorFromMeta(meta meta) *APIError {
|
||||
return &APIError{
|
||||
meta.Statuscode,
|
||||
meta.Message,
|
||||
}
|
||||
}
|
||||
|
||||
// Error return the types.APIError string
|
||||
func (e *APIError) Error() string {
|
||||
return fmt.Sprintf("%d : %s", e.Code, e.Message)
|
||||
}
|
||||
|
||||
// UpdateError contains the user's field and corresponding error
|
||||
type UpdateError struct {
|
||||
Field string
|
||||
Error error
|
||||
}
|
||||
|
||||
// UserUpdateError contains the errors resulting from a UserUpdate or a UserCreateFull call
|
||||
type UserUpdateError struct {
|
||||
Errors map[string]error
|
||||
}
|
||||
|
||||
func (e *UserUpdateError) Error() string {
|
||||
var errors []string
|
||||
for k, e := range e.Errors {
|
||||
errors = append(errors, fmt.Sprintf("%s: %v", k, e))
|
||||
}
|
||||
return strings.Join(errors, ", ")
|
||||
}
|
||||
|
||||
//newUpdateError returns an UpdateError based on an UpdateError channel
|
||||
func newUpdateError(errors chan *UpdateError) *UserUpdateError {
|
||||
ue := UserUpdateError{map[string]error{}}
|
||||
for e := range errors {
|
||||
if e != nil {
|
||||
ue.Errors[e.Field] = e.Error
|
||||
}
|
||||
}
|
||||
if len(ue.Errors) > 0 {
|
||||
return &ue
|
||||
}
|
||||
return nil
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
package gonextcloud
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestUserUpdateErrors(t *testing.T) {
|
||||
exp := map[string]error{}
|
||||
errs := make(chan *UpdateError)
|
||||
go func() {
|
||||
for i := 0; i < 10; i++ {
|
||||
f := strconv.Itoa(i)
|
||||
e := errors.New(f)
|
||||
err := UpdateError{
|
||||
Field: f,
|
||||
Error: e,
|
||||
}
|
||||
exp[f] = e
|
||||
errs <- &err
|
||||
}
|
||||
close(errs)
|
||||
}()
|
||||
uerrs := newUpdateError(errs)
|
||||
assert.Equal(t, exp, uerrs.Errors)
|
||||
assert.NotEmpty(t, uerrs.Error())
|
||||
}
|
||||
|
||||
func TestUserUpdateErrorsNil(t *testing.T) {
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan *UpdateError)
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
errs <- nil
|
||||
wg.Done()
|
||||
}()
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
}()
|
||||
uerrs := newUpdateError(errs)
|
||||
assert.Nil(t, uerrs)
|
||||
}
|
|
@ -5,4 +5,5 @@ app-name: testapp
|
|||
share-folder: /Documents
|
||||
not-existing-user: this-user-should-not-exist
|
||||
not-existing-group: this-group-should-not-exist
|
||||
email: my@mail.com
|
||||
not-existing-folder: this-folder-should-not-exist
|
||||
email: my@mail.com
|
||||
|
|
|
@ -0,0 +1,18 @@
|
|||
module gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud
|
||||
|
||||
go 1.12
|
||||
|
||||
require (
|
||||
github.com/fatih/structs v0.0.0-20180123065059-ebf56d35bba7
|
||||
github.com/google/go-querystring v0.0.0-20170111101155-53e6ce116135 // indirect
|
||||
github.com/kr/pretty v0.1.0 // indirect
|
||||
github.com/levigross/grequests v0.0.0-20171009010347-bf9788368aa0
|
||||
github.com/pkg/errors v0.0.0-20181023235946-059132a15dd0
|
||||
github.com/sirupsen/logrus v1.4.2
|
||||
github.com/stretchr/testify v1.2.2
|
||||
gitlab.bertha.cloud/adphi/gowebdav v0.0.0-20190720232020-771eec6e76d0
|
||||
golang.org/x/net v0.0.0-20190628185345-da137c7871d7 // indirect
|
||||
golang.org/x/sys v0.0.0-20190712062909-fae7ac547cb7 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
|
||||
gopkg.in/yaml.v2 v2.2.1
|
||||
)
|
|
@ -0,0 +1,42 @@
|
|||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/fatih/structs v0.0.0-20180123065059-ebf56d35bba7 h1:bGT+Ub6bpzHl7AAYQhBrZ5nYTAH2SF/848WducU0Ao4=
|
||||
github.com/fatih/structs v0.0.0-20180123065059-ebf56d35bba7/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
|
||||
github.com/google/go-querystring v0.0.0-20170111101155-53e6ce116135 h1:zLTLjkaOFEFIOxY5BWLFLwh+cL8vOBW4XJ2aqLE/Tf0=
|
||||
github.com/google/go-querystring v0.0.0-20170111101155-53e6ce116135/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/levigross/grequests v0.0.0-20171009010347-bf9788368aa0 h1:QpdhtrR7SX3R7OlEv9dZarsXogM3PM/tl1ibRH/eHbQ=
|
||||
github.com/levigross/grequests v0.0.0-20171009010347-bf9788368aa0/go.mod h1:uCZIhROSrVmuF/BPYFPwDeiiQ6juSLp0kikFoEcNcEs=
|
||||
github.com/pkg/errors v0.0.0-20181023235946-059132a15dd0 h1:R+lX9nKwNd1n7UE5SQAyoorREvRn3aLF6ZndXBoIWqY=
|
||||
github.com/pkg/errors v0.0.0-20181023235946-059132a15dd0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
|
||||
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
|
||||
github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A=
|
||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
gitlab.bertha.cloud/adphi/gowebdav v0.0.0-20190720232020-771eec6e76d0 h1:kjJ5Xn+FgD+QvWP670A2hmdMqxWkOuffMukEA1JSGo4=
|
||||
gitlab.bertha.cloud/adphi/gowebdav v0.0.0-20190720232020-771eec6e76d0/go.mod h1:Nr6YgM/ZBLPOlAAjcER6HSAXF64AAlal6AJ2CEKg2Fc=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/net v0.0.0-20190628185345-da137c7871d7 h1:rTIdg5QFRR7XCaK4LCjBiPbx8j4DQRpdYMnGn/bJUEU=
|
||||
golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190712062909-fae7ac547cb7 h1:LepdCS8Gf/MVejFIt8lsiexZATdoGVyp5bcyS+rYoUI=
|
||||
golang.org/x/sys v0.0.0-20190712062909-fae7ac547cb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
|
@ -1,22 +1,49 @@
|
|||
package types
|
||||
package gonextcloud
|
||||
|
||||
//Client is the main client interface
|
||||
type Client interface {
|
||||
Apps() Apps
|
||||
AppsConfig() AppsConfig
|
||||
GroupFolders() GroupFolders
|
||||
Notifications() Notifications
|
||||
Shares() Shares
|
||||
Users() Users
|
||||
Groups() Groups
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// NewClient create a new client
|
||||
func NewClient(hostname string) (Client, error) {
|
||||
return newClient(hostname)
|
||||
}
|
||||
|
||||
// Client is the main client interface
|
||||
type Client interface {
|
||||
// Nextcloud Apps client
|
||||
Apps() Apps
|
||||
// Nextcloud App Config client
|
||||
AppsConfig() AppsConfig
|
||||
// Nextcloud Group Folders client
|
||||
GroupFolders() GroupFolders
|
||||
// Nextcloud Notifications client
|
||||
Notifications() Notifications
|
||||
// Nextcloud Shares client
|
||||
Shares() Shares
|
||||
// Nextcloud Users client
|
||||
Users() Users
|
||||
// Nextcloud Groups client
|
||||
Groups() Groups
|
||||
// Nextcloud WebDav (files) client
|
||||
WebDav() WebDav
|
||||
// Nextcloud Monitoring client
|
||||
Monitoring() (*Monitoring, error)
|
||||
// Login authorize client
|
||||
Login(username string, password string) error
|
||||
// Logout clear connetion and session
|
||||
Logout() error
|
||||
}
|
||||
|
||||
// Auth is the standard auth methods
|
||||
type Auth interface {
|
||||
Login(username string, password string) error
|
||||
Logout() error
|
||||
}
|
||||
|
||||
//Apps available methods
|
||||
// Apps available methods
|
||||
type Apps interface {
|
||||
List() ([]string, error)
|
||||
ListEnabled() ([]string, error)
|
||||
|
@ -26,7 +53,7 @@ type Apps interface {
|
|||
Disable(name string) error
|
||||
}
|
||||
|
||||
//AppsConfig available methods
|
||||
// AppsConfig available methods
|
||||
type AppsConfig interface {
|
||||
List() (apps []string, err error)
|
||||
Keys(id string) (keys []string, err error)
|
||||
|
@ -37,10 +64,10 @@ type AppsConfig interface {
|
|||
Details(appID string) (map[string]string, error)
|
||||
}
|
||||
|
||||
//Groups available methods
|
||||
// Groups available methods
|
||||
type Groups interface {
|
||||
List() ([]string, error)
|
||||
ListDetails() ([]Group, error)
|
||||
ListDetails(search string) ([]Group, error)
|
||||
Users(name string) ([]string, error)
|
||||
Search(search string) ([]string, error)
|
||||
Create(name string) error
|
||||
|
@ -48,7 +75,7 @@ type Groups interface {
|
|||
SubAdminList(name string) ([]string, error)
|
||||
}
|
||||
|
||||
//GroupFolders available methods
|
||||
// GroupFolders available methods
|
||||
type GroupFolders interface {
|
||||
List() (map[int]GroupFolder, error)
|
||||
Get(id int) (GroupFolder, error)
|
||||
|
@ -60,7 +87,7 @@ type GroupFolders interface {
|
|||
SetQuota(folderID int, quota int) error
|
||||
}
|
||||
|
||||
//Notifications available methods
|
||||
// Notifications available methods
|
||||
type Notifications interface {
|
||||
List() ([]Notification, error)
|
||||
Get(id int) (Notification, error)
|
||||
|
@ -71,7 +98,7 @@ type Notifications interface {
|
|||
Available() error
|
||||
}
|
||||
|
||||
//Shares available methods
|
||||
// Shares available methods
|
||||
type Shares interface {
|
||||
List() ([]Share, error)
|
||||
GetFromPath(path string, reshares bool, subfiles bool) ([]Share, error)
|
||||
|
@ -92,7 +119,7 @@ type Shares interface {
|
|||
UpdatePermissions(shareID int, permissions SharePermission) error
|
||||
}
|
||||
|
||||
//Users available methods
|
||||
// Users available methods
|
||||
type Users interface {
|
||||
List() ([]string, error)
|
||||
ListDetails() (map[string]UserDetails, error)
|
||||
|
@ -113,7 +140,7 @@ type Users interface {
|
|||
UpdateWebSite(name string, website string) error
|
||||
UpdateTwitter(name string, twitter string) error
|
||||
UpdatePassword(name string, password string) error
|
||||
UpdateQuota(name string, quota int) error
|
||||
UpdateQuota(name string, quota int64) error
|
||||
GroupList(name string) ([]string, error)
|
||||
GroupAdd(name string, group string) error
|
||||
GroupRemove(name string, group string) error
|
||||
|
@ -121,3 +148,35 @@ type Users interface {
|
|||
GroupDemote(name string, group string) error
|
||||
GroupSubAdminList(name string) ([]string, error)
|
||||
}
|
||||
|
||||
// WebDav available methods
|
||||
type WebDav interface {
|
||||
// ReadDir reads the contents of a remote directory
|
||||
ReadDir(path string) ([]os.FileInfo, error)
|
||||
// Stat returns the file stats for a specified path
|
||||
Stat(path string) (os.FileInfo, error)
|
||||
// Remove removes a remote file
|
||||
Remove(path string) error
|
||||
// RemoveAll removes remote files
|
||||
RemoveAll(path string) error
|
||||
// Mkdir makes a directory
|
||||
Mkdir(path string, _ os.FileMode) error
|
||||
// MkdirAll like mkdir -p, but for webdav
|
||||
MkdirAll(path string, _ os.FileMode) error
|
||||
// Rename moves a file from A to B
|
||||
Rename(oldpath, newpath string, overwrite bool) error
|
||||
// Copy copies a file from A to B
|
||||
Copy(oldpath, newpath string, overwrite bool) error
|
||||
// Read reads the contents of a remote file
|
||||
Read(path string) ([]byte, error)
|
||||
// ReadStream reads the stream for a given path
|
||||
ReadStream(path string) (io.ReadCloser, error)
|
||||
// Write writes data to a given path
|
||||
Write(path string, data []byte, _ os.FileMode) error
|
||||
// WriteStream writes a stream
|
||||
WriteStream(path string, stream io.Reader, _ os.FileMode) error
|
||||
|
||||
// Walk walks the file tree rooted at root, calling walkFn for each file or
|
||||
// directory in the tree, including root.
|
||||
Walk(path string, walkFunc filepath.WalkFunc) error
|
||||
}
|
|
@ -2,9 +2,6 @@ package gonextcloud
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
|
||||
"gopkg.in/yaml.v2"
|
||||
"io/ioutil"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
|
@ -15,6 +12,9 @@ import (
|
|||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
|
@ -25,6 +25,7 @@ type Config struct {
|
|||
ShareFolder string `yaml:"share-folder"`
|
||||
NotExistingUser string `yaml:"not-existing-user"`
|
||||
NotExistingGroup string `yaml:"not-existing-group"`
|
||||
NotExistingFolder string `yaml:"not-existing-folder"`
|
||||
Email string `yaml:"email"`
|
||||
}
|
||||
|
||||
|
@ -34,7 +35,7 @@ type test = func(t *testing.T)
|
|||
|
||||
var (
|
||||
config = Config{}
|
||||
c *Client
|
||||
c *client
|
||||
groupID = 37
|
||||
provisionningTests = []struct {
|
||||
string
|
||||
|
@ -51,7 +52,7 @@ var (
|
|||
"create client",
|
||||
func(t *testing.T) {
|
||||
var err error
|
||||
c, err = NewClient(config.URL)
|
||||
c, err = newClient(config.URL)
|
||||
assert.NoError(t, err, "aie")
|
||||
},
|
||||
},
|
||||
|
@ -130,7 +131,7 @@ var (
|
|||
// return
|
||||
// }
|
||||
// username := fmt.Sprintf("%s-2", config.NotExistingUser)
|
||||
// user := &types.Users{
|
||||
// user := &types.users{
|
||||
// ID: username,
|
||||
// Displayname: strings.ToUpper(username),
|
||||
// Email: "some@address.com",
|
||||
|
@ -139,9 +140,9 @@ var (
|
|||
// Phone: "42 42 242 424",
|
||||
// Website: "my.site.com",
|
||||
// }
|
||||
// err := c.Users().Create(username, password, user)
|
||||
// err := c.users().Create(username, password, user)
|
||||
// assert.NoError(t, err)
|
||||
// u, err := c.Users().Get(username)
|
||||
// u, err := c.users().Get(username)
|
||||
// assert.NoError(t, err)
|
||||
// o := structs.Map(user)
|
||||
// r := structs.Map(u)
|
||||
|
@ -152,46 +153,11 @@ var (
|
|||
// assert.Equal(t, o[k], r[k])
|
||||
// }
|
||||
// // Clean up
|
||||
// err = c.Users().Delete(u.ID)
|
||||
// err = c.users().Delete(u.ID)
|
||||
// assert.NoError(t, err)
|
||||
// },
|
||||
//},
|
||||
//
|
||||
//{
|
||||
// "TestUserUpdate",
|
||||
// func(t *testing.T) {
|
||||
// if err := initClient(); err != nil {
|
||||
// return
|
||||
// }
|
||||
// username := fmt.Sprintf("%s-2", config.NotExistingUser)
|
||||
// err := c.Users().Create(username, password, nil)
|
||||
// assert.NoError(t, err)
|
||||
// user := &types.Users{
|
||||
// ID: username,
|
||||
// Displayname: strings.ToUpper(username),
|
||||
// Email: "some@address.com",
|
||||
// Address: "Main Street, City",
|
||||
// Twitter: "@me",
|
||||
// Phone: "42 42 242 424",
|
||||
// Website: "my.site.com",
|
||||
// }
|
||||
// err = c.Users().Update(user)
|
||||
// assert.NoError(t, err)
|
||||
// u, err := c.Users().Get(username)
|
||||
// assert.NoError(t, err)
|
||||
// o := structs.Map(user)
|
||||
// r := structs.Map(u)
|
||||
// for k := range o {
|
||||
// if ignoredUserField(k) {
|
||||
// continue
|
||||
// }
|
||||
// assert.Equal(t, o[k], r[k])
|
||||
// }
|
||||
// // Clean up
|
||||
// err = c.Users().Delete(u.ID)
|
||||
// assert.NoError(t, err)
|
||||
// },
|
||||
//},
|
||||
{
|
||||
"TestUserCreateExisting",
|
||||
func(t *testing.T) {
|
||||
|
@ -314,11 +280,11 @@ var (
|
|||
{
|
||||
"TestUserUpdateQuota",
|
||||
func(t *testing.T) {
|
||||
quota := 1024 * 1024 * 1024
|
||||
quota := int64(1024 * 1024 * 1024)
|
||||
err := c.Users().UpdateQuota(config.NotExistingUser, quota)
|
||||
assert.NoError(t, err)
|
||||
// TODO : Find better verification : A never connected Users does not have quota available
|
||||
//u, err := c.Users(config.NotExistingUser)
|
||||
// TODO : Find better verification : A never connected users does not have quota available
|
||||
//u, err := c.users(config.NotExistingUser)
|
||||
//assert.NoError(t, err)
|
||||
//assert.Equal(t, quota, u.Quota.Quota)
|
||||
},
|
||||
|
@ -441,15 +407,15 @@ var (
|
|||
{
|
||||
"TestLoggedIn",
|
||||
func(t *testing.T) {
|
||||
c := &Client{}
|
||||
c.capabilities = &types.Capabilities{}
|
||||
c := &client{}
|
||||
c.capabilities = &Capabilities{}
|
||||
assert.False(t, c.loggedIn())
|
||||
},
|
||||
},
|
||||
{
|
||||
"TestLoginInvalidURL",
|
||||
func(t *testing.T) {
|
||||
c, _ = NewClient("")
|
||||
c, _ = newClient("")
|
||||
err := c.Login("", "")
|
||||
assert.Error(t, err)
|
||||
},
|
||||
|
@ -457,7 +423,7 @@ var (
|
|||
{
|
||||
"TestBaseRequest",
|
||||
func(t *testing.T) {
|
||||
c, _ = NewClient("")
|
||||
c, _ = newClient("")
|
||||
_, err := c.baseRequest(http.MethodGet, routes.capabilities, nil, "admin", "invalid")
|
||||
assert.Error(t, err)
|
||||
},
|
||||
|
@ -497,10 +463,10 @@ func TestUserCreateBatchWithoutPassword(t *testing.T) {
|
|||
if c.version.Major < 14 {
|
||||
t.SkipNow()
|
||||
}
|
||||
var us []types.User
|
||||
var us []User
|
||||
for i := 0; i < 5; i++ {
|
||||
u := fmt.Sprintf(config.NotExistingUser+"_%d", i)
|
||||
us = append(us, types.User{
|
||||
us = append(us, User{
|
||||
Username: u,
|
||||
DisplayName: strings.Title(u),
|
||||
Groups: []string{"admin"},
|
||||
|
@ -539,7 +505,7 @@ func TestGroupListDetails(t *testing.T) {
|
|||
if err := initClient(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gs, err := c.Groups().ListDetails()
|
||||
gs, err := c.Groups().ListDetails("")
|
||||
assert.NoError(t, err)
|
||||
assert.NotEmpty(t, gs)
|
||||
}
|
||||
|
@ -581,7 +547,7 @@ func initClient() error {
|
|||
return err
|
||||
}
|
||||
var err error
|
||||
c, err = NewClient(config.URL)
|
||||
c, err = newClient(config.URL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package types
|
||||
package gonextcloud
|
||||
|
||||
//Group
|
||||
// Group is a Nextcloud group
|
||||
type Group struct {
|
||||
ID string `json:"id"`
|
||||
Displayname string `json:"displayname"`
|
170
groupfolders.go
170
groupfolders.go
|
@ -1,140 +1,58 @@
|
|||
package gonextcloud
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
req "github.com/levigross/grequests"
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
import "strconv"
|
||||
|
||||
//GroupFolders contains all Groups Folders available actions
|
||||
type GroupFolders struct {
|
||||
c *Client
|
||||
type groupFolderBadFormatIDAndGroups struct {
|
||||
ID string `json:"id"`
|
||||
MountPoint string `json:"mount_point"`
|
||||
Groups map[string]string `json:"groups"`
|
||||
Quota string `json:"quota"`
|
||||
Size int `json:"size"`
|
||||
}
|
||||
|
||||
//List returns the groups folders
|
||||
func (g *GroupFolders) List() (map[int]types.GroupFolder, error) {
|
||||
res, err := g.c.baseRequest(http.MethodGet, routes.groupfolders, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.GroupFoldersListResponse
|
||||
res.JSON(&r)
|
||||
gfs := formatBadIDAndGroups(r.Ocs.Data)
|
||||
return gfs, nil
|
||||
type groupFolderBadFormatGroups struct {
|
||||
ID int `json:"id"`
|
||||
MountPoint string `json:"mount_point"`
|
||||
Groups map[string]string `json:"groups"`
|
||||
Quota string `json:"quota"`
|
||||
Size int `json:"size"`
|
||||
}
|
||||
|
||||
//Get returns the group folder details
|
||||
func (g *GroupFolders) Get(id int) (types.GroupFolder, error) {
|
||||
res, err := g.c.baseRequest(http.MethodGet, routes.groupfolders, nil, strconv.Itoa(id))
|
||||
if err != nil {
|
||||
return types.GroupFolder{}, err
|
||||
}
|
||||
var r types.GroupFoldersResponse
|
||||
res.JSON(&r)
|
||||
if r.Ocs.Data.ID == 0 {
|
||||
return types.GroupFolder{}, fmt.Errorf("%d is not a valid groupfolder's id", id)
|
||||
}
|
||||
return r.Ocs.Data.FormatGroupFolder(), nil
|
||||
// GroupFolder is group shared folder from groupfolders application
|
||||
type GroupFolder struct {
|
||||
ID int `json:"id"`
|
||||
MountPoint string `json:"mount_point"`
|
||||
Groups map[string]SharePermission `json:"groups"`
|
||||
Quota int `json:"quota"`
|
||||
Size int `json:"size"`
|
||||
}
|
||||
|
||||
//Create creates a group folder
|
||||
func (g *GroupFolders) Create(name string) (id int, err error) {
|
||||
// TODO: Validate Folder name
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"mountpoint": name,
|
||||
},
|
||||
func (gf *groupFolderBadFormatGroups) FormatGroupFolder() GroupFolder {
|
||||
g := GroupFolder{}
|
||||
g.ID = gf.ID
|
||||
g.MountPoint = gf.MountPoint
|
||||
g.Groups = map[string]SharePermission{}
|
||||
for k, v := range gf.Groups {
|
||||
p, _ := strconv.Atoi(v)
|
||||
g.Groups[k] = SharePermission(p)
|
||||
}
|
||||
res, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var r types.GroupFoldersCreateResponse
|
||||
res.JSON(&r)
|
||||
id, _ = strconv.Atoi(r.Ocs.Data.ID)
|
||||
return id, nil
|
||||
q, _ := strconv.Atoi(gf.Quota)
|
||||
g.Quota = q
|
||||
g.Size = gf.Size
|
||||
return g
|
||||
}
|
||||
|
||||
//Rename renames the group folder
|
||||
func (g *GroupFolders) Rename(groupID int, name string) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"mountpoint": name,
|
||||
},
|
||||
func (gf *groupFolderBadFormatIDAndGroups) FormatGroupFolder() GroupFolder {
|
||||
g := GroupFolder{}
|
||||
g.ID, _ = strconv.Atoi(gf.ID)
|
||||
g.MountPoint = gf.MountPoint
|
||||
g.Groups = map[string]SharePermission{}
|
||||
for k, v := range gf.Groups {
|
||||
p, _ := strconv.Atoi(v)
|
||||
g.Groups[k] = SharePermission(p)
|
||||
}
|
||||
// GroupFolders's response does not give any clues about success or failure
|
||||
_, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(groupID), "mountpoint")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//TODO func (c *Client) GroupFoldersDelete(id int) error {
|
||||
|
||||
//AddGroup adds group to folder
|
||||
func (g *GroupFolders) AddGroup(folderID int, groupName string) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"group": groupName,
|
||||
},
|
||||
}
|
||||
// GroupFolders's response does not give any clues about success or failure
|
||||
_, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "groups")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//RemoveGroup remove a group from the group folder
|
||||
func (g *GroupFolders) RemoveGroup(folderID int, groupName string) error {
|
||||
// GroupFolders's response does not give any clues about success or failure
|
||||
_, err := g.c.baseRequest(http.MethodDelete, routes.groupfolders, nil, strconv.Itoa(folderID), "groups", groupName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//SetGroupPermissions set groups permissions
|
||||
func (g *GroupFolders) SetGroupPermissions(folderID int, groupName string, permission types.SharePermission) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"permissions": strconv.Itoa(int(permission)),
|
||||
},
|
||||
}
|
||||
// GroupFolders's response does not give any clues about success or failure
|
||||
_, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "groups", groupName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//SetQuota set quota on the group folder. quota in bytes, use -3 for unlimited
|
||||
func (g *GroupFolders) SetQuota(folderID int, quota int) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"quota": strconv.Itoa(int(quota)),
|
||||
},
|
||||
}
|
||||
// GroupFolders's response does not give any clues about success or failure
|
||||
_, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "quota")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func formatBadIDAndGroups(g map[string]types.GroupFolderBadFormatIDAndGroups) map[int]types.GroupFolder {
|
||||
var gfs = map[int]types.GroupFolder{}
|
||||
for k := range g {
|
||||
i, _ := strconv.Atoi(k)
|
||||
d := g[k]
|
||||
gfs[i] = d.FormatGroupFolder()
|
||||
}
|
||||
return gfs
|
||||
q, _ := strconv.Atoi(gf.Quota)
|
||||
g.Quota = q
|
||||
g.Size = gf.Size
|
||||
return g
|
||||
}
|
||||
|
|
|
@ -0,0 +1,140 @@
|
|||
package gonextcloud
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
req "github.com/levigross/grequests"
|
||||
)
|
||||
|
||||
//groupFolders contains all groups Folders available actions
|
||||
type groupFolders struct {
|
||||
c *client
|
||||
}
|
||||
|
||||
//List returns the groups folders
|
||||
func (g *groupFolders) List() (map[int]GroupFolder, error) {
|
||||
res, err := g.c.baseRequest(http.MethodGet, routes.groupfolders, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r groupFoldersListResponse
|
||||
res.JSON(&r)
|
||||
gfs := formatBadIDAndGroups(r.Ocs.Data)
|
||||
return gfs, nil
|
||||
}
|
||||
|
||||
//Get returns the group folder details
|
||||
func (g *groupFolders) Get(id int) (GroupFolder, error) {
|
||||
res, err := g.c.baseRequest(http.MethodGet, routes.groupfolders, nil, strconv.Itoa(id))
|
||||
if err != nil {
|
||||
return GroupFolder{}, err
|
||||
}
|
||||
var r groupFoldersResponse
|
||||
res.JSON(&r)
|
||||
if r.Ocs.Data.ID == 0 {
|
||||
return GroupFolder{}, fmt.Errorf("%d is not a valid groupfolder's id", id)
|
||||
}
|
||||
return r.Ocs.Data.FormatGroupFolder(), nil
|
||||
}
|
||||
|
||||
//Create creates a group folder
|
||||
func (g *groupFolders) Create(name string) (id int, err error) {
|
||||
// TODO: Validate Folder name
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"mountpoint": name,
|
||||
},
|
||||
}
|
||||
res, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var r groupFoldersCreateResponse
|
||||
res.JSON(&r)
|
||||
id, _ = strconv.Atoi(r.Ocs.Data.ID)
|
||||
return id, nil
|
||||
}
|
||||
|
||||
//Rename renames the group folder
|
||||
func (g *groupFolders) Rename(groupID int, name string) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"mountpoint": name,
|
||||
},
|
||||
}
|
||||
// groupFolders's response does not give any clues about success or failure
|
||||
_, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(groupID), "mountpoint")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//TODO func (c *client) GroupFoldersDelete(id int) error {
|
||||
|
||||
//AddGroup adds group to folder
|
||||
func (g *groupFolders) AddGroup(folderID int, groupName string) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"group": groupName,
|
||||
},
|
||||
}
|
||||
// groupFolders's response does not give any clues about success or failure
|
||||
_, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "groups")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//RemoveGroup remove a group from the group folder
|
||||
func (g *groupFolders) RemoveGroup(folderID int, groupName string) error {
|
||||
// groupFolders's response does not give any clues about success or failure
|
||||
_, err := g.c.baseRequest(http.MethodDelete, routes.groupfolders, nil, strconv.Itoa(folderID), "groups", groupName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//SetGroupPermissions set groups permissions
|
||||
func (g *groupFolders) SetGroupPermissions(folderID int, groupName string, permission SharePermission) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"permissions": strconv.Itoa(int(permission)),
|
||||
},
|
||||
}
|
||||
// groupFolders's response does not give any clues about success or failure
|
||||
_, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "groups", groupName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//SetQuota set quota on the group folder. quota in bytes, use -3 for unlimited
|
||||
func (g *groupFolders) SetQuota(folderID int, quota int) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"quota": strconv.Itoa(int(quota)),
|
||||
},
|
||||
}
|
||||
// groupFolders's response does not give any clues about success or failure
|
||||
_, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "quota")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func formatBadIDAndGroups(g map[string]groupFolderBadFormatIDAndGroups) map[int]GroupFolder {
|
||||
var gfs = map[int]GroupFolder{}
|
||||
for k := range g {
|
||||
i, _ := strconv.Atoi(k)
|
||||
d := g[k]
|
||||
gfs[i] = d.FormatGroupFolder()
|
||||
}
|
||||
return gfs
|
||||
}
|
|
@ -1,9 +1,9 @@
|
|||
package gonextcloud
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
var (
|
||||
|
@ -53,7 +53,7 @@ var (
|
|||
{
|
||||
"TestGroupFoldersSetGroupPermissions",
|
||||
func(t *testing.T) {
|
||||
err := c.GroupFolders().SetGroupPermissions(groupID, "admin", types.ReadPermission)
|
||||
err := c.GroupFolders().SetGroupPermissions(groupID, "admin", ReadPermission)
|
||||
assert.NoError(t, err)
|
||||
},
|
||||
},
|
|
@ -1,51 +1,56 @@
|
|||
package gonextcloud
|
||||
|
||||
import (
|
||||
req "github.com/levigross/grequests"
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
|
||||
"net/http"
|
||||
|
||||
req "github.com/levigross/grequests"
|
||||
)
|
||||
|
||||
//Groups contains all Groups available actions
|
||||
type Groups struct {
|
||||
c *Client
|
||||
//groups contains all groups available actions
|
||||
type groups struct {
|
||||
c *client
|
||||
}
|
||||
|
||||
//List lists the Nextcloud groups
|
||||
func (g *Groups) List() ([]string, error) {
|
||||
func (g *groups) List() ([]string, error) {
|
||||
res, err := g.c.baseRequest(http.MethodGet, routes.groups, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.GroupListResponse
|
||||
var r groupListResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data.Groups, nil
|
||||
}
|
||||
|
||||
//ListDetails lists the Nextcloud groups
|
||||
func (g *Groups) ListDetails() ([]types.Group, error) {
|
||||
res, err := g.c.baseRequest(http.MethodGet, routes.groups, nil, "details")
|
||||
func (g *groups) ListDetails(search string) ([]Group, error) {
|
||||
ro := &req.RequestOptions{
|
||||
Params: map[string]string{
|
||||
"search": search,
|
||||
},
|
||||
}
|
||||
res, err := g.c.baseRequest(http.MethodGet, routes.groups, ro, "details")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.GroupListDetailsResponse
|
||||
var r groupListDetailsResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data.Groups, nil
|
||||
}
|
||||
|
||||
//Users list the group's users
|
||||
func (g *Groups) Users(name string) ([]string, error) {
|
||||
//users list the group's users
|
||||
func (g *groups) Users(name string) ([]string, error) {
|
||||
res, err := g.c.baseRequest(http.MethodGet, routes.groups, nil, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.UserListResponse
|
||||
var r userListResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data.Users, nil
|
||||
}
|
||||
|
||||
//Search return the list of groups matching the search string
|
||||
func (g *Groups) Search(search string) ([]string, error) {
|
||||
func (g *groups) Search(search string) ([]string, error) {
|
||||
ro := &req.RequestOptions{
|
||||
Params: map[string]string{"search": search},
|
||||
}
|
||||
|
@ -53,13 +58,13 @@ func (g *Groups) Search(search string) ([]string, error) {
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.GroupListResponse
|
||||
var r groupListResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data.Groups, nil
|
||||
}
|
||||
|
||||
//Create creates a group
|
||||
func (g *Groups) Create(name string) error {
|
||||
func (g *groups) Create(name string) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"groupid": name,
|
||||
|
@ -69,22 +74,22 @@ func (g *Groups) Create(name string) error {
|
|||
}
|
||||
|
||||
//Delete deletes the group
|
||||
func (g *Groups) Delete(name string) error {
|
||||
func (g *groups) Delete(name string) error {
|
||||
return g.baseRequest(http.MethodDelete, nil, name)
|
||||
}
|
||||
|
||||
//SubAdminList lists the group's subadmins
|
||||
func (g *Groups) SubAdminList(name string) ([]string, error) {
|
||||
func (g *groups) SubAdminList(name string) ([]string, error) {
|
||||
res, err := g.c.baseRequest(http.MethodGet, routes.groups, nil, name, "subadmins")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.UserListResponse
|
||||
var r userListResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data.Users, nil
|
||||
}
|
||||
|
||||
func (g *Groups) baseRequest(method string, ro *req.RequestOptions, subRoute ...string) error {
|
||||
func (g *groups) baseRequest(method string, ro *req.RequestOptions, subRoute ...string) error {
|
||||
_, err := g.c.baseRequest(method, routes.groups, ro, subRoute...)
|
||||
return err
|
||||
}
|
|
@ -0,0 +1,132 @@
|
|||
// Code generated by mockery v1.0.0. DO NOT EDIT.
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/mock"
|
||||
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud"
|
||||
)
|
||||
|
||||
// Apps is an autogenerated mock type for the Apps type
|
||||
type Apps struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
// Disable provides a mock function with given fields: name
|
||||
func (_m *Apps) Disable(name string) error {
|
||||
ret := _m.Called(name)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string) error); ok {
|
||||
r0 = rf(name)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Enable provides a mock function with given fields: name
|
||||
func (_m *Apps) Enable(name string) error {
|
||||
ret := _m.Called(name)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string) error); ok {
|
||||
r0 = rf(name)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Infos provides a mock function with given fields: name
|
||||
func (_m *Apps) Infos(name string) (gonextcloud.App, error) {
|
||||
ret := _m.Called(name)
|
||||
|
||||
var r0 gonextcloud.App
|
||||
if rf, ok := ret.Get(0).(func(string) gonextcloud.App); ok {
|
||||
r0 = rf(name)
|
||||
} else {
|
||||
r0 = ret.Get(0).(gonextcloud.App)
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(string) error); ok {
|
||||
r1 = rf(name)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// List provides a mock function with given fields:
|
||||
func (_m *Apps) List() ([]string, error) {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 []string
|
||||
if rf, ok := ret.Get(0).(func() []string); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]string)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func() error); ok {
|
||||
r1 = rf()
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// ListDisabled provides a mock function with given fields:
|
||||
func (_m *Apps) ListDisabled() ([]string, error) {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 []string
|
||||
if rf, ok := ret.Get(0).(func() []string); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]string)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func() error); ok {
|
||||
r1 = rf()
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// ListEnabled provides a mock function with given fields:
|
||||
func (_m *Apps) ListEnabled() ([]string, error) {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 []string
|
||||
if rf, ok := ret.Get(0).(func() []string); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]string)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func() error); ok {
|
||||
r1 = rf()
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
|
@ -0,0 +1,151 @@
|
|||
// Code generated by mockery v1.0.0. DO NOT EDIT.
|
||||
|
||||
package mocks
|
||||
|
||||
import mock "github.com/stretchr/testify/mock"
|
||||
|
||||
// AppsConfig is an autogenerated mock type for the AppsConfig type
|
||||
type AppsConfig struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
// DeleteValue provides a mock function with given fields: id, key, value
|
||||
func (_m *AppsConfig) DeleteValue(id string, key string, value string) error {
|
||||
ret := _m.Called(id, key, value)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string, string) error); ok {
|
||||
r0 = rf(id, key, value)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Details provides a mock function with given fields: appID
|
||||
func (_m *AppsConfig) Details(appID string) (map[string]string, error) {
|
||||
ret := _m.Called(appID)
|
||||
|
||||
var r0 map[string]string
|
||||
if rf, ok := ret.Get(0).(func(string) map[string]string); ok {
|
||||
r0 = rf(appID)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(map[string]string)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(string) error); ok {
|
||||
r1 = rf(appID)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// Get provides a mock function with given fields:
|
||||
func (_m *AppsConfig) Get() (map[string]map[string]string, error) {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 map[string]map[string]string
|
||||
if rf, ok := ret.Get(0).(func() map[string]map[string]string); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(map[string]map[string]string)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func() error); ok {
|
||||
r1 = rf()
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// Keys provides a mock function with given fields: id
|
||||
func (_m *AppsConfig) Keys(id string) ([]string, error) {
|
||||
ret := _m.Called(id)
|
||||
|
||||
var r0 []string
|
||||
if rf, ok := ret.Get(0).(func(string) []string); ok {
|
||||
r0 = rf(id)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]string)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(string) error); ok {
|
||||
r1 = rf(id)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// List provides a mock function with given fields:
|
||||
func (_m *AppsConfig) List() ([]string, error) {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 []string
|
||||
if rf, ok := ret.Get(0).(func() []string); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]string)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func() error); ok {
|
||||
r1 = rf()
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// SetValue provides a mock function with given fields: id, key, value
|
||||
func (_m *AppsConfig) SetValue(id string, key string, value string) error {
|
||||
ret := _m.Called(id, key, value)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string, string) error); ok {
|
||||
r0 = rf(id, key, value)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Value provides a mock function with given fields: id, key
|
||||
func (_m *AppsConfig) Value(id string, key string) (string, error) {
|
||||
ret := _m.Called(id, key)
|
||||
|
||||
var r0 string
|
||||
if rf, ok := ret.Get(0).(func(string, string) string); ok {
|
||||
r0 = rf(id, key)
|
||||
} else {
|
||||
r0 = ret.Get(0).(string)
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(string, string) error); ok {
|
||||
r1 = rf(id, key)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
// Code generated by mockery v1.0.0. DO NOT EDIT.
|
||||
|
||||
package mocks
|
||||
|
||||
import mock "github.com/stretchr/testify/mock"
|
||||
|
||||
// Auth is an autogenerated mock type for the Auth type
|
||||
type Auth struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
// Login provides a mock function with given fields: username, password
|
||||
func (_m *Auth) Login(username string, password string) error {
|
||||
ret := _m.Called(username, password)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string) error); ok {
|
||||
r0 = rf(username, password)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Logout provides a mock function with given fields:
|
||||
func (_m *Auth) Logout() error {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func() error); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
|
@ -0,0 +1,154 @@
|
|||
// Code generated by mockery v1.0.0. DO NOT EDIT.
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/mock"
|
||||
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud"
|
||||
)
|
||||
|
||||
// Client is an autogenerated mock type for the Client type
|
||||
type Client struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
// Apps provides a mock function with given fields:
|
||||
func (_m *Client) Apps() gonextcloud.Apps {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 gonextcloud.Apps
|
||||
if rf, ok := ret.Get(0).(func() gonextcloud.Apps); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(gonextcloud.Apps)
|
||||
}
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// AppsConfig provides a mock function with given fields:
|
||||
func (_m *Client) AppsConfig() gonextcloud.AppsConfig {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 gonextcloud.AppsConfig
|
||||
if rf, ok := ret.Get(0).(func() gonextcloud.AppsConfig); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(gonextcloud.AppsConfig)
|
||||
}
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// GroupFolders provides a mock function with given fields:
|
||||
func (_m *Client) GroupFolders() gonextcloud.GroupFolders {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 gonextcloud.GroupFolders
|
||||
if rf, ok := ret.Get(0).(func() gonextcloud.GroupFolders); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(gonextcloud.GroupFolders)
|
||||
}
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Groups provides a mock function with given fields:
|
||||
func (_m *Client) Groups() gonextcloud.Groups {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 gonextcloud.Groups
|
||||
if rf, ok := ret.Get(0).(func() gonextcloud.Groups); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(gonextcloud.Groups)
|
||||
}
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Login provides a mock function with given fields: username, password
|
||||
func (_m *Client) Login(username string, password string) error {
|
||||
ret := _m.Called(username, password)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string) error); ok {
|
||||
r0 = rf(username, password)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Logout provides a mock function with given fields:
|
||||
func (_m *Client) Logout() error {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func() error); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Notifications provides a mock function with given fields:
|
||||
func (_m *Client) Notifications() gonextcloud.Notifications {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 gonextcloud.Notifications
|
||||
if rf, ok := ret.Get(0).(func() gonextcloud.Notifications); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(gonextcloud.Notifications)
|
||||
}
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Shares provides a mock function with given fields:
|
||||
func (_m *Client) Shares() gonextcloud.Shares {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 gonextcloud.Shares
|
||||
if rf, ok := ret.Get(0).(func() gonextcloud.Shares); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(gonextcloud.Shares)
|
||||
}
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Users provides a mock function with given fields:
|
||||
func (_m *Client) Users() gonextcloud.Users {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 gonextcloud.Users
|
||||
if rf, ok := ret.Get(0).(func() gonextcloud.Users); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(gonextcloud.Users)
|
||||
}
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
|
@ -0,0 +1,149 @@
|
|||
// Code generated by mockery v1.0.0. DO NOT EDIT.
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/mock"
|
||||
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud"
|
||||
)
|
||||
|
||||
// GroupFolders is an autogenerated mock type for the GroupFolders type
|
||||
type GroupFolders struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
// AddGroup provides a mock function with given fields: folderID, groupName
|
||||
func (_m *GroupFolders) AddGroup(folderID int, groupName string) error {
|
||||
ret := _m.Called(folderID, groupName)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(int, string) error); ok {
|
||||
r0 = rf(folderID, groupName)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Create provides a mock function with given fields: name
|
||||
func (_m *GroupFolders) Create(name string) (int, error) {
|
||||
ret := _m.Called(name)
|
||||
|
||||
var r0 int
|
||||
if rf, ok := ret.Get(0).(func(string) int); ok {
|
||||
r0 = rf(name)
|
||||
} else {
|
||||
r0 = ret.Get(0).(int)
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(string) error); ok {
|
||||
r1 = rf(name)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// Get provides a mock function with given fields: id
|
||||
func (_m *GroupFolders) Get(id int) (gonextcloud.GroupFolder, error) {
|
||||
ret := _m.Called(id)
|
||||
|
||||
var r0 gonextcloud.GroupFolder
|
||||
if rf, ok := ret.Get(0).(func(int) gonextcloud.GroupFolder); ok {
|
||||
r0 = rf(id)
|
||||
} else {
|
||||
r0 = ret.Get(0).(gonextcloud.GroupFolder)
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(int) error); ok {
|
||||
r1 = rf(id)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// List provides a mock function with given fields:
|
||||
func (_m *GroupFolders) List() (map[int]gonextcloud.GroupFolder, error) {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 map[int]gonextcloud.GroupFolder
|
||||
if rf, ok := ret.Get(0).(func() map[int]gonextcloud.GroupFolder); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(map[int]gonextcloud.GroupFolder)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func() error); ok {
|
||||
r1 = rf()
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// RemoveGroup provides a mock function with given fields: folderID, groupName
|
||||
func (_m *GroupFolders) RemoveGroup(folderID int, groupName string) error {
|
||||
ret := _m.Called(folderID, groupName)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(int, string) error); ok {
|
||||
r0 = rf(folderID, groupName)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Rename provides a mock function with given fields: groupID, name
|
||||
func (_m *GroupFolders) Rename(groupID int, name string) error {
|
||||
ret := _m.Called(groupID, name)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(int, string) error); ok {
|
||||
r0 = rf(groupID, name)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// SetGroupPermissions provides a mock function with given fields: folderID, groupName, permission
|
||||
func (_m *GroupFolders) SetGroupPermissions(folderID int, groupName string, permission gonextcloud.SharePermission) error {
|
||||
ret := _m.Called(folderID, groupName, permission)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(int, string, gonextcloud.SharePermission) error); ok {
|
||||
r0 = rf(folderID, groupName, permission)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// SetQuota provides a mock function with given fields: folderID, quota
|
||||
func (_m *GroupFolders) SetQuota(folderID int, quota int) error {
|
||||
ret := _m.Called(folderID, quota)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(int, int) error); ok {
|
||||
r0 = rf(folderID, quota)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
|
@ -0,0 +1,157 @@
|
|||
// Code generated by mockery v1.0.0. DO NOT EDIT.
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/mock"
|
||||
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud"
|
||||
)
|
||||
|
||||
// Groups is an autogenerated mock type for the Groups type
|
||||
type Groups struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
// Create provides a mock function with given fields: name
|
||||
func (_m *Groups) Create(name string) error {
|
||||
ret := _m.Called(name)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string) error); ok {
|
||||
r0 = rf(name)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Delete provides a mock function with given fields: name
|
||||
func (_m *Groups) Delete(name string) error {
|
||||
ret := _m.Called(name)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string) error); ok {
|
||||
r0 = rf(name)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// List provides a mock function with given fields:
|
||||
func (_m *Groups) List() ([]string, error) {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 []string
|
||||
if rf, ok := ret.Get(0).(func() []string); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]string)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func() error); ok {
|
||||
r1 = rf()
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// ListDetails provides a mock function with given fields: search
|
||||
func (_m *Groups) ListDetails(search string) ([]gonextcloud.Group, error) {
|
||||
ret := _m.Called(search)
|
||||
|
||||
var r0 []gonextcloud.Group
|
||||
if rf, ok := ret.Get(0).(func(string) []gonextcloud.Group); ok {
|
||||
r0 = rf(search)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]gonextcloud.Group)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(string) error); ok {
|
||||
r1 = rf(search)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// Search provides a mock function with given fields: search
|
||||
func (_m *Groups) Search(search string) ([]string, error) {
|
||||
ret := _m.Called(search)
|
||||
|
||||
var r0 []string
|
||||
if rf, ok := ret.Get(0).(func(string) []string); ok {
|
||||
r0 = rf(search)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]string)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(string) error); ok {
|
||||
r1 = rf(search)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// SubAdminList provides a mock function with given fields: name
|
||||
func (_m *Groups) SubAdminList(name string) ([]string, error) {
|
||||
ret := _m.Called(name)
|
||||
|
||||
var r0 []string
|
||||
if rf, ok := ret.Get(0).(func(string) []string); ok {
|
||||
r0 = rf(name)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]string)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(string) error); ok {
|
||||
r1 = rf(name)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// Users provides a mock function with given fields: name
|
||||
func (_m *Groups) Users(name string) ([]string, error) {
|
||||
ret := _m.Called(name)
|
||||
|
||||
var r0 []string
|
||||
if rf, ok := ret.Get(0).(func(string) []string); ok {
|
||||
r0 = rf(name)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]string)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(string) error); ok {
|
||||
r1 = rf(name)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
|
@ -0,0 +1,128 @@
|
|||
// Code generated by mockery v1.0.0. DO NOT EDIT.
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/mock"
|
||||
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud"
|
||||
)
|
||||
|
||||
// Notifications is an autogenerated mock type for the Notifications type
|
||||
type Notifications struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
// AdminAvailable provides a mock function with given fields:
|
||||
func (_m *Notifications) AdminAvailable() error {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func() error); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Available provides a mock function with given fields:
|
||||
func (_m *Notifications) Available() error {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func() error); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Create provides a mock function with given fields: userID, title, message
|
||||
func (_m *Notifications) Create(userID string, title string, message string) error {
|
||||
ret := _m.Called(userID, title, message)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string, string) error); ok {
|
||||
r0 = rf(userID, title, message)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Delete provides a mock function with given fields: id
|
||||
func (_m *Notifications) Delete(id int) error {
|
||||
ret := _m.Called(id)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(int) error); ok {
|
||||
r0 = rf(id)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// DeleteAll provides a mock function with given fields:
|
||||
func (_m *Notifications) DeleteAll() error {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func() error); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Get provides a mock function with given fields: id
|
||||
func (_m *Notifications) Get(id int) (gonextcloud.Notification, error) {
|
||||
ret := _m.Called(id)
|
||||
|
||||
var r0 gonextcloud.Notification
|
||||
if rf, ok := ret.Get(0).(func(int) gonextcloud.Notification); ok {
|
||||
r0 = rf(id)
|
||||
} else {
|
||||
r0 = ret.Get(0).(gonextcloud.Notification)
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(int) error); ok {
|
||||
r1 = rf(id)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// List provides a mock function with given fields:
|
||||
func (_m *Notifications) List() ([]gonextcloud.Notification, error) {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 []gonextcloud.Notification
|
||||
if rf, ok := ret.Get(0).(func() []gonextcloud.Notification); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]gonextcloud.Notification)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func() error); ok {
|
||||
r1 = rf()
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
|
@ -0,0 +1,186 @@
|
|||
// Code generated by mockery v1.0.0. DO NOT EDIT.
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/mock"
|
||||
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud"
|
||||
)
|
||||
|
||||
// Shares is an autogenerated mock type for the Shares type
|
||||
type Shares struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
// Create provides a mock function with given fields: path, shareType, permission, shareWith, publicUpload, password
|
||||
func (_m *Shares) Create(path string, shareType gonextcloud.ShareType, permission gonextcloud.SharePermission, shareWith string, publicUpload bool, password string) (gonextcloud.Share, error) {
|
||||
ret := _m.Called(path, shareType, permission, shareWith, publicUpload, password)
|
||||
|
||||
var r0 gonextcloud.Share
|
||||
if rf, ok := ret.Get(0).(func(string, gonextcloud.ShareType, gonextcloud.SharePermission, string, bool, string) gonextcloud.Share); ok {
|
||||
r0 = rf(path, shareType, permission, shareWith, publicUpload, password)
|
||||
} else {
|
||||
r0 = ret.Get(0).(gonextcloud.Share)
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(string, gonextcloud.ShareType, gonextcloud.SharePermission, string, bool, string) error); ok {
|
||||
r1 = rf(path, shareType, permission, shareWith, publicUpload, password)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// Delete provides a mock function with given fields: shareID
|
||||
func (_m *Shares) Delete(shareID int) error {
|
||||
ret := _m.Called(shareID)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(int) error); ok {
|
||||
r0 = rf(shareID)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Get provides a mock function with given fields: shareID
|
||||
func (_m *Shares) Get(shareID string) (gonextcloud.Share, error) {
|
||||
ret := _m.Called(shareID)
|
||||
|
||||
var r0 gonextcloud.Share
|
||||
if rf, ok := ret.Get(0).(func(string) gonextcloud.Share); ok {
|
||||
r0 = rf(shareID)
|
||||
} else {
|
||||
r0 = ret.Get(0).(gonextcloud.Share)
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(string) error); ok {
|
||||
r1 = rf(shareID)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// GetFromPath provides a mock function with given fields: path, reshares, subfiles
|
||||
func (_m *Shares) GetFromPath(path string, reshares bool, subfiles bool) ([]gonextcloud.Share, error) {
|
||||
ret := _m.Called(path, reshares, subfiles)
|
||||
|
||||
var r0 []gonextcloud.Share
|
||||
if rf, ok := ret.Get(0).(func(string, bool, bool) []gonextcloud.Share); ok {
|
||||
r0 = rf(path, reshares, subfiles)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]gonextcloud.Share)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(string, bool, bool) error); ok {
|
||||
r1 = rf(path, reshares, subfiles)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// List provides a mock function with given fields:
|
||||
func (_m *Shares) List() ([]gonextcloud.Share, error) {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 []gonextcloud.Share
|
||||
if rf, ok := ret.Get(0).(func() []gonextcloud.Share); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]gonextcloud.Share)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func() error); ok {
|
||||
r1 = rf()
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// Update provides a mock function with given fields: shareUpdate
|
||||
func (_m *Shares) Update(shareUpdate gonextcloud.ShareUpdate) error {
|
||||
ret := _m.Called(shareUpdate)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(gonextcloud.ShareUpdate) error); ok {
|
||||
r0 = rf(shareUpdate)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// UpdateExpireDate provides a mock function with given fields: shareID, expireDate
|
||||
func (_m *Shares) UpdateExpireDate(shareID int, expireDate string) error {
|
||||
ret := _m.Called(shareID, expireDate)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(int, string) error); ok {
|
||||
r0 = rf(shareID, expireDate)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// UpdatePassword provides a mock function with given fields: shareID, password
|
||||
func (_m *Shares) UpdatePassword(shareID int, password string) error {
|
||||
ret := _m.Called(shareID, password)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(int, string) error); ok {
|
||||
r0 = rf(shareID, password)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// UpdatePermissions provides a mock function with given fields: shareID, permissions
|
||||
func (_m *Shares) UpdatePermissions(shareID int, permissions gonextcloud.SharePermission) error {
|
||||
ret := _m.Called(shareID, permissions)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(int, gonextcloud.SharePermission) error); ok {
|
||||
r0 = rf(shareID, permissions)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// UpdatePublicUpload provides a mock function with given fields: shareID, public
|
||||
func (_m *Shares) UpdatePublicUpload(shareID int, public bool) error {
|
||||
ret := _m.Called(shareID, public)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(int, bool) error); ok {
|
||||
r0 = rf(shareID, public)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
|
@ -0,0 +1,439 @@
|
|||
// Code generated by mockery v1.0.0. DO NOT EDIT.
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/mock"
|
||||
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud"
|
||||
)
|
||||
|
||||
// Users is an autogenerated mock type for the Users type
|
||||
type Users struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
// Create provides a mock function with given fields: username, password, user
|
||||
func (_m *Users) Create(username string, password string, user *gonextcloud.UserDetails) error {
|
||||
ret := _m.Called(username, password, user)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string, *gonextcloud.UserDetails) error); ok {
|
||||
r0 = rf(username, password, user)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// CreateBatchWithoutPassword provides a mock function with given fields: users
|
||||
func (_m *Users) CreateBatchWithoutPassword(users []gonextcloud.User) error {
|
||||
ret := _m.Called(users)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func([]gonextcloud.User) error); ok {
|
||||
r0 = rf(users)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// CreateWithoutPassword provides a mock function with given fields: username, email, displayName, quota, language, groups
|
||||
func (_m *Users) CreateWithoutPassword(username string, email string, displayName string, quota string, language string, groups ...string) error {
|
||||
_va := make([]interface{}, len(groups))
|
||||
for _i := range groups {
|
||||
_va[_i] = groups[_i]
|
||||
}
|
||||
var _ca []interface{}
|
||||
_ca = append(_ca, username, email, displayName, quota, language)
|
||||
_ca = append(_ca, _va...)
|
||||
ret := _m.Called(_ca...)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string, string, string, string, ...string) error); ok {
|
||||
r0 = rf(username, email, displayName, quota, language, groups...)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Delete provides a mock function with given fields: name
|
||||
func (_m *Users) Delete(name string) error {
|
||||
ret := _m.Called(name)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string) error); ok {
|
||||
r0 = rf(name)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Disable provides a mock function with given fields: name
|
||||
func (_m *Users) Disable(name string) error {
|
||||
ret := _m.Called(name)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string) error); ok {
|
||||
r0 = rf(name)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Enable provides a mock function with given fields: name
|
||||
func (_m *Users) Enable(name string) error {
|
||||
ret := _m.Called(name)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string) error); ok {
|
||||
r0 = rf(name)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Get provides a mock function with given fields: name
|
||||
func (_m *Users) Get(name string) (*gonextcloud.UserDetails, error) {
|
||||
ret := _m.Called(name)
|
||||
|
||||
var r0 *gonextcloud.UserDetails
|
||||
if rf, ok := ret.Get(0).(func(string) *gonextcloud.UserDetails); ok {
|
||||
r0 = rf(name)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(*gonextcloud.UserDetails)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(string) error); ok {
|
||||
r1 = rf(name)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// GroupAdd provides a mock function with given fields: name, group
|
||||
func (_m *Users) GroupAdd(name string, group string) error {
|
||||
ret := _m.Called(name, group)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string) error); ok {
|
||||
r0 = rf(name, group)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// GroupDemote provides a mock function with given fields: name, group
|
||||
func (_m *Users) GroupDemote(name string, group string) error {
|
||||
ret := _m.Called(name, group)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string) error); ok {
|
||||
r0 = rf(name, group)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// GroupList provides a mock function with given fields: name
|
||||
func (_m *Users) GroupList(name string) ([]string, error) {
|
||||
ret := _m.Called(name)
|
||||
|
||||
var r0 []string
|
||||
if rf, ok := ret.Get(0).(func(string) []string); ok {
|
||||
r0 = rf(name)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]string)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(string) error); ok {
|
||||
r1 = rf(name)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// GroupPromote provides a mock function with given fields: name, group
|
||||
func (_m *Users) GroupPromote(name string, group string) error {
|
||||
ret := _m.Called(name, group)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string) error); ok {
|
||||
r0 = rf(name, group)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// GroupRemove provides a mock function with given fields: name, group
|
||||
func (_m *Users) GroupRemove(name string, group string) error {
|
||||
ret := _m.Called(name, group)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string) error); ok {
|
||||
r0 = rf(name, group)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// GroupSubAdminList provides a mock function with given fields: name
|
||||
func (_m *Users) GroupSubAdminList(name string) ([]string, error) {
|
||||
ret := _m.Called(name)
|
||||
|
||||
var r0 []string
|
||||
if rf, ok := ret.Get(0).(func(string) []string); ok {
|
||||
r0 = rf(name)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]string)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(string) error); ok {
|
||||
r1 = rf(name)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// List provides a mock function with given fields:
|
||||
func (_m *Users) List() ([]string, error) {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 []string
|
||||
if rf, ok := ret.Get(0).(func() []string); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]string)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func() error); ok {
|
||||
r1 = rf()
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// ListDetails provides a mock function with given fields:
|
||||
func (_m *Users) ListDetails() (map[string]gonextcloud.UserDetails, error) {
|
||||
ret := _m.Called()
|
||||
|
||||
var r0 map[string]gonextcloud.UserDetails
|
||||
if rf, ok := ret.Get(0).(func() map[string]gonextcloud.UserDetails); ok {
|
||||
r0 = rf()
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(map[string]gonextcloud.UserDetails)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func() error); ok {
|
||||
r1 = rf()
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// Search provides a mock function with given fields: search
|
||||
func (_m *Users) Search(search string) ([]string, error) {
|
||||
ret := _m.Called(search)
|
||||
|
||||
var r0 []string
|
||||
if rf, ok := ret.Get(0).(func(string) []string); ok {
|
||||
r0 = rf(search)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]string)
|
||||
}
|
||||
}
|
||||
|
||||
var r1 error
|
||||
if rf, ok := ret.Get(1).(func(string) error); ok {
|
||||
r1 = rf(search)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// SendWelcomeEmail provides a mock function with given fields: name
|
||||
func (_m *Users) SendWelcomeEmail(name string) error {
|
||||
ret := _m.Called(name)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string) error); ok {
|
||||
r0 = rf(name)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// Update provides a mock function with given fields: user
|
||||
func (_m *Users) Update(user *gonextcloud.UserDetails) error {
|
||||
ret := _m.Called(user)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(*gonextcloud.UserDetails) error); ok {
|
||||
r0 = rf(user)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// UpdateAddress provides a mock function with given fields: name, address
|
||||
func (_m *Users) UpdateAddress(name string, address string) error {
|
||||
ret := _m.Called(name, address)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string) error); ok {
|
||||
r0 = rf(name, address)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// UpdateDisplayName provides a mock function with given fields: name, displayName
|
||||
func (_m *Users) UpdateDisplayName(name string, displayName string) error {
|
||||
ret := _m.Called(name, displayName)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string) error); ok {
|
||||
r0 = rf(name, displayName)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// UpdateEmail provides a mock function with given fields: name, email
|
||||
func (_m *Users) UpdateEmail(name string, email string) error {
|
||||
ret := _m.Called(name, email)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string) error); ok {
|
||||
r0 = rf(name, email)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// UpdatePassword provides a mock function with given fields: name, password
|
||||
func (_m *Users) UpdatePassword(name string, password string) error {
|
||||
ret := _m.Called(name, password)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string) error); ok {
|
||||
r0 = rf(name, password)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// UpdatePhone provides a mock function with given fields: name, phone
|
||||
func (_m *Users) UpdatePhone(name string, phone string) error {
|
||||
ret := _m.Called(name, phone)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string) error); ok {
|
||||
r0 = rf(name, phone)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// UpdateQuota provides a mock function with given fields: name, quota
|
||||
func (_m *Users) UpdateQuota(name string, quota int64) error {
|
||||
ret := _m.Called(name, quota)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, int64) error); ok {
|
||||
r0 = rf(name, quota)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// UpdateTwitter provides a mock function with given fields: name, twitter
|
||||
func (_m *Users) UpdateTwitter(name string, twitter string) error {
|
||||
ret := _m.Called(name, twitter)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string) error); ok {
|
||||
r0 = rf(name, twitter)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
||||
|
||||
// UpdateWebSite provides a mock function with given fields: name, website
|
||||
func (_m *Users) UpdateWebSite(name string, website string) error {
|
||||
ret := _m.Called(name, website)
|
||||
|
||||
var r0 error
|
||||
if rf, ok := ret.Get(0).(func(string, string) error); ok {
|
||||
r0 = rf(name, website)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
|
||||
return r0
|
||||
}
|
|
@ -1,17 +1,72 @@
|
|||
package gonextcloud
|
||||
|
||||
import (
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
//Monitoring return nextcloud monitoring statistics
|
||||
func (c *Client) Monitoring() (*types.Monitoring, error) {
|
||||
res, err := c.baseRequest(http.MethodGet, routes.monitor, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var m types.MonitoringResponse
|
||||
res.JSON(&m)
|
||||
return &m.Ocs.Data, nil
|
||||
// System contains the operating system statistics
|
||||
type System struct {
|
||||
Version string `json:"version"`
|
||||
Theme string `json:"theme"`
|
||||
EnableAvatars string `json:"enable_avatars"`
|
||||
EnablePreviews string `json:"enable_previews"`
|
||||
MemcacheLocal string `json:"memcache.local"`
|
||||
MemcacheDistributed string `json:"memcache.distributed"`
|
||||
FilelockingEnabled string `json:"filelocking.enabled"`
|
||||
MemcacheLocking string `json:"memcache.locking"`
|
||||
Debug string `json:"debug"`
|
||||
Freespace int64 `json:"freespace"`
|
||||
Cpuload []float32 `json:"cpuload"`
|
||||
MemTotal int `json:"mem_total"`
|
||||
MemFree int `json:"mem_free"`
|
||||
SwapTotal int `json:"swap_total"`
|
||||
SwapFree int `json:"swap_free"`
|
||||
}
|
||||
|
||||
// Monitoring contains the nextcloud monitoring statistics
|
||||
type Monitoring struct {
|
||||
// Nextcloud Statistics
|
||||
Nextcloud struct {
|
||||
System System `json:"system"`
|
||||
Storage Storage `json:"storage"`
|
||||
Shares struct {
|
||||
NumShares int `json:"num_shares"`
|
||||
NumSharesUser int `json:"num_shares_user"`
|
||||
NumSharesGroups int `json:"num_shares_groups"`
|
||||
NumSharesLink int `json:"num_shares_link"`
|
||||
NumSharesLinkNoPassword int `json:"num_shares_link_no_password"`
|
||||
NumFedSharesSent int `json:"num_fed_shares_sent"`
|
||||
NumFedSharesReceived int `json:"num_fed_shares_received"`
|
||||
} `json:"shares"`
|
||||
} `json:"nextcloud"`
|
||||
// Server statistics
|
||||
Server struct {
|
||||
Webserver string `json:"webserver"`
|
||||
Php struct {
|
||||
Version string `json:"version"`
|
||||
MemoryLimit int `json:"memory_limit"`
|
||||
MaxExecutionTime int `json:"max_execution_time"`
|
||||
UploadMaxFilesize int `json:"upload_max_filesize"`
|
||||
} `json:"php"`
|
||||
Database struct {
|
||||
Type string `json:"type"`
|
||||
Version string `json:"version"`
|
||||
Size int `json:"size"`
|
||||
} `json:"database"`
|
||||
} `json:"server"`
|
||||
// Active users statistics
|
||||
ActiveUsers ActiveUsers `json:"activeUsers"`
|
||||
}
|
||||
|
||||
// ActiveUsers contains the active users statistics
|
||||
type ActiveUsers struct {
|
||||
Last5Minutes int `json:"last5minutes"`
|
||||
Last1Hour int `json:"last1hour"`
|
||||
Last24Hours int `json:"last24hours"`
|
||||
}
|
||||
|
||||
// Storage contains the storage statistics
|
||||
type Storage struct {
|
||||
NumUsers int `json:"num_users"`
|
||||
NumFiles int `json:"num_files"`
|
||||
NumStorages int `json:"num_storages"`
|
||||
NumStoragesLocal int `json:"num_storages_local"`
|
||||
NumStoragesHome int `json:"num_storages_home"`
|
||||
NumStoragesOther int `json:"num_storages_other"`
|
||||
}
|
||||
|
|
|
@ -0,0 +1,16 @@
|
|||
package gonextcloud
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
//Monitoring return nextcloud monitoring statistics
|
||||
func (c *client) Monitoring() (*Monitoring, error) {
|
||||
res, err := c.baseRequest(http.MethodGet, routes.monitor, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var m monitoringResponse
|
||||
res.JSON(&m)
|
||||
return &m.Ocs.Data, nil
|
||||
}
|
|
@ -1,7 +1,8 @@
|
|||
package types
|
||||
package gonextcloud
|
||||
|
||||
import "time"
|
||||
|
||||
// Notification is a nextcloud notification (from notification app)
|
||||
type Notification struct {
|
||||
NotificationID int `json:"notification_id"`
|
||||
App string `json:"app"`
|
|
@ -2,19 +2,19 @@ package gonextcloud
|
|||
|
||||
import (
|
||||
"errors"
|
||||
req "github.com/levigross/grequests"
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
req "github.com/levigross/grequests"
|
||||
)
|
||||
|
||||
//Notifications contains all Notifications available actions
|
||||
type Notifications struct {
|
||||
c *Client
|
||||
//notifications contains all notifications available actions
|
||||
type notifications struct {
|
||||
c *client
|
||||
}
|
||||
|
||||
//List returns all the notifications
|
||||
func (n *Notifications) List() ([]types.Notification, error) {
|
||||
func (n *notifications) List() ([]Notification, error) {
|
||||
if err := n.Available(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -22,27 +22,27 @@ func (n *Notifications) List() ([]types.Notification, error) {
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.NotificationsListResponse
|
||||
var r notificationsListResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data, nil
|
||||
}
|
||||
|
||||
//Get returns the notification corresponding to the id
|
||||
func (n *Notifications) Get(id int) (types.Notification, error) {
|
||||
func (n *notifications) Get(id int) (Notification, error) {
|
||||
if err := n.Available(); err != nil {
|
||||
return types.Notification{}, err
|
||||
return Notification{}, err
|
||||
}
|
||||
res, err := n.c.baseRequest(http.MethodGet, routes.notifications, nil, strconv.Itoa(id))
|
||||
if err != nil {
|
||||
return types.Notification{}, err
|
||||
return Notification{}, err
|
||||
}
|
||||
var r types.NotificationResponse
|
||||
var r notificationResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data, nil
|
||||
}
|
||||
|
||||
//Delete deletes the notification corresponding to the id
|
||||
func (n *Notifications) Delete(id int) error {
|
||||
func (n *notifications) Delete(id int) error {
|
||||
if err := n.Available(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -51,7 +51,7 @@ func (n *Notifications) Delete(id int) error {
|
|||
}
|
||||
|
||||
//DeleteAll deletes all notifications
|
||||
func (n *Notifications) DeleteAll() error {
|
||||
func (n *notifications) DeleteAll() error {
|
||||
if err := n.Available(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -60,7 +60,7 @@ func (n *Notifications) DeleteAll() error {
|
|||
}
|
||||
|
||||
//Create creates a notification (if the user is an admin)
|
||||
func (n *Notifications) Create(userID, title, message string) error {
|
||||
func (n *notifications) Create(userID, title, message string) error {
|
||||
if err := n.AdminAvailable(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -75,7 +75,7 @@ func (n *Notifications) Create(userID, title, message string) error {
|
|||
}
|
||||
|
||||
//AdminAvailable returns an error if the admin-notifications app is not installed
|
||||
func (n *Notifications) AdminAvailable() error {
|
||||
func (n *notifications) AdminAvailable() error {
|
||||
if len(n.c.capabilities.Notifications.AdminNotifications) == 0 {
|
||||
return errors.New("'admin notifications' not available on this instance")
|
||||
}
|
||||
|
@ -83,7 +83,7 @@ func (n *Notifications) AdminAvailable() error {
|
|||
}
|
||||
|
||||
//Available returns an error if the notifications app is not installed
|
||||
func (n *Notifications) Available() error {
|
||||
func (n *notifications) Available() error {
|
||||
if len(n.c.capabilities.Notifications.OcsEndpoints) == 0 {
|
||||
return errors.New("notifications not available on this instance")
|
||||
}
|
|
@ -1,7 +1,7 @@
|
|||
package types
|
||||
package gonextcloud
|
||||
|
||||
//Meta
|
||||
type Meta struct {
|
||||
//meta
|
||||
type meta struct {
|
||||
Status string `json:"status"`
|
||||
Statuscode int `json:"statuscode"`
|
||||
Message string `json:"message"`
|
||||
|
@ -9,109 +9,109 @@ type Meta struct {
|
|||
Itemsperpage string `json:"itemsperpage"`
|
||||
}
|
||||
|
||||
//ErrorResponse
|
||||
type ErrorResponse struct {
|
||||
//errorResponse
|
||||
type errorResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Meta meta `json:"meta"`
|
||||
Data []interface{} `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
//UserListResponse
|
||||
type UserListResponse struct {
|
||||
//userListResponse
|
||||
type userListResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Meta meta `json:"meta"`
|
||||
Data struct {
|
||||
Users []string `json:"users"`
|
||||
} `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
type UserListDetailsResponse struct {
|
||||
type userListDetailsResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Meta meta `json:"meta"`
|
||||
Data struct {
|
||||
Users map[string]UserDetails `json:"users"`
|
||||
} `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
//UserResponse
|
||||
type UserResponse struct {
|
||||
//userResponse
|
||||
type userResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Meta meta `json:"meta"`
|
||||
Data UserDetails `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
//BaseResponse
|
||||
type BaseResponse struct {
|
||||
//baseResponse
|
||||
type baseResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Meta meta `json:"meta"`
|
||||
Data []string `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
//GroupListResponse
|
||||
type GroupListResponse struct {
|
||||
//groupListResponse
|
||||
type groupListResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Meta meta `json:"meta"`
|
||||
Data struct {
|
||||
Groups []string `json:"groups"`
|
||||
} `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
//GroupListDetailsResponse
|
||||
type GroupListDetailsResponse struct {
|
||||
//groupListDetailsResponse
|
||||
type groupListDetailsResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Meta meta `json:"meta"`
|
||||
Data struct {
|
||||
Groups []Group `json:"groups"`
|
||||
} `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
//AppListResponse
|
||||
type AppListResponse struct {
|
||||
//appListResponse
|
||||
type appListResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Meta meta `json:"meta"`
|
||||
Data struct {
|
||||
Apps []string `json:"apps"`
|
||||
} `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
//AppResponse
|
||||
type AppResponse struct {
|
||||
//appResponse
|
||||
type appResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Meta meta `json:"meta"`
|
||||
Data App `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
type AppConfigResponse struct {
|
||||
type appConfigResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Meta meta `json:"meta"`
|
||||
Data struct {
|
||||
Data []string `json:"data"`
|
||||
} `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
type AppcConfigValueResponse struct {
|
||||
type appcConfigValueResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Meta meta `json:"meta"`
|
||||
Data struct {
|
||||
Data string `json:"data"`
|
||||
} `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
//CapabilitiesResponse
|
||||
type CapabilitiesResponse struct {
|
||||
//capabilitiesResponse
|
||||
type capabilitiesResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Meta meta `json:"meta"`
|
||||
Data struct {
|
||||
Version Version `json:"version"`
|
||||
Capabilities Capabilities `json:"capabilities"`
|
||||
|
@ -119,6 +119,7 @@ type CapabilitiesResponse struct {
|
|||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
// Version contains the nextcloud version informations
|
||||
type Version struct {
|
||||
Major int `json:"major"`
|
||||
Minor int `json:"minor"`
|
||||
|
@ -127,58 +128,58 @@ type Version struct {
|
|||
Edition string `json:"edition"`
|
||||
}
|
||||
|
||||
type MonitoringResponse struct {
|
||||
type monitoringResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Meta meta `json:"meta"`
|
||||
Data Monitoring `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
type SharesListResponse struct {
|
||||
type sharesListResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Meta meta `json:"meta"`
|
||||
Data []Share `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
type SharesResponse struct {
|
||||
type sharesResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Meta meta `json:"meta"`
|
||||
Data Share `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
type GroupFoldersListResponse struct {
|
||||
type groupFoldersListResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Data map[string]GroupFolderBadFormatIDAndGroups `json:"data"`
|
||||
Meta meta `json:"meta"`
|
||||
Data map[string]groupFolderBadFormatIDAndGroups `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
type GroupFoldersCreateResponse struct {
|
||||
type groupFoldersCreateResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Data GroupFolderBadFormatIDAndGroups `json:"data"`
|
||||
Meta meta `json:"meta"`
|
||||
Data groupFolderBadFormatIDAndGroups `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
type GroupFoldersResponse struct {
|
||||
type groupFoldersResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Data GroupFolderBadFormatGroups `json:"data"`
|
||||
Meta meta `json:"meta"`
|
||||
Data groupFolderBadFormatGroups `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
type NotificationsListResponse struct {
|
||||
type notificationsListResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Meta meta `json:"meta"`
|
||||
Data []Notification `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
||||
|
||||
type NotificationResponse struct {
|
||||
type notificationResponse struct {
|
||||
Ocs struct {
|
||||
Meta Meta `json:"meta"`
|
||||
Meta meta `json:"meta"`
|
||||
Data Notification `json:"data"`
|
||||
} `json:"ocs"`
|
||||
}
|
|
@ -2,8 +2,8 @@ package gonextcloud
|
|||
|
||||
import "net/url"
|
||||
|
||||
// Routes references the available routes
|
||||
type Routes struct {
|
||||
// apiRoutes references the available routes
|
||||
type apiRoutes struct {
|
||||
capabilities *url.URL
|
||||
users *url.URL
|
||||
groups *url.URL
|
||||
|
@ -20,7 +20,7 @@ const badRequest = 998
|
|||
|
||||
var (
|
||||
apiPath = &url.URL{Path: "/ocs/v2.php"}
|
||||
routes = Routes{
|
||||
routes = apiRoutes{
|
||||
capabilities: &url.URL{Path: apiPath.Path + "/cloud/capabilities"},
|
||||
users: &url.URL{Path: apiPath.Path + "/cloud/users"},
|
||||
groups: &url.URL{Path: apiPath.Path + "/cloud/groups"},
|
||||
|
|
225
shares.go
225
shares.go
|
@ -1,171 +1,68 @@
|
|||
package gonextcloud
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
req "github.com/levigross/grequests"
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
// ShareType is the nextcloud shares types enum :
|
||||
type ShareType int
|
||||
|
||||
// SharePermission is the nextcloud share permissions enum
|
||||
type SharePermission int
|
||||
|
||||
const (
|
||||
// UserShare is a file or folder shared with other user(s)
|
||||
UserShare ShareType = 0
|
||||
// GroupShare is a file or folder shared with a group
|
||||
GroupShare ShareType = 1
|
||||
// PublicLinkShare is a file or folder shared through public link
|
||||
PublicLinkShare ShareType = 3
|
||||
// FederatedCloudShare is a file or folder shared through federated cloud
|
||||
FederatedCloudShare ShareType = 6
|
||||
|
||||
// ReadPermission grant read permission
|
||||
ReadPermission SharePermission = 1
|
||||
// UpdatePermission grant update permission
|
||||
UpdatePermission SharePermission = 2
|
||||
// CreatePermission grant create permission
|
||||
CreatePermission SharePermission = 4
|
||||
// DeletePermission grant delete permission
|
||||
DeletePermission SharePermission = 8
|
||||
// ReSharePermission grant resharing permission
|
||||
ReSharePermission SharePermission = 16
|
||||
// AllPermissions grant all permissions
|
||||
AllPermissions SharePermission = 31
|
||||
)
|
||||
|
||||
//Shares contains all Shares available actions
|
||||
type Shares struct {
|
||||
c *Client
|
||||
// ShareUpdate contains the data required in order to update a nextcloud share
|
||||
type ShareUpdate struct {
|
||||
ShareID int
|
||||
Permissions SharePermission
|
||||
Password string
|
||||
PublicUpload bool
|
||||
ExpireDate string
|
||||
}
|
||||
|
||||
//List list all shares of the logged in user
|
||||
func (s *Shares) List() ([]types.Share, error) {
|
||||
res, err := s.c.baseRequest(http.MethodGet, routes.shares, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.SharesListResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data, nil
|
||||
}
|
||||
|
||||
//GetFromPath return shares from a specific file or folder
|
||||
func (s *Shares) GetFromPath(path string, reshares bool, subfiles bool) ([]types.Share, error) {
|
||||
ro := &req.RequestOptions{
|
||||
Params: map[string]string{
|
||||
"path": path,
|
||||
"reshares": strconv.FormatBool(reshares),
|
||||
"subfiles": strconv.FormatBool(subfiles),
|
||||
},
|
||||
}
|
||||
res, err := s.c.baseRequest(http.MethodGet, routes.shares, ro)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.SharesListResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data, nil
|
||||
}
|
||||
|
||||
//Get information about a known Share
|
||||
func (s *Shares) Get(shareID string) (types.Share, error) {
|
||||
res, err := s.c.baseRequest(http.MethodGet, routes.shares, nil, shareID)
|
||||
if err != nil {
|
||||
return types.Share{}, err
|
||||
}
|
||||
var r types.SharesListResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data[0], nil
|
||||
}
|
||||
|
||||
//Create create a share
|
||||
func (s *Shares) Create(
|
||||
path string,
|
||||
shareType types.ShareType,
|
||||
permission types.SharePermission,
|
||||
shareWith string,
|
||||
publicUpload bool,
|
||||
password string,
|
||||
) (types.Share, error) {
|
||||
|
||||
if (shareType == types.UserShare || shareType == types.GroupShare) && shareWith == "" {
|
||||
return types.Share{}, fmt.Errorf("shareWith cannot be empty for ShareType UserShare or GroupShare")
|
||||
}
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"path": path,
|
||||
"shareType": strconv.Itoa(int(shareType)),
|
||||
"shareWith": shareWith,
|
||||
"publicUpload": strconv.FormatBool(publicUpload),
|
||||
"password": password,
|
||||
"permissions": strconv.Itoa(int(permission)),
|
||||
},
|
||||
}
|
||||
res, err := s.c.baseRequest(http.MethodPost, routes.shares, ro)
|
||||
if err != nil {
|
||||
return types.Share{}, err
|
||||
}
|
||||
var r types.SharesResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data, nil
|
||||
}
|
||||
|
||||
//Delete Remove the given share.
|
||||
func (s *Shares) Delete(shareID int) error {
|
||||
_, err := s.c.baseRequest(http.MethodDelete, routes.shares, nil, strconv.Itoa(shareID))
|
||||
return err
|
||||
}
|
||||
|
||||
// Update update share details
|
||||
// expireDate expireDate expects a well formatted date string, e.g. ‘YYYY-MM-DD’
|
||||
func (s *Shares) Update(shareUpdate types.ShareUpdate) error {
|
||||
errs := make(chan types.UpdateError)
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(4)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := s.UpdatePassword(shareUpdate.ShareID, shareUpdate.Password); err != nil {
|
||||
errs <- types.UpdateError{
|
||||
Field: "password",
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := s.UpdateExpireDate(shareUpdate.ShareID, shareUpdate.ExpireDate); err != nil {
|
||||
errs <- types.UpdateError{
|
||||
Field: "expireDate",
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := s.UpdatePermissions(shareUpdate.ShareID, shareUpdate.Permissions); err != nil {
|
||||
errs <- types.UpdateError{
|
||||
Field: "permissions",
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := s.UpdatePublicUpload(shareUpdate.ShareID, shareUpdate.PublicUpload); err != nil {
|
||||
errs <- types.UpdateError{
|
||||
Field: "publicUpload",
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
}()
|
||||
return types.NewUpdateError(errs)
|
||||
}
|
||||
|
||||
//UpdateExpireDate updates the share's expire date
|
||||
// expireDate expects a well formatted date string, e.g. ‘YYYY-MM-DD’
|
||||
func (s *Shares) UpdateExpireDate(shareID int, expireDate string) error {
|
||||
return s.baseShareUpdate(strconv.Itoa(shareID), "expireDate", expireDate)
|
||||
}
|
||||
|
||||
//UpdatePublicUpload enable or disable public upload
|
||||
func (s *Shares) UpdatePublicUpload(shareID int, public bool) error {
|
||||
return s.baseShareUpdate(strconv.Itoa(shareID), "publicUpload", strconv.FormatBool(public))
|
||||
}
|
||||
|
||||
//UpdatePassword updates share password
|
||||
func (s *Shares) UpdatePassword(shareID int, password string) error {
|
||||
return s.baseShareUpdate(strconv.Itoa(shareID), "password", password)
|
||||
}
|
||||
|
||||
//UpdatePermissions update permissions
|
||||
func (s *Shares) UpdatePermissions(shareID int, permissions types.SharePermission) error {
|
||||
return s.baseShareUpdate(strconv.Itoa(shareID), "permissions", strconv.Itoa(int(permissions)))
|
||||
}
|
||||
|
||||
func (s *Shares) baseShareUpdate(shareID string, key string, value string) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{key: value},
|
||||
}
|
||||
_, err := s.c.baseRequest(http.MethodPut, routes.shares, ro, shareID)
|
||||
return err
|
||||
// Share is a nextcloud share
|
||||
type Share struct {
|
||||
ID string `json:"id"`
|
||||
ShareType int `json:"share_type"`
|
||||
UIDOwner string `json:"uid_owner"`
|
||||
DisplaynameOwner string `json:"displayname_owner"`
|
||||
Permissions int `json:"permissions"`
|
||||
Stime int `json:"stime"`
|
||||
Parent interface{} `json:"parent"`
|
||||
Expiration string `json:"expiration"`
|
||||
Token string `json:"token"`
|
||||
UIDFileOwner string `json:"uid_file_owner"`
|
||||
DisplaynameFileOwner string `json:"displayname_file_owner"`
|
||||
Path string `json:"path"`
|
||||
ItemType string `json:"item_type"`
|
||||
Mimetype string `json:"mimetype"`
|
||||
StorageID string `json:"storage_id"`
|
||||
Storage int `json:"storage"`
|
||||
ItemSource int `json:"item_source"`
|
||||
FileSource int `json:"file_source"`
|
||||
FileParent int `json:"file_parent"`
|
||||
FileTarget string `json:"file_target"`
|
||||
ShareWith string `json:"share_with"`
|
||||
ShareWithDisplayname string `json:"share_with_displayname"`
|
||||
MailSend int `json:"mail_send"`
|
||||
Tags []string `json:"tags"`
|
||||
}
|
||||
|
|
|
@ -0,0 +1,174 @@
|
|||
package gonextcloud
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
req "github.com/levigross/grequests"
|
||||
)
|
||||
|
||||
//shares contains all shares available actions
|
||||
type shares struct {
|
||||
c *client
|
||||
}
|
||||
|
||||
//List list all shares of the logged in user
|
||||
func (s *shares) List() ([]Share, error) {
|
||||
res, err := s.c.baseRequest(http.MethodGet, routes.shares, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r sharesListResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data, nil
|
||||
}
|
||||
|
||||
//GetFromPath return shares from a specific file or folder
|
||||
func (s *shares) GetFromPath(path string, reshares bool, subfiles bool) ([]Share, error) {
|
||||
ro := &req.RequestOptions{
|
||||
Params: map[string]string{
|
||||
"path": path,
|
||||
"reshares": strconv.FormatBool(reshares),
|
||||
"subfiles": strconv.FormatBool(subfiles),
|
||||
},
|
||||
}
|
||||
res, err := s.c.baseRequest(http.MethodGet, routes.shares, ro)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r sharesListResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data, nil
|
||||
}
|
||||
|
||||
//Get information about a known Share
|
||||
func (s *shares) Get(shareID string) (Share, error) {
|
||||
res, err := s.c.baseRequest(http.MethodGet, routes.shares, nil, shareID)
|
||||
if err != nil {
|
||||
return Share{}, err
|
||||
}
|
||||
var r sharesListResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data[0], nil
|
||||
}
|
||||
|
||||
//Create create a share
|
||||
func (s *shares) Create(
|
||||
path string,
|
||||
shareType ShareType,
|
||||
permission SharePermission,
|
||||
shareWith string,
|
||||
publicUpload bool,
|
||||
password string,
|
||||
) (Share, error) {
|
||||
|
||||
if (shareType == UserShare || shareType == GroupShare) && shareWith == "" {
|
||||
return Share{}, fmt.Errorf("shareWith cannot be empty for ShareType UserShare or GroupShare")
|
||||
}
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"path": path,
|
||||
"shareType": strconv.Itoa(int(shareType)),
|
||||
"shareWith": shareWith,
|
||||
"publicUpload": strconv.FormatBool(publicUpload),
|
||||
"password": password,
|
||||
"permissions": strconv.Itoa(int(permission)),
|
||||
},
|
||||
}
|
||||
res, err := s.c.baseRequest(http.MethodPost, routes.shares, ro)
|
||||
if err != nil {
|
||||
return Share{}, err
|
||||
}
|
||||
var r sharesResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data, nil
|
||||
}
|
||||
|
||||
//Delete Remove the given share.
|
||||
func (s *shares) Delete(shareID int) error {
|
||||
_, err := s.c.baseRequest(http.MethodDelete, routes.shares, nil, strconv.Itoa(shareID))
|
||||
return err
|
||||
}
|
||||
|
||||
// Update update share details
|
||||
// expireDate expireDate expects a well formatted date string, e.g. ‘YYYY-MM-DD’
|
||||
func (s *shares) Update(shareUpdate ShareUpdate) error {
|
||||
errs := make(chan *UpdateError)
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(4)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := s.UpdatePassword(shareUpdate.ShareID, shareUpdate.Password); err != nil {
|
||||
errs <- &UpdateError{
|
||||
Field: "password",
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := s.UpdateExpireDate(shareUpdate.ShareID, shareUpdate.ExpireDate); err != nil {
|
||||
errs <- &UpdateError{
|
||||
Field: "expireDate",
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := s.UpdatePermissions(shareUpdate.ShareID, shareUpdate.Permissions); err != nil {
|
||||
errs <- &UpdateError{
|
||||
Field: "permissions",
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := s.UpdatePublicUpload(shareUpdate.ShareID, shareUpdate.PublicUpload); err != nil {
|
||||
errs <- &UpdateError{
|
||||
Field: "publicUpload",
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
}()
|
||||
if err := newUpdateError(errs); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//UpdateExpireDate updates the share's expire date
|
||||
// expireDate expects a well formatted date string, e.g. ‘YYYY-MM-DD’
|
||||
func (s *shares) UpdateExpireDate(shareID int, expireDate string) error {
|
||||
return s.baseShareUpdate(strconv.Itoa(shareID), "expireDate", expireDate)
|
||||
}
|
||||
|
||||
//UpdatePublicUpload enable or disable public upload
|
||||
func (s *shares) UpdatePublicUpload(shareID int, public bool) error {
|
||||
return s.baseShareUpdate(strconv.Itoa(shareID), "publicUpload", strconv.FormatBool(public))
|
||||
}
|
||||
|
||||
//UpdatePassword updates share password
|
||||
func (s *shares) UpdatePassword(shareID int, password string) error {
|
||||
return s.baseShareUpdate(strconv.Itoa(shareID), "password", password)
|
||||
}
|
||||
|
||||
//UpdatePermissions update permissions
|
||||
func (s *shares) UpdatePermissions(shareID int, permissions SharePermission) error {
|
||||
return s.baseShareUpdate(strconv.Itoa(shareID), "permissions", strconv.Itoa(int(permissions)))
|
||||
}
|
||||
|
||||
func (s *shares) baseShareUpdate(shareID string, key string, value string) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{key: value},
|
||||
}
|
||||
_, err := s.c.baseRequest(http.MethodPut, routes.shares, ro, shareID)
|
||||
return err
|
||||
}
|
|
@ -1,59 +0,0 @@
|
|||
package types
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//APIError contains the returned error code and message from the Nextcloud's API
|
||||
type APIError struct {
|
||||
Code int
|
||||
Message string
|
||||
}
|
||||
|
||||
//ErrorFromMeta return a types.APIError from the Response's types.Meta
|
||||
func ErrorFromMeta(meta Meta) *APIError {
|
||||
return &APIError{
|
||||
meta.Statuscode,
|
||||
meta.Message,
|
||||
}
|
||||
}
|
||||
|
||||
//Error return the types.APIError string
|
||||
func (e *APIError) Error() string {
|
||||
return fmt.Sprintf("%d : %s", e.Code, e.Message)
|
||||
}
|
||||
|
||||
//UpdateError contains the user's field and corresponding error
|
||||
type UpdateError struct {
|
||||
Field string
|
||||
Error error
|
||||
}
|
||||
|
||||
//UpdateError contains the errors resulting from a UserUpdate or a UserCreateFull call
|
||||
type UserUpdateError struct {
|
||||
Errors map[string]error
|
||||
}
|
||||
|
||||
func (e *UserUpdateError) Error() string {
|
||||
var errors []string
|
||||
for k, e := range e.Errors {
|
||||
errors = append(errors, fmt.Sprintf("%s: %v", k, e))
|
||||
}
|
||||
return strings.Join(errors, ",")
|
||||
}
|
||||
|
||||
//NewUpdateError returns an UpdateError based on an UpdateError channel
|
||||
func NewUpdateError(errors chan UpdateError) *UserUpdateError {
|
||||
var ue UserUpdateError
|
||||
for e := range errors {
|
||||
if ue.Errors == nil {
|
||||
ue.Errors = map[string]error{e.Field: e.Error}
|
||||
}
|
||||
ue.Errors[e.Field] = e.Error
|
||||
}
|
||||
if len(ue.Errors) > 0 {
|
||||
return &ue
|
||||
}
|
||||
return nil
|
||||
}
|
|
@ -1,57 +0,0 @@
|
|||
package types
|
||||
|
||||
import "strconv"
|
||||
|
||||
type GroupFolderBadFormatIDAndGroups struct {
|
||||
ID string `json:"id"`
|
||||
MountPoint string `json:"mount_point"`
|
||||
Groups map[string]string `json:"groups"`
|
||||
Quota string `json:"quota"`
|
||||
Size int `json:"size"`
|
||||
}
|
||||
|
||||
type GroupFolderBadFormatGroups struct {
|
||||
ID int `json:"id"`
|
||||
MountPoint string `json:"mount_point"`
|
||||
Groups map[string]string `json:"groups"`
|
||||
Quota string `json:"quota"`
|
||||
Size int `json:"size"`
|
||||
}
|
||||
|
||||
type GroupFolder struct {
|
||||
ID int `json:"id"`
|
||||
MountPoint string `json:"mount_point"`
|
||||
Groups map[string]SharePermission `json:"groups"`
|
||||
Quota int `json:"quota"`
|
||||
Size int `json:"size"`
|
||||
}
|
||||
|
||||
func (gf *GroupFolderBadFormatGroups) FormatGroupFolder() GroupFolder {
|
||||
g := GroupFolder{}
|
||||
g.ID = gf.ID
|
||||
g.MountPoint = gf.MountPoint
|
||||
g.Groups = map[string]SharePermission{}
|
||||
for k, v := range gf.Groups {
|
||||
p, _ := strconv.Atoi(v)
|
||||
g.Groups[k] = SharePermission(p)
|
||||
}
|
||||
q, _ := strconv.Atoi(gf.Quota)
|
||||
g.Quota = q
|
||||
g.Size = gf.Size
|
||||
return g
|
||||
}
|
||||
|
||||
func (gf *GroupFolderBadFormatIDAndGroups) FormatGroupFolder() GroupFolder {
|
||||
g := GroupFolder{}
|
||||
g.ID, _ = strconv.Atoi(gf.ID)
|
||||
g.MountPoint = gf.MountPoint
|
||||
g.Groups = map[string]SharePermission{}
|
||||
for k, v := range gf.Groups {
|
||||
p, _ := strconv.Atoi(v)
|
||||
g.Groups[k] = SharePermission(p)
|
||||
}
|
||||
q, _ := strconv.Atoi(gf.Quota)
|
||||
g.Quota = q
|
||||
g.Size = gf.Size
|
||||
return g
|
||||
}
|
|
@ -1,65 +0,0 @@
|
|||
package types
|
||||
|
||||
type System struct {
|
||||
Version string `json:"version"`
|
||||
Theme string `json:"theme"`
|
||||
EnableAvatars string `json:"enable_avatars"`
|
||||
EnablePreviews string `json:"enable_previews"`
|
||||
MemcacheLocal string `json:"memcache.local"`
|
||||
MemcacheDistributed string `json:"memcache.distributed"`
|
||||
FilelockingEnabled string `json:"filelocking.enabled"`
|
||||
MemcacheLocking string `json:"memcache.locking"`
|
||||
Debug string `json:"debug"`
|
||||
Freespace int64 `json:"freespace"`
|
||||
Cpuload []float32 `json:"cpuload"`
|
||||
MemTotal int `json:"mem_total"`
|
||||
MemFree int `json:"mem_free"`
|
||||
SwapTotal int `json:"swap_total"`
|
||||
SwapFree int `json:"swap_free"`
|
||||
}
|
||||
|
||||
type Monitoring struct {
|
||||
Nextcloud struct {
|
||||
System System `json:"system"`
|
||||
Storage Storage `json:"storage"`
|
||||
Shares struct {
|
||||
NumShares int `json:"num_shares"`
|
||||
NumSharesUser int `json:"num_shares_user"`
|
||||
NumSharesGroups int `json:"num_shares_groups"`
|
||||
NumSharesLink int `json:"num_shares_link"`
|
||||
NumSharesLinkNoPassword int `json:"num_shares_link_no_password"`
|
||||
NumFedSharesSent int `json:"num_fed_shares_sent"`
|
||||
NumFedSharesReceived int `json:"num_fed_shares_received"`
|
||||
} `json:"shares"`
|
||||
} `json:"nextcloud"`
|
||||
Server struct {
|
||||
Webserver string `json:"webserver"`
|
||||
Php struct {
|
||||
Version string `json:"version"`
|
||||
MemoryLimit int `json:"memory_limit"`
|
||||
MaxExecutionTime int `json:"max_execution_time"`
|
||||
UploadMaxFilesize int `json:"upload_max_filesize"`
|
||||
} `json:"php"`
|
||||
Database struct {
|
||||
Type string `json:"type"`
|
||||
Version string `json:"version"`
|
||||
Size int `json:"size"`
|
||||
} `json:"database"`
|
||||
} `json:"server"`
|
||||
ActiveUsers ActiveUsers `json:"activeUsers"`
|
||||
}
|
||||
|
||||
type ActiveUsers struct {
|
||||
Last5Minutes int `json:"last5minutes"`
|
||||
Last1Hour int `json:"last1hour"`
|
||||
Last24Hours int `json:"last24hours"`
|
||||
}
|
||||
|
||||
type Storage struct {
|
||||
NumUsers int `json:"num_users"`
|
||||
NumFiles int `json:"num_files"`
|
||||
NumStorages int `json:"num_storages"`
|
||||
NumStoragesLocal int `json:"num_storages_local"`
|
||||
NumStoragesHome int `json:"num_storages_home"`
|
||||
NumStoragesOther int `json:"num_storages_other"`
|
||||
}
|
|
@ -1,53 +0,0 @@
|
|||
package types
|
||||
|
||||
type ShareType int
|
||||
type SharePermission int
|
||||
|
||||
const (
|
||||
UserShare ShareType = 0
|
||||
GroupShare ShareType = 1
|
||||
PublicLinkShare ShareType = 3
|
||||
FederatedCloudShare ShareType = 6
|
||||
|
||||
ReadPermission SharePermission = 1
|
||||
UpdatePermission SharePermission = 2
|
||||
CreatePermission SharePermission = 4
|
||||
DeletePermission SharePermission = 8
|
||||
ReSharePermission SharePermission = 16
|
||||
AllPermissions SharePermission = 31
|
||||
)
|
||||
|
||||
type ShareUpdate struct {
|
||||
ShareID int
|
||||
Permissions SharePermission
|
||||
Password string
|
||||
PublicUpload bool
|
||||
ExpireDate string
|
||||
}
|
||||
|
||||
type Share struct {
|
||||
ID string `json:"id"`
|
||||
ShareType int `json:"share_type"`
|
||||
UIDOwner string `json:"uid_owner"`
|
||||
DisplaynameOwner string `json:"displayname_owner"`
|
||||
Permissions int `json:"permissions"`
|
||||
Stime int `json:"stime"`
|
||||
Parent interface{} `json:"parent"`
|
||||
Expiration string `json:"expiration"`
|
||||
Token string `json:"token"`
|
||||
UIDFileOwner string `json:"uid_file_owner"`
|
||||
DisplaynameFileOwner string `json:"displayname_file_owner"`
|
||||
Path string `json:"path"`
|
||||
ItemType string `json:"item_type"`
|
||||
Mimetype string `json:"mimetype"`
|
||||
StorageID string `json:"storage_id"`
|
||||
Storage int `json:"storage"`
|
||||
ItemSource int `json:"item_source"`
|
||||
FileSource int `json:"file_source"`
|
||||
FileParent int `json:"file_parent"`
|
||||
FileTarget string `json:"file_target"`
|
||||
ShareWith string `json:"share_with"`
|
||||
ShareWithDisplayname string `json:"share_with_displayname"`
|
||||
MailSend int `json:"mail_send"`
|
||||
Tags []string `json:"tags"`
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
package gonextcloud
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/structs"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestUserUpdate(t *testing.T) {
|
||||
if err := initClient(); err != nil {
|
||||
return
|
||||
}
|
||||
username := fmt.Sprintf("%s-2", config.NotExistingUser)
|
||||
err := c.Users().Create(username, password, nil)
|
||||
if err != nil {
|
||||
t.FailNow()
|
||||
}
|
||||
err = c.Groups().Create(config.NotExistingGroup)
|
||||
if err != nil {
|
||||
t.FailNow()
|
||||
}
|
||||
user := &UserDetails{
|
||||
ID: username,
|
||||
Displayname: strings.ToUpper(username),
|
||||
Email: "some@mail.com",
|
||||
Quota: Quota{
|
||||
// Unlimited
|
||||
Quota: -3,
|
||||
},
|
||||
Groups: []string{config.NotExistingGroup},
|
||||
}
|
||||
s := time.Now()
|
||||
err = c.Users().Update(user)
|
||||
e := time.Now().Sub(s)
|
||||
fmt.Println(e.String())
|
||||
assert.NoError(t, err)
|
||||
u, err := c.Users().Get(username)
|
||||
assert.NoError(t, err)
|
||||
o := structs.Map(user)
|
||||
r := structs.Map(u)
|
||||
for k := range o {
|
||||
if ignoredUserField(k) {
|
||||
continue
|
||||
}
|
||||
assert.Equal(t, o[k], r[k])
|
||||
}
|
||||
// Clean up
|
||||
err = c.Users().Delete(username)
|
||||
assert.NoError(t, err)
|
||||
err = c.Groups().Delete(config.NotExistingGroup)
|
||||
assert.NoError(t, err)
|
||||
|
||||
}
|
|
@ -1,6 +1,8 @@
|
|||
package types
|
||||
package gonextcloud
|
||||
|
||||
//User encapsulate the data needed to create a new Nextcloud's User
|
||||
import "strconv"
|
||||
|
||||
// User encapsulate the data needed to create a new Nextcloud's User
|
||||
type User struct {
|
||||
Username string
|
||||
Email string
|
||||
|
@ -10,7 +12,7 @@ type User struct {
|
|||
Groups []string
|
||||
}
|
||||
|
||||
//UserDetails is the raw Nextcloud User response
|
||||
// UserDetails is the raw Nextcloud User response
|
||||
type UserDetails struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ID string `json:"id"`
|
||||
|
@ -31,10 +33,18 @@ type UserDetails struct {
|
|||
Locale string `json:"locale,omitempty"`
|
||||
}
|
||||
|
||||
// Quota is a use storage Quota
|
||||
type Quota struct {
|
||||
Free int64 `json:"free"`
|
||||
Used int `json:"used"`
|
||||
Used int64 `json:"used"`
|
||||
Total int64 `json:"total"`
|
||||
Relative float64 `json:"relative"`
|
||||
Quota int `json:"quota"`
|
||||
Quota int64 `json:"quota"`
|
||||
}
|
||||
|
||||
func (q *Quota) String() string {
|
||||
if q.Quota < 0 {
|
||||
return "none"
|
||||
}
|
||||
return strconv.FormatInt(q.Quota, 10)
|
||||
}
|
|
@ -2,58 +2,56 @@ package gonextcloud
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/fatih/structs"
|
||||
req "github.com/levigross/grequests"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/sirupsen/logrus"
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
req "github.com/levigross/grequests"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
//Users contains all Users available actions
|
||||
type Users struct {
|
||||
c *Client
|
||||
//users contains all users available actions
|
||||
type users struct {
|
||||
c *client
|
||||
}
|
||||
|
||||
// List return the Nextcloud'user list
|
||||
func (u *Users) List() ([]string, error) {
|
||||
func (u *users) List() ([]string, error) {
|
||||
res, err := u.c.baseRequest(http.MethodGet, routes.users, nil)
|
||||
//res, err := c.session.Get(u.String(), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.UserListResponse
|
||||
var r userListResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data.Users, nil
|
||||
}
|
||||
|
||||
//ListDetails return a map of user with details
|
||||
func (u *Users) ListDetails() (map[string]types.UserDetails, error) {
|
||||
func (u *users) ListDetails() (map[string]UserDetails, error) {
|
||||
res, err := u.c.baseRequest(http.MethodGet, routes.users, nil, "details")
|
||||
//res, err := c.session.Get(u.String(), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.UserListDetailsResponse
|
||||
var r userListDetailsResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data.Users, nil
|
||||
}
|
||||
|
||||
// Get return the details about the specified user
|
||||
func (u *Users) Get(name string) (*types.UserDetails, error) {
|
||||
func (u *users) Get(name string) (*UserDetails, error) {
|
||||
if name == "" {
|
||||
return nil, &types.APIError{Message: "name cannot be empty"}
|
||||
return nil, &APIError{Message: "name cannot be empty"}
|
||||
}
|
||||
res, err := u.c.baseRequest(http.MethodGet, routes.users, nil, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.UserResponse
|
||||
var r userResponse
|
||||
js := res.String()
|
||||
// Nextcloud does not encode JSON properly
|
||||
js = reformatJSON(js)
|
||||
|
@ -64,7 +62,7 @@ func (u *Users) Get(name string) (*types.UserDetails, error) {
|
|||
}
|
||||
|
||||
// Search returns the users whose name match the search string
|
||||
func (u *Users) Search(search string) ([]string, error) {
|
||||
func (u *users) Search(search string) ([]string, error) {
|
||||
ro := &req.RequestOptions{
|
||||
Params: map[string]string{"search": search},
|
||||
}
|
||||
|
@ -72,14 +70,14 @@ func (u *Users) Search(search string) ([]string, error) {
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.UserListResponse
|
||||
var r userListResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data.Users, nil
|
||||
}
|
||||
|
||||
// Create create a new user
|
||||
func (u *Users) Create(username string, password string, user *types.UserDetails) error {
|
||||
// Create base Users
|
||||
func (u *users) Create(username string, password string, user *UserDetails) error {
|
||||
// Create base users
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"userid": username,
|
||||
|
@ -99,7 +97,7 @@ func (u *Users) Create(username string, password string, user *types.UserDetails
|
|||
|
||||
// CreateWithoutPassword create a user without provisioning a password, the email address must be provided to send
|
||||
// an init password email
|
||||
func (u *Users) CreateWithoutPassword(username, email, displayName, quota, language string, groups ...string) error {
|
||||
func (u *users) CreateWithoutPassword(username, email, displayName, quota, language string, groups ...string) error {
|
||||
if u.c.version.Major < 14 {
|
||||
return errors.New("unsupported method: requires Nextcloud 14+")
|
||||
}
|
||||
|
@ -134,12 +132,12 @@ func (u *Users) CreateWithoutPassword(username, email, displayName, quota, langu
|
|||
}
|
||||
|
||||
//CreateBatchWithoutPassword create multiple users and send them the init password email
|
||||
func (u *Users) CreateBatchWithoutPassword(users []types.User) error {
|
||||
func (u *users) CreateBatchWithoutPassword(users []User) error {
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error)
|
||||
for _, us := range users {
|
||||
wg.Add(1)
|
||||
go func(user types.User) {
|
||||
go func(user User) {
|
||||
logrus.Debugf("creating user %s", user.Username)
|
||||
defer wg.Done()
|
||||
if err := u.CreateWithoutPassword(
|
||||
|
@ -164,12 +162,12 @@ func (u *Users) CreateBatchWithoutPassword(users []types.User) error {
|
|||
}
|
||||
|
||||
//Delete delete the user
|
||||
func (u *Users) Delete(name string) error {
|
||||
func (u *users) Delete(name string) error {
|
||||
return u.baseRequest(http.MethodDelete, nil, name)
|
||||
}
|
||||
|
||||
//Enable enables the user
|
||||
func (u *Users) Enable(name string) error {
|
||||
func (u *users) Enable(name string) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{},
|
||||
}
|
||||
|
@ -177,7 +175,7 @@ func (u *Users) Enable(name string) error {
|
|||
}
|
||||
|
||||
//Disable disables the user
|
||||
func (u *Users) Disable(name string) error {
|
||||
func (u *users) Disable(name string) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{},
|
||||
}
|
||||
|
@ -185,89 +183,173 @@ func (u *Users) Disable(name string) error {
|
|||
}
|
||||
|
||||
//SendWelcomeEmail (re)send the welcome mail to the user (return an error if the user has not configured his email)
|
||||
func (u *Users) SendWelcomeEmail(name string) error {
|
||||
func (u *users) SendWelcomeEmail(name string) error {
|
||||
return u.baseRequest(http.MethodPost, nil, name, "welcome")
|
||||
}
|
||||
|
||||
//Update takes a *types.Users struct to update the user's information
|
||||
func (u *Users) Update(user *types.UserDetails) error {
|
||||
m := structs.Map(user)
|
||||
errs := make(chan types.UpdateError)
|
||||
//Update takes a *types.users struct to update the user's information
|
||||
// Updatable fields: Email, Displayname, Phone, Address, Website, Twitter, Quota, groups
|
||||
func (u *users) Update(user *UserDetails) error {
|
||||
// Get user to update only modified fields
|
||||
original, err := u.Get(user.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
errs := make(chan *UpdateError)
|
||||
var wg sync.WaitGroup
|
||||
for k := range m {
|
||||
if !ignoredUserField(k) && m[k].(string) != "" {
|
||||
update := func(key string, value string) {
|
||||
defer wg.Done()
|
||||
if err := u.updateAttribute(user.ID, strings.ToLower(key), value); err != nil {
|
||||
errs <- &UpdateError{
|
||||
Field: key,
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
errs <- nil
|
||||
}
|
||||
// Email
|
||||
if user.Email != original.Email {
|
||||
wg.Add(1)
|
||||
go update("Email", user.Email)
|
||||
}
|
||||
// Displayname
|
||||
if user.Displayname != original.Displayname {
|
||||
wg.Add(1)
|
||||
go update("Displayname", user.Displayname)
|
||||
}
|
||||
// Phone
|
||||
if user.Phone != original.Phone {
|
||||
wg.Add(1)
|
||||
go update("Phone", user.Phone)
|
||||
}
|
||||
// Address
|
||||
if user.Address != original.Address {
|
||||
wg.Add(1)
|
||||
go update("Address", user.Address)
|
||||
}
|
||||
// Website
|
||||
if user.Website != original.Website {
|
||||
wg.Add(1)
|
||||
go update("Website", user.Website)
|
||||
}
|
||||
// Twitter
|
||||
if user.Twitter != original.Twitter {
|
||||
wg.Add(1)
|
||||
go update("Twitter", user.Twitter)
|
||||
}
|
||||
// Quota
|
||||
if user.Quota.Quota != original.Quota.Quota {
|
||||
var value string
|
||||
// If empty
|
||||
if user.Quota == (Quota{}) {
|
||||
value = "default"
|
||||
} else {
|
||||
value = user.Quota.String()
|
||||
}
|
||||
wg.Add(1)
|
||||
go update("Quota", value)
|
||||
}
|
||||
// groups
|
||||
// Group removed
|
||||
for _, g := range original.Groups {
|
||||
if !contains(user.Groups, g) {
|
||||
wg.Add(1)
|
||||
go func(key string, value string) {
|
||||
go func(gr string) {
|
||||
defer wg.Done()
|
||||
if err := u.updateAttribute(user.ID, strings.ToLower(key), value); err != nil {
|
||||
errs <- types.UpdateError{
|
||||
Field: key,
|
||||
if err := u.GroupRemove(user.ID, gr); err != nil {
|
||||
errs <- &UpdateError{
|
||||
Field: "groups/" + gr,
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
}(k, m[k].(string))
|
||||
errs <- nil
|
||||
}(g)
|
||||
}
|
||||
}
|
||||
|
||||
// Group Added
|
||||
for _, g := range user.Groups {
|
||||
if !contains(original.Groups, g) {
|
||||
wg.Add(1)
|
||||
go func(gr string) {
|
||||
defer wg.Done()
|
||||
if err := u.GroupAdd(user.ID, gr); err != nil {
|
||||
errs <- &UpdateError{
|
||||
Field: "groups/" + gr,
|
||||
Error: err,
|
||||
}
|
||||
}
|
||||
errs <- nil
|
||||
}(g)
|
||||
}
|
||||
}
|
||||
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
}()
|
||||
return types.NewUpdateError(errs)
|
||||
// Warning : we actually need to check the *err
|
||||
if err := newUpdateError(errs); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//UpdateEmail update the user's email
|
||||
func (u *Users) UpdateEmail(name string, email string) error {
|
||||
func (u *users) UpdateEmail(name string, email string) error {
|
||||
return u.updateAttribute(name, "email", email)
|
||||
}
|
||||
|
||||
//UpdateDisplayName update the user's display name
|
||||
func (u *Users) UpdateDisplayName(name string, displayName string) error {
|
||||
func (u *users) UpdateDisplayName(name string, displayName string) error {
|
||||
return u.updateAttribute(name, "displayname", displayName)
|
||||
}
|
||||
|
||||
//UpdatePhone update the user's phone
|
||||
func (u *Users) UpdatePhone(name string, phone string) error {
|
||||
func (u *users) UpdatePhone(name string, phone string) error {
|
||||
return u.updateAttribute(name, "phone", phone)
|
||||
}
|
||||
|
||||
//UpdateAddress update the user's address
|
||||
func (u *Users) UpdateAddress(name string, address string) error {
|
||||
func (u *users) UpdateAddress(name string, address string) error {
|
||||
return u.updateAttribute(name, "address", address)
|
||||
}
|
||||
|
||||
//UpdateWebSite update the user's website
|
||||
func (u *Users) UpdateWebSite(name string, website string) error {
|
||||
func (u *users) UpdateWebSite(name string, website string) error {
|
||||
return u.updateAttribute(name, "website", website)
|
||||
}
|
||||
|
||||
//UpdateTwitter update the user's twitter
|
||||
func (u *Users) UpdateTwitter(name string, twitter string) error {
|
||||
func (u *users) UpdateTwitter(name string, twitter string) error {
|
||||
return u.updateAttribute(name, "twitter", twitter)
|
||||
}
|
||||
|
||||
//UpdatePassword update the user's password
|
||||
func (u *Users) UpdatePassword(name string, password string) error {
|
||||
func (u *users) UpdatePassword(name string, password string) error {
|
||||
return u.updateAttribute(name, "password", password)
|
||||
}
|
||||
|
||||
//UpdateQuota update the user's quota (bytes)
|
||||
func (u *Users) UpdateQuota(name string, quota int) error {
|
||||
return u.updateAttribute(name, "quota", strconv.Itoa(quota))
|
||||
//UpdateQuota update the user's quota (bytes). Set negative quota for unlimited
|
||||
func (u *users) UpdateQuota(name string, quota int64) error {
|
||||
q := Quota{Quota: quota}
|
||||
return u.updateAttribute(name, "quota", q.String())
|
||||
}
|
||||
|
||||
//GroupList lists the user's groups
|
||||
func (u *Users) GroupList(name string) ([]string, error) {
|
||||
func (u *users) GroupList(name string) ([]string, error) {
|
||||
res, err := u.c.baseRequest(http.MethodGet, routes.users, nil, name, "groups")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.GroupListResponse
|
||||
var r groupListResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data.Groups, nil
|
||||
}
|
||||
|
||||
//GroupAdd adds a the user to the group
|
||||
func (u *Users) GroupAdd(name string, group string) error {
|
||||
func (u *users) GroupAdd(name string, group string) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"groupid": group,
|
||||
|
@ -277,7 +359,7 @@ func (u *Users) GroupAdd(name string, group string) error {
|
|||
}
|
||||
|
||||
//GroupRemove removes the user from the group
|
||||
func (u *Users) GroupRemove(name string, group string) error {
|
||||
func (u *users) GroupRemove(name string, group string) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"groupid": group,
|
||||
|
@ -287,7 +369,7 @@ func (u *Users) GroupRemove(name string, group string) error {
|
|||
}
|
||||
|
||||
//GroupPromote promotes the user as group admin
|
||||
func (u *Users) GroupPromote(name string, group string) error {
|
||||
func (u *users) GroupPromote(name string, group string) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"groupid": group,
|
||||
|
@ -297,7 +379,7 @@ func (u *Users) GroupPromote(name string, group string) error {
|
|||
}
|
||||
|
||||
//GroupDemote demotes the user
|
||||
func (u *Users) GroupDemote(name string, group string) error {
|
||||
func (u *users) GroupDemote(name string, group string) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"groupid": group,
|
||||
|
@ -307,7 +389,7 @@ func (u *Users) GroupDemote(name string, group string) error {
|
|||
}
|
||||
|
||||
//GroupSubAdminList lists the groups where he is subadmin
|
||||
func (u *Users) GroupSubAdminList(name string) ([]string, error) {
|
||||
func (u *users) GroupSubAdminList(name string) ([]string, error) {
|
||||
if !u.c.loggedIn() {
|
||||
return nil, errUnauthorized
|
||||
}
|
||||
|
@ -317,12 +399,12 @@ func (u *Users) GroupSubAdminList(name string) ([]string, error) {
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var r types.BaseResponse
|
||||
var r baseResponse
|
||||
res.JSON(&r)
|
||||
return r.Ocs.Data, nil
|
||||
}
|
||||
|
||||
func (u *Users) updateAttribute(name string, key string, value string) error {
|
||||
func (u *users) updateAttribute(name string, key string, value string) error {
|
||||
ro := &req.RequestOptions{
|
||||
Data: map[string]string{
|
||||
"key": key,
|
||||
|
@ -332,15 +414,24 @@ func (u *Users) updateAttribute(name string, key string, value string) error {
|
|||
return u.baseRequest(http.MethodPut, ro, name)
|
||||
}
|
||||
|
||||
func (u *Users) baseRequest(method string, ro *req.RequestOptions, subRoutes ...string) error {
|
||||
func (u *users) baseRequest(method string, ro *req.RequestOptions, subRoutes ...string) error {
|
||||
_, err := u.c.baseRequest(method, routes.users, ro, subRoutes...)
|
||||
return err
|
||||
}
|
||||
|
||||
func ignoredUserField(key string) bool {
|
||||
keys := []string{"ID", "Quota", "Enabled", "Groups", "Language"}
|
||||
keys := []string{"Email", "Displayname", "Phone", "Address", "Website", "Twitter", "Quota", "groups"}
|
||||
for _, k := range keys {
|
||||
if key == k {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func contains(slice []string, e string) bool {
|
||||
for _, s := range slice {
|
||||
if e == s {
|
||||
return true
|
||||
}
|
||||
}
|
12
utils.go
12
utils.go
|
@ -2,15 +2,15 @@ package gonextcloud
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
req "github.com/levigross/grequests"
|
||||
"gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
req "github.com/levigross/grequests"
|
||||
)
|
||||
|
||||
func (c *Client) baseRequest(method string, route *url.URL, ro *req.RequestOptions, subRoutes ...string) (*req.Response, error) {
|
||||
func (c *client) baseRequest(method string, route *url.URL, ro *req.RequestOptions, subRoutes ...string) (*req.Response, error) {
|
||||
if !c.loggedIn() {
|
||||
return nil, errUnauthorized
|
||||
}
|
||||
|
@ -40,12 +40,12 @@ func (c *Client) baseRequest(method string, route *url.URL, ro *req.RequestOptio
|
|||
}
|
||||
// As we cannot read the ReaderCloser twice, we use the string content
|
||||
js := res.String()
|
||||
var r types.BaseResponse
|
||||
var r baseResponse
|
||||
json.Unmarshal([]byte(js), &r)
|
||||
if r.Ocs.Meta.Statuscode == 200 || r.Ocs.Meta.Statuscode == 100 {
|
||||
return res, nil
|
||||
}
|
||||
err = types.ErrorFromMeta(r.Ocs.Meta)
|
||||
err = errorFromMeta(r.Ocs.Meta)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
@ -55,5 +55,7 @@ func reformatJSON(json string) string {
|
|||
json = strings.Replace(json, "\"false\"", "false", -1)
|
||||
// Nextcloud encode quota as an empty array for never connected users
|
||||
json = strings.Replace(json, "\"quota\":[],", "", -1)
|
||||
// Nextcloud send admin unlimited quota as -3, others as "none" : replace with negative value
|
||||
json = strings.Replace(json, "\"quota\":\"none\"", "\"quota\":-3", -1)
|
||||
return json
|
||||
}
|
||||
|
|
|
@ -2,7 +2,7 @@ ISC License
|
|||
|
||||
Copyright (c) 2012-2016 Dave Collins <dave@davec.name>
|
||||
|
||||
Permission to use, copy, modify, and distribute this software for any
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
|
|
|
@ -16,7 +16,9 @@
|
|||
// when the code is not running on Google App Engine, compiled by GopherJS, and
|
||||
// "-tags safe" is not added to the go build command line. The "disableunsafe"
|
||||
// tag is deprecated and thus should not be used.
|
||||
// +build !js,!appengine,!safe,!disableunsafe
|
||||
// Go versions prior to 1.4 are disabled because they use a different layout
|
||||
// for interfaces which make the implementation of unsafeReflectValue more complex.
|
||||
// +build !js,!appengine,!safe,!disableunsafe,go1.4
|
||||
|
||||
package spew
|
||||
|
||||
|
@ -34,80 +36,49 @@ const (
|
|||
ptrSize = unsafe.Sizeof((*byte)(nil))
|
||||
)
|
||||
|
||||
var (
|
||||
// offsetPtr, offsetScalar, and offsetFlag are the offsets for the
|
||||
// internal reflect.Value fields. These values are valid before golang
|
||||
// commit ecccf07e7f9d which changed the format. The are also valid
|
||||
// after commit 82f48826c6c7 which changed the format again to mirror
|
||||
// the original format. Code in the init function updates these offsets
|
||||
// as necessary.
|
||||
offsetPtr = uintptr(ptrSize)
|
||||
offsetScalar = uintptr(0)
|
||||
offsetFlag = uintptr(ptrSize * 2)
|
||||
type flag uintptr
|
||||
|
||||
// flagKindWidth and flagKindShift indicate various bits that the
|
||||
// reflect package uses internally to track kind information.
|
||||
//
|
||||
// flagRO indicates whether or not the value field of a reflect.Value is
|
||||
// read-only.
|
||||
//
|
||||
// flagIndir indicates whether the value field of a reflect.Value is
|
||||
// the actual data or a pointer to the data.
|
||||
//
|
||||
// These values are valid before golang commit 90a7c3c86944 which
|
||||
// changed their positions. Code in the init function updates these
|
||||
// flags as necessary.
|
||||
flagKindWidth = uintptr(5)
|
||||
flagKindShift = uintptr(flagKindWidth - 1)
|
||||
flagRO = uintptr(1 << 0)
|
||||
flagIndir = uintptr(1 << 1)
|
||||
var (
|
||||
// flagRO indicates whether the value field of a reflect.Value
|
||||
// is read-only.
|
||||
flagRO flag
|
||||
|
||||
// flagAddr indicates whether the address of the reflect.Value's
|
||||
// value may be taken.
|
||||
flagAddr flag
|
||||
)
|
||||
|
||||
func init() {
|
||||
// Older versions of reflect.Value stored small integers directly in the
|
||||
// ptr field (which is named val in the older versions). Versions
|
||||
// between commits ecccf07e7f9d and 82f48826c6c7 added a new field named
|
||||
// scalar for this purpose which unfortunately came before the flag
|
||||
// field, so the offset of the flag field is different for those
|
||||
// versions.
|
||||
//
|
||||
// This code constructs a new reflect.Value from a known small integer
|
||||
// and checks if the size of the reflect.Value struct indicates it has
|
||||
// the scalar field. When it does, the offsets are updated accordingly.
|
||||
vv := reflect.ValueOf(0xf00)
|
||||
if unsafe.Sizeof(vv) == (ptrSize * 4) {
|
||||
offsetScalar = ptrSize * 2
|
||||
offsetFlag = ptrSize * 3
|
||||
}
|
||||
// flagKindMask holds the bits that make up the kind
|
||||
// part of the flags field. In all the supported versions,
|
||||
// it is in the lower 5 bits.
|
||||
const flagKindMask = flag(0x1f)
|
||||
|
||||
// Commit 90a7c3c86944 changed the flag positions such that the low
|
||||
// order bits are the kind. This code extracts the kind from the flags
|
||||
// field and ensures it's the correct type. When it's not, the flag
|
||||
// order has been changed to the newer format, so the flags are updated
|
||||
// accordingly.
|
||||
upf := unsafe.Pointer(uintptr(unsafe.Pointer(&vv)) + offsetFlag)
|
||||
upfv := *(*uintptr)(upf)
|
||||
flagKindMask := uintptr((1<<flagKindWidth - 1) << flagKindShift)
|
||||
if (upfv&flagKindMask)>>flagKindShift != uintptr(reflect.Int) {
|
||||
flagKindShift = 0
|
||||
flagRO = 1 << 5
|
||||
flagIndir = 1 << 6
|
||||
// Different versions of Go have used different
|
||||
// bit layouts for the flags type. This table
|
||||
// records the known combinations.
|
||||
var okFlags = []struct {
|
||||
ro, addr flag
|
||||
}{{
|
||||
// From Go 1.4 to 1.5
|
||||
ro: 1 << 5,
|
||||
addr: 1 << 7,
|
||||
}, {
|
||||
// Up to Go tip.
|
||||
ro: 1<<5 | 1<<6,
|
||||
addr: 1 << 8,
|
||||
}}
|
||||
|
||||
// Commit adf9b30e5594 modified the flags to separate the
|
||||
// flagRO flag into two bits which specifies whether or not the
|
||||
// field is embedded. This causes flagIndir to move over a bit
|
||||
// and means that flagRO is the combination of either of the
|
||||
// original flagRO bit and the new bit.
|
||||
//
|
||||
// This code detects the change by extracting what used to be
|
||||
// the indirect bit to ensure it's set. When it's not, the flag
|
||||
// order has been changed to the newer format, so the flags are
|
||||
// updated accordingly.
|
||||
if upfv&flagIndir == 0 {
|
||||
flagRO = 3 << 5
|
||||
flagIndir = 1 << 7
|
||||
}
|
||||
var flagValOffset = func() uintptr {
|
||||
field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag")
|
||||
if !ok {
|
||||
panic("reflect.Value has no flag field")
|
||||
}
|
||||
return field.Offset
|
||||
}()
|
||||
|
||||
// flagField returns a pointer to the flag field of a reflect.Value.
|
||||
func flagField(v *reflect.Value) *flag {
|
||||
return (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagValOffset))
|
||||
}
|
||||
|
||||
// unsafeReflectValue converts the passed reflect.Value into a one that bypasses
|
||||
|
@ -119,34 +90,56 @@ func init() {
|
|||
// This allows us to check for implementations of the Stringer and error
|
||||
// interfaces to be used for pretty printing ordinarily unaddressable and
|
||||
// inaccessible values such as unexported struct fields.
|
||||
func unsafeReflectValue(v reflect.Value) (rv reflect.Value) {
|
||||
indirects := 1
|
||||
vt := v.Type()
|
||||
upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr)
|
||||
rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag))
|
||||
if rvf&flagIndir != 0 {
|
||||
vt = reflect.PtrTo(v.Type())
|
||||
indirects++
|
||||
} else if offsetScalar != 0 {
|
||||
// The value is in the scalar field when it's not one of the
|
||||
// reference types.
|
||||
switch vt.Kind() {
|
||||
case reflect.Uintptr:
|
||||
case reflect.Chan:
|
||||
case reflect.Func:
|
||||
case reflect.Map:
|
||||
case reflect.Ptr:
|
||||
case reflect.UnsafePointer:
|
||||
default:
|
||||
upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) +
|
||||
offsetScalar)
|
||||
func unsafeReflectValue(v reflect.Value) reflect.Value {
|
||||
if !v.IsValid() || (v.CanInterface() && v.CanAddr()) {
|
||||
return v
|
||||
}
|
||||
flagFieldPtr := flagField(&v)
|
||||
*flagFieldPtr &^= flagRO
|
||||
*flagFieldPtr |= flagAddr
|
||||
return v
|
||||
}
|
||||
|
||||
// Sanity checks against future reflect package changes
|
||||
// to the type or semantics of the Value.flag field.
|
||||
func init() {
|
||||
field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag")
|
||||
if !ok {
|
||||
panic("reflect.Value has no flag field")
|
||||
}
|
||||
if field.Type.Kind() != reflect.TypeOf(flag(0)).Kind() {
|
||||
panic("reflect.Value flag field has changed kind")
|
||||
}
|
||||
type t0 int
|
||||
var t struct {
|
||||
A t0
|
||||
// t0 will have flagEmbedRO set.
|
||||
t0
|
||||
// a will have flagStickyRO set
|
||||
a t0
|
||||
}
|
||||
vA := reflect.ValueOf(t).FieldByName("A")
|
||||
va := reflect.ValueOf(t).FieldByName("a")
|
||||
vt0 := reflect.ValueOf(t).FieldByName("t0")
|
||||
|
||||
// Infer flagRO from the difference between the flags
|
||||
// for the (otherwise identical) fields in t.
|
||||
flagPublic := *flagField(&vA)
|
||||
flagWithRO := *flagField(&va) | *flagField(&vt0)
|
||||
flagRO = flagPublic ^ flagWithRO
|
||||
|
||||
// Infer flagAddr from the difference between a value
|
||||
// taken from a pointer and not.
|
||||
vPtrA := reflect.ValueOf(&t).Elem().FieldByName("A")
|
||||
flagNoPtr := *flagField(&vA)
|
||||
flagPtr := *flagField(&vPtrA)
|
||||
flagAddr = flagNoPtr ^ flagPtr
|
||||
|
||||
// Check that the inferred flags tally with one of the known versions.
|
||||
for _, f := range okFlags {
|
||||
if flagRO == f.ro && flagAddr == f.addr {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
pv := reflect.NewAt(vt, upv)
|
||||
rv = pv
|
||||
for i := 0; i < indirects; i++ {
|
||||
rv = rv.Elem()
|
||||
}
|
||||
return rv
|
||||
panic("reflect.Value read-only flag has changed semantics")
|
||||
}
|
||||
|
|
|
@ -16,7 +16,7 @@
|
|||
// when the code is running on Google App Engine, compiled by GopherJS, or
|
||||
// "-tags safe" is added to the go build command line. The "disableunsafe"
|
||||
// tag is deprecated and thus should not be used.
|
||||
// +build js appengine safe disableunsafe
|
||||
// +build js appengine safe disableunsafe !go1.4
|
||||
|
||||
package spew
|
||||
|
||||
|
|
|
@ -180,7 +180,7 @@ func printComplex(w io.Writer, c complex128, floatPrecision int) {
|
|||
w.Write(closeParenBytes)
|
||||
}
|
||||
|
||||
// printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x'
|
||||
// printHexPtr outputs a uintptr formatted as hexadecimal with a leading '0x'
|
||||
// prefix to Writer w.
|
||||
func printHexPtr(w io.Writer, p uintptr) {
|
||||
// Null pointer.
|
||||
|
|
|
@ -35,16 +35,16 @@ var (
|
|||
|
||||
// cCharRE is a regular expression that matches a cgo char.
|
||||
// It is used to detect character arrays to hexdump them.
|
||||
cCharRE = regexp.MustCompile("^.*\\._Ctype_char$")
|
||||
cCharRE = regexp.MustCompile(`^.*\._Ctype_char$`)
|
||||
|
||||
// cUnsignedCharRE is a regular expression that matches a cgo unsigned
|
||||
// char. It is used to detect unsigned character arrays to hexdump
|
||||
// them.
|
||||
cUnsignedCharRE = regexp.MustCompile("^.*\\._Ctype_unsignedchar$")
|
||||
cUnsignedCharRE = regexp.MustCompile(`^.*\._Ctype_unsignedchar$`)
|
||||
|
||||
// cUint8tCharRE is a regular expression that matches a cgo uint8_t.
|
||||
// It is used to detect uint8_t arrays to hexdump them.
|
||||
cUint8tCharRE = regexp.MustCompile("^.*\\._Ctype_uint8_t$")
|
||||
cUint8tCharRE = regexp.MustCompile(`^.*\._Ctype_uint8_t$`)
|
||||
)
|
||||
|
||||
// dumpState contains information about the state of a dump operation.
|
||||
|
@ -143,10 +143,10 @@ func (d *dumpState) dumpPtr(v reflect.Value) {
|
|||
// Display dereferenced value.
|
||||
d.w.Write(openParenBytes)
|
||||
switch {
|
||||
case nilFound == true:
|
||||
case nilFound:
|
||||
d.w.Write(nilAngleBytes)
|
||||
|
||||
case cycleFound == true:
|
||||
case cycleFound:
|
||||
d.w.Write(circularBytes)
|
||||
|
||||
default:
|
||||
|
|
|
@ -182,10 +182,10 @@ func (f *formatState) formatPtr(v reflect.Value) {
|
|||
|
||||
// Display dereferenced value.
|
||||
switch {
|
||||
case nilFound == true:
|
||||
case nilFound:
|
||||
f.fs.Write(nilAngleBytes)
|
||||
|
||||
case cycleFound == true:
|
||||
case cycleFound:
|
||||
f.fs.Write(circularShortBytes)
|
||||
|
||||
default:
|
||||
|
|
|
@ -0,0 +1,23 @@
|
|||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
*.test
|
|
@ -0,0 +1,13 @@
|
|||
language: go
|
||||
go:
|
||||
- 1.7.x
|
||||
- 1.8.x
|
||||
- 1.9.x
|
||||
- tip
|
||||
sudo: false
|
||||
before_install:
|
||||
- go get github.com/axw/gocov/gocov
|
||||
- go get github.com/mattn/goveralls
|
||||
- if ! go get github.com/golang/tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi
|
||||
script:
|
||||
- $HOME/gopath/bin/goveralls -service=travis-ci
|
|
@ -1,397 +0,0 @@
|
|||
package structs
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A test struct that defines all cases
|
||||
type Foo struct {
|
||||
A string
|
||||
B int `structs:"y"`
|
||||
C bool `json:"c"`
|
||||
d string // not exported
|
||||
E *Baz
|
||||
x string `xml:"x"` // not exported, with tag
|
||||
Y []string
|
||||
Z map[string]interface{}
|
||||
*Bar // embedded
|
||||
}
|
||||
|
||||
type Baz struct {
|
||||
A string
|
||||
B int
|
||||
}
|
||||
|
||||
type Bar struct {
|
||||
E string
|
||||
F int
|
||||
g []string
|
||||
}
|
||||
|
||||
func newStruct() *Struct {
|
||||
b := &Bar{
|
||||
E: "example",
|
||||
F: 2,
|
||||
g: []string{"zeynep", "fatih"},
|
||||
}
|
||||
|
||||
// B and x is not initialized for testing
|
||||
f := &Foo{
|
||||
A: "gopher",
|
||||
C: true,
|
||||
d: "small",
|
||||
E: nil,
|
||||
Y: []string{"example"},
|
||||
Z: nil,
|
||||
}
|
||||
f.Bar = b
|
||||
|
||||
return New(f)
|
||||
}
|
||||
|
||||
func TestField_Set(t *testing.T) {
|
||||
s := newStruct()
|
||||
|
||||
f := s.Field("A")
|
||||
err := f.Set("fatih")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if f.Value().(string) != "fatih" {
|
||||
t.Errorf("Setted value is wrong: %s want: %s", f.Value().(string), "fatih")
|
||||
}
|
||||
|
||||
f = s.Field("Y")
|
||||
err = f.Set([]string{"override", "with", "this"})
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
sliceLen := len(f.Value().([]string))
|
||||
if sliceLen != 3 {
|
||||
t.Errorf("Setted values slice length is wrong: %d, want: %d", sliceLen, 3)
|
||||
}
|
||||
|
||||
f = s.Field("C")
|
||||
err = f.Set(false)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if f.Value().(bool) {
|
||||
t.Errorf("Setted value is wrong: %t want: %t", f.Value().(bool), false)
|
||||
}
|
||||
|
||||
// let's pass a different type
|
||||
f = s.Field("A")
|
||||
err = f.Set(123) // Field A is of type string, but we are going to pass an integer
|
||||
if err == nil {
|
||||
t.Error("Setting a field's value with a different type than the field's type should return an error")
|
||||
}
|
||||
|
||||
// old value should be still there :)
|
||||
if f.Value().(string) != "fatih" {
|
||||
t.Errorf("Setted value is wrong: %s want: %s", f.Value().(string), "fatih")
|
||||
}
|
||||
|
||||
// let's access an unexported field, which should give an error
|
||||
f = s.Field("d")
|
||||
err = f.Set("large")
|
||||
if err != errNotExported {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
// let's set a pointer to struct
|
||||
b := &Bar{
|
||||
E: "gopher",
|
||||
F: 2,
|
||||
}
|
||||
|
||||
f = s.Field("Bar")
|
||||
err = f.Set(b)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
baz := &Baz{
|
||||
A: "helloWorld",
|
||||
B: 42,
|
||||
}
|
||||
|
||||
f = s.Field("E")
|
||||
err = f.Set(baz)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
ba := s.Field("E").Value().(*Baz)
|
||||
|
||||
if ba.A != "helloWorld" {
|
||||
t.Errorf("could not set baz. Got: %s Want: helloWorld", ba.A)
|
||||
}
|
||||
}
|
||||
|
||||
func TestField_NotSettable(t *testing.T) {
|
||||
a := map[int]Baz{
|
||||
4: {
|
||||
A: "value",
|
||||
},
|
||||
}
|
||||
|
||||
s := New(a[4])
|
||||
|
||||
if err := s.Field("A").Set("newValue"); err != errNotSettable {
|
||||
t.Errorf("Trying to set non-settable field should error with %q. Got %q instead.", errNotSettable, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestField_Zero(t *testing.T) {
|
||||
s := newStruct()
|
||||
|
||||
f := s.Field("A")
|
||||
err := f.Zero()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if f.Value().(string) != "" {
|
||||
t.Errorf("Zeroed value is wrong: %s want: %s", f.Value().(string), "")
|
||||
}
|
||||
|
||||
f = s.Field("Y")
|
||||
err = f.Zero()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
sliceLen := len(f.Value().([]string))
|
||||
if sliceLen != 0 {
|
||||
t.Errorf("Zeroed values slice length is wrong: %d, want: %d", sliceLen, 0)
|
||||
}
|
||||
|
||||
f = s.Field("C")
|
||||
err = f.Zero()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
if f.Value().(bool) {
|
||||
t.Errorf("Zeroed value is wrong: %t want: %t", f.Value().(bool), false)
|
||||
}
|
||||
|
||||
// let's access an unexported field, which should give an error
|
||||
f = s.Field("d")
|
||||
err = f.Zero()
|
||||
if err != errNotExported {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
f = s.Field("Bar")
|
||||
err = f.Zero()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
f = s.Field("E")
|
||||
err = f.Zero()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
v := s.Field("E").value
|
||||
if !v.IsNil() {
|
||||
t.Errorf("could not set baz. Got: %s Want: <nil>", v.Interface())
|
||||
}
|
||||
}
|
||||
|
||||
func TestField(t *testing.T) {
|
||||
s := newStruct()
|
||||
|
||||
defer func() {
|
||||
err := recover()
|
||||
if err == nil {
|
||||
t.Error("Retrieveing a non existing field from the struct should panic")
|
||||
}
|
||||
}()
|
||||
|
||||
_ = s.Field("no-field")
|
||||
}
|
||||
|
||||
func TestField_Kind(t *testing.T) {
|
||||
s := newStruct()
|
||||
|
||||
f := s.Field("A")
|
||||
if f.Kind() != reflect.String {
|
||||
t.Errorf("Field A has wrong kind: %s want: %s", f.Kind(), reflect.String)
|
||||
}
|
||||
|
||||
f = s.Field("B")
|
||||
if f.Kind() != reflect.Int {
|
||||
t.Errorf("Field B has wrong kind: %s want: %s", f.Kind(), reflect.Int)
|
||||
}
|
||||
|
||||
// unexported
|
||||
f = s.Field("d")
|
||||
if f.Kind() != reflect.String {
|
||||
t.Errorf("Field d has wrong kind: %s want: %s", f.Kind(), reflect.String)
|
||||
}
|
||||
}
|
||||
|
||||
func TestField_Tag(t *testing.T) {
|
||||
s := newStruct()
|
||||
|
||||
v := s.Field("B").Tag("json")
|
||||
if v != "" {
|
||||
t.Errorf("Field's tag value of a non existing tag should return empty, got: %s", v)
|
||||
}
|
||||
|
||||
v = s.Field("C").Tag("json")
|
||||
if v != "c" {
|
||||
t.Errorf("Field's tag value of the existing field C should return 'c', got: %s", v)
|
||||
}
|
||||
|
||||
v = s.Field("d").Tag("json")
|
||||
if v != "" {
|
||||
t.Errorf("Field's tag value of a non exported field should return empty, got: %s", v)
|
||||
}
|
||||
|
||||
v = s.Field("x").Tag("xml")
|
||||
if v != "x" {
|
||||
t.Errorf("Field's tag value of a non exported field with a tag should return 'x', got: %s", v)
|
||||
}
|
||||
|
||||
v = s.Field("A").Tag("json")
|
||||
if v != "" {
|
||||
t.Errorf("Field's tag value of a existing field without a tag should return empty, got: %s", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestField_Value(t *testing.T) {
|
||||
s := newStruct()
|
||||
|
||||
v := s.Field("A").Value()
|
||||
val, ok := v.(string)
|
||||
if !ok {
|
||||
t.Errorf("Field's value of a A should be string")
|
||||
}
|
||||
|
||||
if val != "gopher" {
|
||||
t.Errorf("Field's value of a existing tag should return 'gopher', got: %s", val)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := recover()
|
||||
if err == nil {
|
||||
t.Error("Value of a non exported field from the field should panic")
|
||||
}
|
||||
}()
|
||||
|
||||
// should panic
|
||||
_ = s.Field("d").Value()
|
||||
}
|
||||
|
||||
func TestField_IsEmbedded(t *testing.T) {
|
||||
s := newStruct()
|
||||
|
||||
if !s.Field("Bar").IsEmbedded() {
|
||||
t.Errorf("Fields 'Bar' field is an embedded field")
|
||||
}
|
||||
|
||||
if s.Field("d").IsEmbedded() {
|
||||
t.Errorf("Fields 'd' field is not an embedded field")
|
||||
}
|
||||
}
|
||||
|
||||
func TestField_IsExported(t *testing.T) {
|
||||
s := newStruct()
|
||||
|
||||
if !s.Field("Bar").IsExported() {
|
||||
t.Errorf("Fields 'Bar' field is an exported field")
|
||||
}
|
||||
|
||||
if !s.Field("A").IsExported() {
|
||||
t.Errorf("Fields 'A' field is an exported field")
|
||||
}
|
||||
|
||||
if s.Field("d").IsExported() {
|
||||
t.Errorf("Fields 'd' field is not an exported field")
|
||||
}
|
||||
}
|
||||
|
||||
func TestField_IsZero(t *testing.T) {
|
||||
s := newStruct()
|
||||
|
||||
if s.Field("A").IsZero() {
|
||||
t.Errorf("Fields 'A' field is an initialized field")
|
||||
}
|
||||
|
||||
if !s.Field("B").IsZero() {
|
||||
t.Errorf("Fields 'B' field is not an initialized field")
|
||||
}
|
||||
}
|
||||
|
||||
func TestField_Name(t *testing.T) {
|
||||
s := newStruct()
|
||||
|
||||
if s.Field("A").Name() != "A" {
|
||||
t.Errorf("Fields 'A' field should have the name 'A'")
|
||||
}
|
||||
}
|
||||
|
||||
func TestField_Field(t *testing.T) {
|
||||
s := newStruct()
|
||||
|
||||
e := s.Field("Bar").Field("E")
|
||||
|
||||
val, ok := e.Value().(string)
|
||||
if !ok {
|
||||
t.Error("The value of the field 'e' inside 'Bar' struct should be string")
|
||||
}
|
||||
|
||||
if val != "example" {
|
||||
t.Errorf("The value of 'e' should be 'example, got: %s", val)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
err := recover()
|
||||
if err == nil {
|
||||
t.Error("Field of a non existing nested struct should panic")
|
||||
}
|
||||
}()
|
||||
|
||||
_ = s.Field("Bar").Field("e")
|
||||
}
|
||||
|
||||
func TestField_Fields(t *testing.T) {
|
||||
s := newStruct()
|
||||
fields := s.Field("Bar").Fields()
|
||||
|
||||
if len(fields) != 3 {
|
||||
t.Errorf("We expect 3 fields in embedded struct, was: %d", len(fields))
|
||||
}
|
||||
}
|
||||
|
||||
func TestField_FieldOk(t *testing.T) {
|
||||
s := newStruct()
|
||||
|
||||
b, ok := s.FieldOk("Bar")
|
||||
if !ok {
|
||||
t.Error("The field 'Bar' should exists.")
|
||||
}
|
||||
|
||||
e, ok := b.FieldOk("E")
|
||||
if !ok {
|
||||
t.Error("The field 'E' should exists.")
|
||||
}
|
||||
|
||||
val, ok := e.Value().(string)
|
||||
if !ok {
|
||||
t.Error("The value of the field 'e' inside 'Bar' struct should be string")
|
||||
}
|
||||
|
||||
if val != "example" {
|
||||
t.Errorf("The value of 'e' should be 'example, got: %s", val)
|
||||
}
|
||||
}
|
|
@ -1,351 +0,0 @@
|
|||
package structs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ExampleNew() {
|
||||
type Server struct {
|
||||
Name string
|
||||
ID int32
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
server := &Server{
|
||||
Name: "Arslan",
|
||||
ID: 123456,
|
||||
Enabled: true,
|
||||
}
|
||||
|
||||
s := New(server)
|
||||
|
||||
fmt.Printf("Name : %v\n", s.Name())
|
||||
fmt.Printf("Values : %v\n", s.Values())
|
||||
fmt.Printf("Value of ID : %v\n", s.Field("ID").Value())
|
||||
// Output:
|
||||
// Name : Server
|
||||
// Values : [Arslan 123456 true]
|
||||
// Value of ID : 123456
|
||||
|
||||
}
|
||||
|
||||
func ExampleMap() {
|
||||
type Server struct {
|
||||
Name string
|
||||
ID int32
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
s := &Server{
|
||||
Name: "Arslan",
|
||||
ID: 123456,
|
||||
Enabled: true,
|
||||
}
|
||||
|
||||
m := Map(s)
|
||||
|
||||
fmt.Printf("%#v\n", m["Name"])
|
||||
fmt.Printf("%#v\n", m["ID"])
|
||||
fmt.Printf("%#v\n", m["Enabled"])
|
||||
// Output:
|
||||
// "Arslan"
|
||||
// 123456
|
||||
// true
|
||||
|
||||
}
|
||||
|
||||
func ExampleMap_tags() {
|
||||
// Custom tags can change the map keys instead of using the fields name
|
||||
type Server struct {
|
||||
Name string `structs:"server_name"`
|
||||
ID int32 `structs:"server_id"`
|
||||
Enabled bool `structs:"enabled"`
|
||||
}
|
||||
|
||||
s := &Server{
|
||||
Name: "Zeynep",
|
||||
ID: 789012,
|
||||
}
|
||||
|
||||
m := Map(s)
|
||||
|
||||
// access them by the custom tags defined above
|
||||
fmt.Printf("%#v\n", m["server_name"])
|
||||
fmt.Printf("%#v\n", m["server_id"])
|
||||
fmt.Printf("%#v\n", m["enabled"])
|
||||
// Output:
|
||||
// "Zeynep"
|
||||
// 789012
|
||||
// false
|
||||
|
||||
}
|
||||
|
||||
func ExampleMap_omitNested() {
|
||||
// By default field with struct types are processed too. We can stop
|
||||
// processing them via "omitnested" tag option.
|
||||
type Server struct {
|
||||
Name string `structs:"server_name"`
|
||||
ID int32 `structs:"server_id"`
|
||||
Time time.Time `structs:"time,omitnested"` // do not convert to map[string]interface{}
|
||||
}
|
||||
|
||||
const shortForm = "2006-Jan-02"
|
||||
t, _ := time.Parse("2006-Jan-02", "2013-Feb-03")
|
||||
|
||||
s := &Server{
|
||||
Name: "Zeynep",
|
||||
ID: 789012,
|
||||
Time: t,
|
||||
}
|
||||
|
||||
m := Map(s)
|
||||
|
||||
// access them by the custom tags defined above
|
||||
fmt.Printf("%v\n", m["server_name"])
|
||||
fmt.Printf("%v\n", m["server_id"])
|
||||
fmt.Printf("%v\n", m["time"].(time.Time))
|
||||
// Output:
|
||||
// Zeynep
|
||||
// 789012
|
||||
// 2013-02-03 00:00:00 +0000 UTC
|
||||
}
|
||||
|
||||
func ExampleMap_omitEmpty() {
|
||||
// By default field with struct types of zero values are processed too. We
|
||||
// can stop processing them via "omitempty" tag option.
|
||||
type Server struct {
|
||||
Name string `structs:",omitempty"`
|
||||
ID int32 `structs:"server_id,omitempty"`
|
||||
Location string
|
||||
}
|
||||
|
||||
// Only add location
|
||||
s := &Server{
|
||||
Location: "Tokyo",
|
||||
}
|
||||
|
||||
m := Map(s)
|
||||
|
||||
// map contains only the Location field
|
||||
fmt.Printf("%v\n", m)
|
||||
// Output:
|
||||
// map[Location:Tokyo]
|
||||
}
|
||||
|
||||
func ExampleValues() {
|
||||
type Server struct {
|
||||
Name string
|
||||
ID int32
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
s := &Server{
|
||||
Name: "Fatih",
|
||||
ID: 135790,
|
||||
Enabled: false,
|
||||
}
|
||||
|
||||
m := Values(s)
|
||||
|
||||
fmt.Printf("Values: %+v\n", m)
|
||||
// Output:
|
||||
// Values: [Fatih 135790 false]
|
||||
}
|
||||
|
||||
func ExampleValues_omitEmpty() {
|
||||
// By default field with struct types of zero values are processed too. We
|
||||
// can stop processing them via "omitempty" tag option.
|
||||
type Server struct {
|
||||
Name string `structs:",omitempty"`
|
||||
ID int32 `structs:"server_id,omitempty"`
|
||||
Location string
|
||||
}
|
||||
|
||||
// Only add location
|
||||
s := &Server{
|
||||
Location: "Ankara",
|
||||
}
|
||||
|
||||
m := Values(s)
|
||||
|
||||
// values contains only the Location field
|
||||
fmt.Printf("Values: %+v\n", m)
|
||||
// Output:
|
||||
// Values: [Ankara]
|
||||
}
|
||||
|
||||
func ExampleValues_tags() {
|
||||
type Location struct {
|
||||
City string
|
||||
Country string
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
Name string
|
||||
ID int32
|
||||
Enabled bool
|
||||
Location Location `structs:"-"` // values from location are not included anymore
|
||||
}
|
||||
|
||||
s := &Server{
|
||||
Name: "Fatih",
|
||||
ID: 135790,
|
||||
Enabled: false,
|
||||
Location: Location{City: "Ankara", Country: "Turkey"},
|
||||
}
|
||||
|
||||
// Let get all values from the struct s. Note that we don't include values
|
||||
// from the Location field
|
||||
m := Values(s)
|
||||
|
||||
fmt.Printf("Values: %+v\n", m)
|
||||
// Output:
|
||||
// Values: [Fatih 135790 false]
|
||||
}
|
||||
|
||||
func ExampleFields() {
|
||||
type Access struct {
|
||||
Name string
|
||||
LastAccessed time.Time
|
||||
Number int
|
||||
}
|
||||
|
||||
s := &Access{
|
||||
Name: "Fatih",
|
||||
LastAccessed: time.Now(),
|
||||
Number: 1234567,
|
||||
}
|
||||
|
||||
fields := Fields(s)
|
||||
|
||||
for i, field := range fields {
|
||||
fmt.Printf("[%d] %+v\n", i, field.Name())
|
||||
}
|
||||
|
||||
// Output:
|
||||
// [0] Name
|
||||
// [1] LastAccessed
|
||||
// [2] Number
|
||||
}
|
||||
|
||||
func ExampleFields_nested() {
|
||||
type Person struct {
|
||||
Name string
|
||||
Number int
|
||||
}
|
||||
|
||||
type Access struct {
|
||||
Person Person
|
||||
HasPermission bool
|
||||
LastAccessed time.Time
|
||||
}
|
||||
|
||||
s := &Access{
|
||||
Person: Person{Name: "fatih", Number: 1234567},
|
||||
LastAccessed: time.Now(),
|
||||
HasPermission: true,
|
||||
}
|
||||
|
||||
// Let's get all fields from the struct s.
|
||||
fields := Fields(s)
|
||||
|
||||
for _, field := range fields {
|
||||
if field.Name() == "Person" {
|
||||
fmt.Printf("Access.Person.Name: %+v\n", field.Field("Name").Value())
|
||||
}
|
||||
}
|
||||
|
||||
// Output:
|
||||
// Access.Person.Name: fatih
|
||||
}
|
||||
|
||||
func ExampleField() {
|
||||
type Person struct {
|
||||
Name string
|
||||
Number int
|
||||
}
|
||||
|
||||
type Access struct {
|
||||
Person Person
|
||||
HasPermission bool
|
||||
LastAccessed time.Time
|
||||
}
|
||||
|
||||
access := &Access{
|
||||
Person: Person{Name: "fatih", Number: 1234567},
|
||||
LastAccessed: time.Now(),
|
||||
HasPermission: true,
|
||||
}
|
||||
|
||||
// Create a new Struct type
|
||||
s := New(access)
|
||||
|
||||
// Get the Field type for "Person" field
|
||||
p := s.Field("Person")
|
||||
|
||||
// Get the underlying "Name field" and print the value of it
|
||||
name := p.Field("Name")
|
||||
|
||||
fmt.Printf("Value of Person.Access.Name: %+v\n", name.Value())
|
||||
|
||||
// Output:
|
||||
// Value of Person.Access.Name: fatih
|
||||
|
||||
}
|
||||
|
||||
func ExampleIsZero() {
|
||||
type Server struct {
|
||||
Name string
|
||||
ID int32
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
// Nothing is initialized
|
||||
a := &Server{}
|
||||
isZeroA := IsZero(a)
|
||||
|
||||
// Name and Enabled is initialized, but not ID
|
||||
b := &Server{
|
||||
Name: "Golang",
|
||||
Enabled: true,
|
||||
}
|
||||
isZeroB := IsZero(b)
|
||||
|
||||
fmt.Printf("%#v\n", isZeroA)
|
||||
fmt.Printf("%#v\n", isZeroB)
|
||||
// Output:
|
||||
// true
|
||||
// false
|
||||
}
|
||||
|
||||
func ExampleHasZero() {
|
||||
// Let's define an Access struct. Note that the "Enabled" field is not
|
||||
// going to be checked because we added the "structs" tag to the field.
|
||||
type Access struct {
|
||||
Name string
|
||||
LastAccessed time.Time
|
||||
Number int
|
||||
Enabled bool `structs:"-"`
|
||||
}
|
||||
|
||||
// Name and Number is not initialized.
|
||||
a := &Access{
|
||||
LastAccessed: time.Now(),
|
||||
}
|
||||
hasZeroA := HasZero(a)
|
||||
|
||||
// Name and Number is initialized.
|
||||
b := &Access{
|
||||
Name: "Fatih",
|
||||
LastAccessed: time.Now(),
|
||||
Number: 12345,
|
||||
}
|
||||
hasZeroB := HasZero(b)
|
||||
|
||||
fmt.Printf("%#v\n", hasZeroA)
|
||||
fmt.Printf("%#v\n", hasZeroB)
|
||||
// Output:
|
||||
// true
|
||||
// false
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -1,46 +0,0 @@
|
|||
package structs
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestParseTag_Name(t *testing.T) {
|
||||
tags := []struct {
|
||||
tag string
|
||||
has bool
|
||||
}{
|
||||
{"", false},
|
||||
{"name", true},
|
||||
{"name,opt", true},
|
||||
{"name , opt, opt2", false}, // has a single whitespace
|
||||
{", opt, opt2", false},
|
||||
}
|
||||
|
||||
for _, tag := range tags {
|
||||
name, _ := parseTag(tag.tag)
|
||||
|
||||
if (name != "name") && tag.has {
|
||||
t.Errorf("Parse tag should return name: %#v", tag)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTag_Opts(t *testing.T) {
|
||||
tags := []struct {
|
||||
opts string
|
||||
has bool
|
||||
}{
|
||||
{"name", false},
|
||||
{"name,opt", true},
|
||||
{"name , opt, opt2", false}, // has a single whitespace
|
||||
{",opt, opt2", true},
|
||||
{", opt3, opt4", false},
|
||||
}
|
||||
|
||||
// search for "opt"
|
||||
for _, tag := range tags {
|
||||
_, opts := parseTag(tag.opts)
|
||||
|
||||
if opts.Has("opt") != tag.has {
|
||||
t.Errorf("Tag opts should have opt: %#v", tag)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,328 +0,0 @@
|
|||
// Copyright 2013 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package query
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Nested struct {
|
||||
A SubNested `url:"a"`
|
||||
B *SubNested `url:"b"`
|
||||
Ptr *SubNested `url:"ptr,omitempty"`
|
||||
}
|
||||
|
||||
type SubNested struct {
|
||||
Value string `url:"value"`
|
||||
}
|
||||
|
||||
func TestValues_types(t *testing.T) {
|
||||
str := "string"
|
||||
strPtr := &str
|
||||
timeVal := time.Date(2000, 1, 1, 12, 34, 56, 0, time.UTC)
|
||||
|
||||
tests := []struct {
|
||||
in interface{}
|
||||
want url.Values
|
||||
}{
|
||||
{
|
||||
// basic primitives
|
||||
struct {
|
||||
A string
|
||||
B int
|
||||
C uint
|
||||
D float32
|
||||
E bool
|
||||
}{},
|
||||
url.Values{
|
||||
"A": {""},
|
||||
"B": {"0"},
|
||||
"C": {"0"},
|
||||
"D": {"0"},
|
||||
"E": {"false"},
|
||||
},
|
||||
},
|
||||
{
|
||||
// pointers
|
||||
struct {
|
||||
A *string
|
||||
B *int
|
||||
C **string
|
||||
D *time.Time
|
||||
}{
|
||||
A: strPtr,
|
||||
C: &strPtr,
|
||||
D: &timeVal,
|
||||
},
|
||||
url.Values{
|
||||
"A": {str},
|
||||
"B": {""},
|
||||
"C": {str},
|
||||
"D": {"2000-01-01T12:34:56Z"},
|
||||
},
|
||||
},
|
||||
{
|
||||
// slices and arrays
|
||||
struct {
|
||||
A []string
|
||||
B []string `url:",comma"`
|
||||
C []string `url:",space"`
|
||||
D [2]string
|
||||
E [2]string `url:",comma"`
|
||||
F [2]string `url:",space"`
|
||||
G []*string `url:",space"`
|
||||
H []bool `url:",int,space"`
|
||||
I []string `url:",brackets"`
|
||||
J []string `url:",semicolon"`
|
||||
K []string `url:",numbered"`
|
||||
}{
|
||||
A: []string{"a", "b"},
|
||||
B: []string{"a", "b"},
|
||||
C: []string{"a", "b"},
|
||||
D: [2]string{"a", "b"},
|
||||
E: [2]string{"a", "b"},
|
||||
F: [2]string{"a", "b"},
|
||||
G: []*string{&str, &str},
|
||||
H: []bool{true, false},
|
||||
I: []string{"a", "b"},
|
||||
J: []string{"a", "b"},
|
||||
K: []string{"a", "b"},
|
||||
},
|
||||
url.Values{
|
||||
"A": {"a", "b"},
|
||||
"B": {"a,b"},
|
||||
"C": {"a b"},
|
||||
"D": {"a", "b"},
|
||||
"E": {"a,b"},
|
||||
"F": {"a b"},
|
||||
"G": {"string string"},
|
||||
"H": {"1 0"},
|
||||
"I[]": {"a", "b"},
|
||||
"J": {"a;b"},
|
||||
"K0": {"a"},
|
||||
"K1": {"b"},
|
||||
},
|
||||
},
|
||||
{
|
||||
// other types
|
||||
struct {
|
||||
A time.Time
|
||||
B time.Time `url:",unix"`
|
||||
C bool `url:",int"`
|
||||
D bool `url:",int"`
|
||||
}{
|
||||
A: time.Date(2000, 1, 1, 12, 34, 56, 0, time.UTC),
|
||||
B: time.Date(2000, 1, 1, 12, 34, 56, 0, time.UTC),
|
||||
C: true,
|
||||
D: false,
|
||||
},
|
||||
url.Values{
|
||||
"A": {"2000-01-01T12:34:56Z"},
|
||||
"B": {"946730096"},
|
||||
"C": {"1"},
|
||||
"D": {"0"},
|
||||
},
|
||||
},
|
||||
{
|
||||
struct {
|
||||
Nest Nested `url:"nest"`
|
||||
}{
|
||||
Nested{
|
||||
A: SubNested{
|
||||
Value: "that",
|
||||
},
|
||||
},
|
||||
},
|
||||
url.Values{
|
||||
"nest[a][value]": {"that"},
|
||||
"nest[b]": {""},
|
||||
},
|
||||
},
|
||||
{
|
||||
struct {
|
||||
Nest Nested `url:"nest"`
|
||||
}{
|
||||
Nested{
|
||||
Ptr: &SubNested{
|
||||
Value: "that",
|
||||
},
|
||||
},
|
||||
},
|
||||
url.Values{
|
||||
"nest[a][value]": {""},
|
||||
"nest[b]": {""},
|
||||
"nest[ptr][value]": {"that"},
|
||||
},
|
||||
},
|
||||
{
|
||||
nil,
|
||||
url.Values{},
|
||||
},
|
||||
}
|
||||
|
||||
for i, tt := range tests {
|
||||
v, err := Values(tt.in)
|
||||
if err != nil {
|
||||
t.Errorf("%d. Values(%q) returned error: %v", i, tt.in, err)
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(tt.want, v) {
|
||||
t.Errorf("%d. Values(%q) returned %v, want %v", i, tt.in, v, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValues_omitEmpty(t *testing.T) {
|
||||
str := ""
|
||||
s := struct {
|
||||
a string
|
||||
A string
|
||||
B string `url:",omitempty"`
|
||||
C string `url:"-"`
|
||||
D string `url:"omitempty"` // actually named omitempty, not an option
|
||||
E *string `url:",omitempty"`
|
||||
}{E: &str}
|
||||
|
||||
v, err := Values(s)
|
||||
if err != nil {
|
||||
t.Errorf("Values(%q) returned error: %v", s, err)
|
||||
}
|
||||
|
||||
want := url.Values{
|
||||
"A": {""},
|
||||
"omitempty": {""},
|
||||
"E": {""}, // E is included because the pointer is not empty, even though the string being pointed to is
|
||||
}
|
||||
if !reflect.DeepEqual(want, v) {
|
||||
t.Errorf("Values(%q) returned %v, want %v", s, v, want)
|
||||
}
|
||||
}
|
||||
|
||||
type A struct {
|
||||
B
|
||||
}
|
||||
|
||||
type B struct {
|
||||
C string
|
||||
}
|
||||
|
||||
type D struct {
|
||||
B
|
||||
C string
|
||||
}
|
||||
|
||||
type e struct {
|
||||
B
|
||||
C string
|
||||
}
|
||||
|
||||
type F struct {
|
||||
e
|
||||
}
|
||||
|
||||
func TestValues_embeddedStructs(t *testing.T) {
|
||||
tests := []struct {
|
||||
in interface{}
|
||||
want url.Values
|
||||
}{
|
||||
{
|
||||
A{B{C: "foo"}},
|
||||
url.Values{"C": {"foo"}},
|
||||
},
|
||||
{
|
||||
D{B: B{C: "bar"}, C: "foo"},
|
||||
url.Values{"C": {"foo", "bar"}},
|
||||
},
|
||||
{
|
||||
F{e{B: B{C: "bar"}, C: "foo"}}, // With unexported embed
|
||||
url.Values{"C": {"foo", "bar"}},
|
||||
},
|
||||
}
|
||||
|
||||
for i, tt := range tests {
|
||||
v, err := Values(tt.in)
|
||||
if err != nil {
|
||||
t.Errorf("%d. Values(%q) returned error: %v", i, tt.in, err)
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(tt.want, v) {
|
||||
t.Errorf("%d. Values(%q) returned %v, want %v", i, tt.in, v, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValues_invalidInput(t *testing.T) {
|
||||
_, err := Values("")
|
||||
if err == nil {
|
||||
t.Errorf("expected Values() to return an error on invalid input")
|
||||
}
|
||||
}
|
||||
|
||||
type EncodedArgs []string
|
||||
|
||||
func (m EncodedArgs) EncodeValues(key string, v *url.Values) error {
|
||||
for i, arg := range m {
|
||||
v.Set(fmt.Sprintf("%s.%d", key, i), arg)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestValues_Marshaler(t *testing.T) {
|
||||
s := struct {
|
||||
Args EncodedArgs `url:"arg"`
|
||||
}{[]string{"a", "b", "c"}}
|
||||
v, err := Values(s)
|
||||
if err != nil {
|
||||
t.Errorf("Values(%q) returned error: %v", s, err)
|
||||
}
|
||||
|
||||
want := url.Values{
|
||||
"arg.0": {"a"},
|
||||
"arg.1": {"b"},
|
||||
"arg.2": {"c"},
|
||||
}
|
||||
if !reflect.DeepEqual(want, v) {
|
||||
t.Errorf("Values(%q) returned %v, want %v", s, v, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValues_MarshalerWithNilPointer(t *testing.T) {
|
||||
s := struct {
|
||||
Args *EncodedArgs `url:"arg"`
|
||||
}{}
|
||||
v, err := Values(s)
|
||||
if err != nil {
|
||||
t.Errorf("Values(%q) returned error: %v", s, err)
|
||||
}
|
||||
|
||||
want := url.Values{}
|
||||
if !reflect.DeepEqual(want, v) {
|
||||
t.Errorf("Values(%q) returned %v, want %v", s, v, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTagParsing(t *testing.T) {
|
||||
name, opts := parseTag("field,foobar,foo")
|
||||
if name != "field" {
|
||||
t.Fatalf("name = %q, want field", name)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
opt string
|
||||
want bool
|
||||
}{
|
||||
{"foobar", true},
|
||||
{"foo", true},
|
||||
{"bar", false},
|
||||
{"field", false},
|
||||
} {
|
||||
if opts.Contains(tt.opt) != tt.want {
|
||||
t.Errorf("Contains(%q) = %v", tt.opt, !tt.want)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
(The MIT License)
|
||||
|
||||
Copyright (c) 2017 marvin + konsorten GmbH (open-source@konsorten.de)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
40
vendor/github.com/konsorten/go-windows-terminal-sequences/README.md
generated
vendored
Normal file
40
vendor/github.com/konsorten/go-windows-terminal-sequences/README.md
generated
vendored
Normal file
|
@ -0,0 +1,40 @@
|
|||
# Windows Terminal Sequences
|
||||
|
||||
This library allow for enabling Windows terminal color support for Go.
|
||||
|
||||
See [Console Virtual Terminal Sequences](https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences) for details.
|
||||
|
||||
## Usage
|
||||
|
||||
```go
|
||||
import (
|
||||
"syscall"
|
||||
|
||||
sequences "github.com/konsorten/go-windows-terminal-sequences"
|
||||
)
|
||||
|
||||
func main() {
|
||||
sequences.EnableVirtualTerminalProcessing(syscall.Stdout, true)
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## Authors
|
||||
|
||||
The tool is sponsored by the [marvin + konsorten GmbH](http://www.konsorten.de).
|
||||
|
||||
We thank all the authors who provided code to this library:
|
||||
|
||||
* Felix Kollmann
|
||||
|
||||
## License
|
||||
|
||||
(The MIT License)
|
||||
|
||||
Copyright (c) 2018 marvin + konsorten GmbH (open-source@konsorten.de)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@ -0,0 +1 @@
|
|||
module github.com/konsorten/go-windows-terminal-sequences
|
36
vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go
generated
vendored
Normal file
36
vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go
generated
vendored
Normal file
|
@ -0,0 +1,36 @@
|
|||
// +build windows
|
||||
|
||||
package sequences
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var (
|
||||
kernel32Dll *syscall.LazyDLL = syscall.NewLazyDLL("Kernel32.dll")
|
||||
setConsoleMode *syscall.LazyProc = kernel32Dll.NewProc("SetConsoleMode")
|
||||
)
|
||||
|
||||
func EnableVirtualTerminalProcessing(stream syscall.Handle, enable bool) error {
|
||||
const ENABLE_VIRTUAL_TERMINAL_PROCESSING uint32 = 0x4
|
||||
|
||||
var mode uint32
|
||||
err := syscall.GetConsoleMode(syscall.Stdout, &mode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if enable {
|
||||
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING
|
||||
} else {
|
||||
mode &^= ENABLE_VIRTUAL_TERMINAL_PROCESSING
|
||||
}
|
||||
|
||||
ret, _, err := setConsoleMode.Call(uintptr(unsafe.Pointer(stream)), uintptr(mode))
|
||||
if ret == 0 {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
*.test
|
||||
*.prof
|
||||
|
||||
.idea/
|
||||
*.iml
|
|
@ -0,0 +1,23 @@
|
|||
language: go
|
||||
|
||||
matrix:
|
||||
fast_finish: true
|
||||
include:
|
||||
- go: 1.7
|
||||
- go: 1.8
|
||||
- go: master
|
||||
allow_failures:
|
||||
- go: master
|
||||
before_install:
|
||||
- go get -u -v github.com/axw/gocov/gocov
|
||||
- go get -u -v github.com/mattn/goveralls
|
||||
- go get -u -v github.com/golang/lint/golint
|
||||
|
||||
script:
|
||||
- diff -u <(echo -n) <(gofmt -s -d ./)
|
||||
- diff -u <(echo -n) <(go vet ./...)
|
||||
- diff -u <(echo -n) <(golint ./...)
|
||||
- go test -v -race -covermode=atomic -coverprofile=coverage.out
|
||||
|
||||
after_success:
|
||||
- goveralls -coverprofile=coverage.out -service=travis-ci -repotoken $COVERALLS_TOKEN
|
|
@ -1,99 +0,0 @@
|
|||
package grequests
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBasicDeleteRequest(t *testing.T) {
|
||||
resp, err := Delete("http://httpbin.org/delete", nil)
|
||||
|
||||
if err != nil {
|
||||
t.Error("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteSession(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
resp, err := session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"one": "two"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"two": "three"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"three": "four"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
resp, err = session.Delete("http://httpbin.org/delete", nil)
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
cookieURL, err := url.Parse("http://httpbin.org")
|
||||
if err != nil {
|
||||
t.Error("We (for some reason) cannot parse the cookie URL")
|
||||
}
|
||||
|
||||
if len(session.HTTPClient.Jar.Cookies(cookieURL)) != 3 {
|
||||
t.Error("Invalid number of cookies provided: ", resp.RawResponse.Cookies())
|
||||
}
|
||||
|
||||
for _, cookie := range session.HTTPClient.Jar.Cookies(cookieURL) {
|
||||
switch cookie.Name {
|
||||
case "one":
|
||||
if cookie.Value != "two" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
case "two":
|
||||
if cookie.Value != "three" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
case "three":
|
||||
if cookie.Value != "four" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
default:
|
||||
t.Error("We should not have any other cookies: ", cookie)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestDeleteInvalidURLSession(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
if _, err := session.Delete("%../dir/", nil); err == nil {
|
||||
t.Error("Some how the request was valid to make request ", err)
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -1,115 +0,0 @@
|
|||
package grequests
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBasicHeadRequest(t *testing.T) {
|
||||
resp, err := Head("http://httpbin.org/get", nil)
|
||||
if err != nil {
|
||||
t.Error("Unable to make HEAD request: ", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("HEAD request did not return success: ", resp.StatusCode)
|
||||
}
|
||||
|
||||
if resp.Header.Get("Content-Type") != "application/json" {
|
||||
t.Error("Content Type Header is unexpected: ", resp.Header.Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBasicHeadRequestNoContent(t *testing.T) {
|
||||
resp, err := Head("http://httpbin.org/bytes/0", nil)
|
||||
if err != nil {
|
||||
t.Error("Unable to make HEAD request: ", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("HEAD request did not return success: ", resp.StatusCode)
|
||||
}
|
||||
|
||||
if resp.Header.Get("Content-Type") != "application/octet-stream" {
|
||||
t.Error("Content Type Header is unexpected: ", resp.Header.Get("Content-Type"))
|
||||
}
|
||||
|
||||
if resp.Bytes() != nil {
|
||||
t.Error("Somehow byte buffer is working now (bytes)", resp.Bytes())
|
||||
}
|
||||
|
||||
if resp.String() != "" {
|
||||
t.Error("Somehow byte buffer is working now (bytes)", resp.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHeadSession(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
resp, err := session.Head("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"one": "two"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
resp, err = session.Head("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"two": "three"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
resp, err = session.Head("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"three": "four"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
cookieURL, err := url.Parse("http://httpbin.org")
|
||||
if err != nil {
|
||||
t.Error("We (for some reason) cannot parse the cookie URL")
|
||||
}
|
||||
|
||||
if len(session.HTTPClient.Jar.Cookies(cookieURL)) != 3 {
|
||||
t.Error("Invalid number of cookies provided: ", session.HTTPClient.Jar.Cookies(cookieURL))
|
||||
}
|
||||
|
||||
for _, cookie := range session.HTTPClient.Jar.Cookies(cookieURL) {
|
||||
switch cookie.Name {
|
||||
case "one":
|
||||
if cookie.Value != "two" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
case "two":
|
||||
if cookie.Value != "three" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
case "three":
|
||||
if cookie.Value != "four" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
default:
|
||||
t.Error("We should not have any other cookies: ", cookie)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestHeadInvalidURLSession(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
if _, err := session.Head("%../dir/", nil); err == nil {
|
||||
t.Error("Some how the request was valid to make request ", err)
|
||||
}
|
||||
}
|
|
@ -1,88 +0,0 @@
|
|||
package grequests
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBasicOPTIONSRequest(t *testing.T) {
|
||||
resp, err := Options("http://httpbin.org/get", nil)
|
||||
if err != nil {
|
||||
t.Error("Unable to make OPTIONS request: ", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Options request did not return success: ", resp.StatusCode)
|
||||
}
|
||||
|
||||
if resp.Header.Get("Access-Control-Allow-Methods") != "GET, POST, PUT, DELETE, PATCH, OPTIONS" {
|
||||
t.Error("Access-Control-Allow-Methods Type Header is unexpected: ", resp.Header)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptionsSession(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
resp, err := session.Options("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"one": "two"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
resp, err = session.Options("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"two": "three"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
resp, err = session.Options("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"three": "four"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
cookieURL, err := url.Parse("http://httpbin.org")
|
||||
if err != nil {
|
||||
t.Error("We (for some reason) cannot parse the cookie URL")
|
||||
}
|
||||
|
||||
for _, cookie := range session.HTTPClient.Jar.Cookies(cookieURL) {
|
||||
switch cookie.Name {
|
||||
case "one":
|
||||
if cookie.Value != "two" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
case "two":
|
||||
if cookie.Value != "three" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
case "three":
|
||||
if cookie.Value != "four" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
default:
|
||||
t.Error("We should not have any other cookies: ", cookie)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestOptionsInvalidURLSession(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
if _, err := session.Options("%../dir/", nil); err == nil {
|
||||
t.Error("Some how the request was valid to make request ", err)
|
||||
}
|
||||
}
|
|
@ -1,99 +0,0 @@
|
|||
package grequests
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBasicPatchRequest(t *testing.T) {
|
||||
resp, err := Patch("http://httpbin.org/patch", nil)
|
||||
|
||||
if err != nil {
|
||||
t.Error("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchSession(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
resp, err := session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"one": "two"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"two": "three"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"three": "four"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
resp, err = session.Patch("http://httpbin.org/patch", &RequestOptions{Params: map[string]string{"one": "two"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK: ", resp.String())
|
||||
}
|
||||
|
||||
cookieURL, err := url.Parse("http://httpbin.org")
|
||||
if err != nil {
|
||||
t.Error("We (for some reason) cannot parse the cookie URL")
|
||||
}
|
||||
|
||||
if len(session.HTTPClient.Jar.Cookies(cookieURL)) != 3 {
|
||||
t.Error("Invalid number of cookies provided: ", session.HTTPClient.Jar.Cookies(cookieURL))
|
||||
}
|
||||
|
||||
for _, cookie := range session.HTTPClient.Jar.Cookies(cookieURL) {
|
||||
switch cookie.Name {
|
||||
case "one":
|
||||
if cookie.Value != "two" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
case "two":
|
||||
if cookie.Value != "three" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
case "three":
|
||||
if cookie.Value != "four" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
default:
|
||||
t.Error("We should not have any other cookies: ", cookie)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestPatchInvalidURLSession(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
if _, err := session.Patch("%../dir/", nil); err == nil {
|
||||
t.Error("Some how the request was valid to make request ", err)
|
||||
}
|
||||
}
|
|
@ -1,948 +0,0 @@
|
|||
package grequests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type BasicPostResponse struct {
|
||||
Args struct{} `json:"args"`
|
||||
Data string `json:"data"`
|
||||
Files struct{} `json:"files"`
|
||||
Form struct {
|
||||
One string `json:"one"`
|
||||
} `json:"form"`
|
||||
Headers struct {
|
||||
Accept string `json:"Accept"`
|
||||
ContentLength string `json:"Content-Length"`
|
||||
ContentType string `json:"Content-Type"`
|
||||
Host string `json:"Host"`
|
||||
UserAgent string `json:"User-Agent"`
|
||||
} `json:"headers"`
|
||||
JSON interface{} `json:"json"`
|
||||
Origin string `json:"origin"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
type BasicPostJSONResponse struct {
|
||||
Args struct{} `json:"args"`
|
||||
Data string `json:"data"`
|
||||
Files struct{} `json:"files"`
|
||||
Form struct{} `json:"form"`
|
||||
Headers struct {
|
||||
AcceptEncoding string `json:"Accept-Encoding"`
|
||||
ContentLength string `json:"Content-Length"`
|
||||
ContentType string `json:"Content-Type"`
|
||||
Host string `json:"Host"`
|
||||
UserAgent string `json:"User-Agent"`
|
||||
XRequestedWith string `json:"X-Requested-With"`
|
||||
} `json:"headers"`
|
||||
JSON struct {
|
||||
One string `json:"One"`
|
||||
} `json:"json"`
|
||||
Origin string `json:"origin"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
type BasicMultiFileUploadResponse struct {
|
||||
Args struct{} `json:"args"`
|
||||
Data string `json:"data"`
|
||||
Files struct {
|
||||
File1 string `json:"file1"`
|
||||
File2 string `json:"file2"`
|
||||
} `json:"files"`
|
||||
Form struct {
|
||||
One string `json:"One"`
|
||||
} `json:"form"`
|
||||
Headers struct {
|
||||
AcceptEncoding string `json:"Accept-Encoding"`
|
||||
ContentLength string `json:"Content-Length"`
|
||||
ContentType string `json:"Content-Type"`
|
||||
Host string `json:"Host"`
|
||||
UserAgent string `json:"User-Agent"`
|
||||
} `json:"headers"`
|
||||
JSON interface{} `json:"json"`
|
||||
Origin string `json:"origin"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
type BasicPostFileUpload struct {
|
||||
Args struct{} `json:"args"`
|
||||
Data string `json:"data"`
|
||||
Files struct {
|
||||
File string `json:"file"`
|
||||
} `json:"files"`
|
||||
Form struct {
|
||||
One string `json:"one"`
|
||||
} `json:"form"`
|
||||
Headers struct {
|
||||
AcceptEncoding string `json:"Accept-Encoding"`
|
||||
ContentLength string `json:"Content-Length"`
|
||||
ContentType string `json:"Content-Type"`
|
||||
Host string `json:"Host"`
|
||||
UserAgent string `json:"User-Agent"`
|
||||
} `json:"headers"`
|
||||
JSON interface{} `json:"json"`
|
||||
Origin string `json:"origin"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
type XMLPostMessage struct {
|
||||
Name string
|
||||
Age int
|
||||
Height int
|
||||
}
|
||||
|
||||
type dataAndErrorBuffer struct {
|
||||
err error
|
||||
bytes.Buffer
|
||||
}
|
||||
|
||||
func (dataAndErrorBuffer) Close() error { return nil }
|
||||
|
||||
func (r dataAndErrorBuffer) Read(p []byte) (n int, err error) {
|
||||
return 0, r.err
|
||||
}
|
||||
|
||||
func TestBasicPostRequest(t *testing.T) {
|
||||
resp, _ := Post("http://httpbin.org/post",
|
||||
&RequestOptions{Data: map[string]string{"One": "Two"}})
|
||||
verifyOkPostResponse(resp, t)
|
||||
|
||||
}
|
||||
|
||||
func TestBasicRegularPostRequest(t *testing.T) {
|
||||
resp, err := Post("http://httpbin.org/post",
|
||||
&RequestOptions{Data: map[string]string{"One": "Two"}})
|
||||
|
||||
if err != nil {
|
||||
t.Error("Cannot post: ", err)
|
||||
}
|
||||
|
||||
verifyOkPostResponse(resp, t)
|
||||
|
||||
}
|
||||
|
||||
func TestBasicPostRequestInvalidURL(t *testing.T) {
|
||||
resp, _ := Post("%../dir/",
|
||||
&RequestOptions{Data: map[string]string{"One": "Two"},
|
||||
Params: map[string]string{"1": "2"}})
|
||||
|
||||
if resp.Error == nil {
|
||||
t.Error("Somehow the request went through")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestBasicPostRequestInvalidURLNoParams(t *testing.T) {
|
||||
resp, _ := Post("%../dir/", &RequestOptions{Data: map[string]string{"One": "Two"}})
|
||||
|
||||
if resp.Error == nil {
|
||||
t.Error("Somehow the request went through")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestSessionPostRequestInvalidURLNoParams(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
if _, err := session.Post("%../dir/", &RequestOptions{Data: map[string]string{"One": "Two"}}); err == nil {
|
||||
t.Error("Somehow the request went through")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestXMLPostRequestInvalidURL(t *testing.T) {
|
||||
resp, _ := Post("%../dir/",
|
||||
&RequestOptions{XML: XMLPostMessage{Name: "Human", Age: 1, Height: 1}})
|
||||
|
||||
if resp.Error == nil {
|
||||
t.Error("Somehow the request went through")
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMLSessionPostRequestInvalidURL(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
_, err := session.Post("%../dir/",
|
||||
&RequestOptions{XML: XMLPostMessage{Name: "Human", Age: 1, Height: 1}})
|
||||
|
||||
if err == nil {
|
||||
t.Error("Somehow the request went through")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBasicPostJsonRequestInvalidURL(t *testing.T) {
|
||||
_, err := Post("%../dir/",
|
||||
&RequestOptions{JSON: map[string]string{"One": "Two"}, IsAjax: true})
|
||||
|
||||
if err == nil {
|
||||
t.Error("Somehow the request went through")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionPostJsonRequestInvalidURL(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
_, err := session.Post("%../dir/",
|
||||
&RequestOptions{JSON: map[string]string{"One": "Two"}, IsAjax: true})
|
||||
|
||||
if err == nil {
|
||||
t.Error("Somehow the request went through")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBasicPostJsonRequestInvalidJSON(t *testing.T) {
|
||||
resp, err := Post("http://httpbin.org/post",
|
||||
&RequestOptions{JSON: math.NaN(), IsAjax: true})
|
||||
|
||||
if err == nil {
|
||||
t.Error("Somehow the request went through")
|
||||
}
|
||||
|
||||
if resp.Ok == true {
|
||||
t.Error("Somehow the request is OK")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionPostJsonRequestInvalidJSON(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
resp, err := session.Post("http://httpbin.org/post",
|
||||
&RequestOptions{JSON: math.NaN(), IsAjax: true})
|
||||
|
||||
if err == nil {
|
||||
t.Error("Somehow the request went through")
|
||||
}
|
||||
|
||||
if resp.Ok == true {
|
||||
t.Error("Somehow the request is OK")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBasicPostJsonRequestInvalidXML(t *testing.T) {
|
||||
resp, err := Post("http://httpbin.org/post",
|
||||
&RequestOptions{XML: map[string]string{"One": "two"}, IsAjax: true})
|
||||
|
||||
if err == nil {
|
||||
t.Error("Somehow the request went through")
|
||||
}
|
||||
|
||||
if resp.Ok == true {
|
||||
t.Error("Somehow the request is OK")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionPostJsonRequestInvalidXML(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
resp, err := session.Post("http://httpbin.org/post",
|
||||
&RequestOptions{XML: map[string]string{"One": "two"}, IsAjax: true})
|
||||
|
||||
if err == nil {
|
||||
t.Error("Somehow the request went through")
|
||||
}
|
||||
|
||||
if resp.Ok == true {
|
||||
t.Error("Somehow the request is OK")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBasicPostRequestUploadInvalidURL(t *testing.T) {
|
||||
|
||||
fd, err := FileUploadFromDisk("testdata/mypassword")
|
||||
|
||||
if err != nil {
|
||||
t.Error("Unable to open file: ", err)
|
||||
}
|
||||
|
||||
defer fd[0].FileContents.Close()
|
||||
|
||||
resp, _ := Post("%../dir/",
|
||||
&RequestOptions{
|
||||
Files: fd,
|
||||
Data: map[string]string{"One": "Two"},
|
||||
})
|
||||
|
||||
if resp.Error == nil {
|
||||
t.Fatal("Somehow able to make the request")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionPostRequestUploadInvalidURL(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
fd, err := FileUploadFromDisk("testdata/mypassword")
|
||||
|
||||
if err != nil {
|
||||
t.Error("Unable to open file: ", err)
|
||||
}
|
||||
|
||||
defer fd[0].FileContents.Close()
|
||||
|
||||
_, err = session.Post("%../dir/",
|
||||
&RequestOptions{
|
||||
Files: fd,
|
||||
Data: map[string]string{"One": "Two"},
|
||||
})
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("Somehow able to make the request")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBasicPostRequestUploadInvalidFileUpload(t *testing.T) {
|
||||
|
||||
resp, _ := Post("%../dir/",
|
||||
&RequestOptions{
|
||||
Files: []FileUpload{{FileName: `\x00%'"üfdsufhid\Ä\"D\\\"JS%25//'"H•\\\\'"¶•ªç∂\uf8\x8AKÔÓÔ`, FileContents: nil}},
|
||||
Data: map[string]string{"One": "Two"},
|
||||
})
|
||||
|
||||
if resp.Error == nil {
|
||||
t.Fatal("Somehow able to make the request")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionPostRequestUploadInvalidFileUpload(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
_, err := session.Post("%../dir/",
|
||||
&RequestOptions{
|
||||
Files: []FileUpload{{FileName: "üfdsufhidÄDJSHAKÔÓÔ", FileContents: nil}},
|
||||
Data: map[string]string{"One": "Two"},
|
||||
})
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("Somehow able to make the request")
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMLPostRequest(t *testing.T) {
|
||||
resp, _ := Post("http://httpbin.org/post",
|
||||
&RequestOptions{XML: XMLPostMessage{Name: "Human", Age: 1, Height: 1}})
|
||||
|
||||
if resp.Error != nil {
|
||||
t.Fatal("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
myJSONStruct := &BasicPostJSONResponse{}
|
||||
|
||||
if err := resp.JSON(myJSONStruct); err != nil {
|
||||
t.Error("Unable to coerce to JSON", err)
|
||||
}
|
||||
|
||||
myXMLStruct := &XMLPostMessage{}
|
||||
|
||||
xml.Unmarshal([]byte(myJSONStruct.Data), myXMLStruct)
|
||||
|
||||
if myXMLStruct.Age != 1 {
|
||||
t.Errorf("Unable to serialize XML response from within JSON %#v ", myXMLStruct)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestXMLPostRequestReaderBody(t *testing.T) {
|
||||
msg := XMLPostMessage{Name: "Human", Age: 1, Height: 1}
|
||||
derBytes, err := xml.Marshal(msg)
|
||||
if err != nil {
|
||||
t.Fatal("Unable to marshal XML", err)
|
||||
}
|
||||
|
||||
resp, _ := Post("http://httpbin.org/post",
|
||||
&RequestOptions{RequestBody: bytes.NewReader(derBytes)})
|
||||
|
||||
if resp.Error != nil {
|
||||
t.Fatal("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
myJSONStruct := &BasicPostJSONResponse{}
|
||||
|
||||
if err := resp.JSON(myJSONStruct); err != nil {
|
||||
t.Error("Unable to coerce to JSON", err)
|
||||
}
|
||||
|
||||
myXMLStruct := &XMLPostMessage{}
|
||||
|
||||
xml.Unmarshal([]byte(myJSONStruct.Data), myXMLStruct)
|
||||
|
||||
if myXMLStruct.Age != 1 {
|
||||
t.Errorf("Unable to serialize XML response from within JSON %#v ", myXMLStruct)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestXMLMarshaledStringPostRequest(t *testing.T) {
|
||||
xmlStruct := XMLPostMessage{Name: "Human", Age: 1, Height: 1}
|
||||
encoded, _ := xml.Marshal(xmlStruct)
|
||||
resp, _ := Post("http://httpbin.org/post",
|
||||
&RequestOptions{XML: string(encoded)})
|
||||
|
||||
if resp.Error != nil {
|
||||
t.Fatal("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
myJSONStruct := &BasicPostJSONResponse{}
|
||||
if err := resp.JSON(myJSONStruct); err != nil {
|
||||
t.Error("Unable to response to JSON", err)
|
||||
}
|
||||
|
||||
if myJSONStruct.Data != string(encoded) {
|
||||
t.Error("Response is not valid", myJSONStruct.Data, string(encoded))
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMLMarshaledBytesPostRequest(t *testing.T) {
|
||||
xmlStruct := XMLPostMessage{Name: "Human", Age: 1, Height: 1}
|
||||
encoded, _ := xml.Marshal(xmlStruct)
|
||||
resp, _ := Post("http://httpbin.org/post",
|
||||
&RequestOptions{XML: encoded})
|
||||
|
||||
if resp.Error != nil {
|
||||
t.Fatal("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
myJSONStruct := &BasicPostJSONResponse{}
|
||||
if err := resp.JSON(myJSONStruct); err != nil {
|
||||
t.Error("Unable to response to JSON", err)
|
||||
}
|
||||
|
||||
if myJSONStruct.Data != string(encoded) {
|
||||
t.Error("Response is not valid", myJSONStruct.Data, string(encoded))
|
||||
}
|
||||
}
|
||||
|
||||
func TestXMLNilPostRequest(t *testing.T) {
|
||||
resp, _ := Post("http://httpbin.org/post", &RequestOptions{XML: nil})
|
||||
|
||||
if resp.Error != nil {
|
||||
t.Fatal("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
myJSONStruct := &BasicPostJSONResponse{}
|
||||
if err := resp.JSON(myJSONStruct); err != nil {
|
||||
t.Error("Unable to response to JSON", err)
|
||||
}
|
||||
|
||||
if myJSONStruct.Data != "" {
|
||||
t.Error("Response is not valid", myJSONStruct.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBasicPostRequestUploadErrorReader(t *testing.T) {
|
||||
var rd dataAndErrorBuffer
|
||||
rd.err = fmt.Errorf("Random Error")
|
||||
_, err := Post("http://httpbin.org/post",
|
||||
&RequestOptions{
|
||||
Files: []FileUpload{{FileName: "Random.test", FileContents: rd}},
|
||||
Data: map[string]string{"One": "Two"},
|
||||
})
|
||||
|
||||
if err == nil {
|
||||
t.Error("Somehow our test didn't fail...")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBasicPostRequestUploadErrorEOFReader(t *testing.T) {
|
||||
var rd dataAndErrorBuffer
|
||||
rd.err = io.EOF
|
||||
_, err := Post("http://httpbin.org/post",
|
||||
&RequestOptions{
|
||||
Files: []FileUpload{{FileName: "Random.test", FileContents: rd}},
|
||||
Data: map[string]string{"One": "Two"},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Error("Somehow our test didn't fail... ", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBasicPostRequestUpload(t *testing.T) {
|
||||
|
||||
fd, err := FileUploadFromDisk("testdata/mypassword")
|
||||
|
||||
if err != nil {
|
||||
t.Error("Unable to open file: ", err)
|
||||
}
|
||||
|
||||
resp, _ := Post("http://httpbin.org/post",
|
||||
&RequestOptions{
|
||||
Files: fd,
|
||||
Data: map[string]string{"One": "Two"},
|
||||
})
|
||||
|
||||
if resp.Error != nil {
|
||||
t.Fatal("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
myJSONStruct := &BasicPostFileUpload{}
|
||||
|
||||
if err := resp.JSON(myJSONStruct); err != nil {
|
||||
t.Error("Unable to coerce to JSON", err)
|
||||
}
|
||||
|
||||
if myJSONStruct.URL != "http://httpbin.org/post" {
|
||||
t.Error("For some reason the URL isn't the same", myJSONStruct.URL)
|
||||
}
|
||||
|
||||
if myJSONStruct.Headers.Host != "httpbin.org" {
|
||||
t.Error("The host header is invalid")
|
||||
}
|
||||
|
||||
if myJSONStruct.Files.File != "saucy sauce" {
|
||||
t.Error("File upload contents have been modified: ", myJSONStruct.Files.File)
|
||||
}
|
||||
|
||||
if resp.Bytes() != nil {
|
||||
t.Error("JSON decoding did not fully consume the response stream (Bytes)", resp.Bytes())
|
||||
}
|
||||
|
||||
if resp.String() != "" {
|
||||
t.Error("JSON decoding did not fully consume the response stream (String)", resp.String())
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
t.Error("Response returned a non-200 code")
|
||||
}
|
||||
|
||||
if myJSONStruct.Form.One != "Two" {
|
||||
t.Error("Unable to parse form properly", myJSONStruct.Form)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBasicPostRequestUploadWithMime(t *testing.T) {
|
||||
|
||||
fd, err := os.Open("testdata/mypassword")
|
||||
|
||||
if err != nil {
|
||||
t.Error("Unable to open file: ", err)
|
||||
}
|
||||
|
||||
resp, _ := Post("http://httpbin.org/post",
|
||||
&RequestOptions{
|
||||
Files: []FileUpload{{FileContents: fd, FileMime: "text/plain"}},
|
||||
Data: map[string]string{"One": "Two"},
|
||||
})
|
||||
|
||||
if resp.Error != nil {
|
||||
t.Fatal("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
myJSONStruct := &BasicPostFileUpload{}
|
||||
|
||||
if err := resp.JSON(myJSONStruct); err != nil {
|
||||
t.Error("Unable to coerce to JSON", err)
|
||||
}
|
||||
|
||||
if myJSONStruct.URL != "http://httpbin.org/post" {
|
||||
t.Error("For some reason the URL isn't the same", myJSONStruct.URL)
|
||||
}
|
||||
|
||||
if myJSONStruct.Headers.Host != "httpbin.org" {
|
||||
t.Error("The host header is invalid")
|
||||
}
|
||||
|
||||
if myJSONStruct.Files.File != "saucy sauce" {
|
||||
t.Error("File upload contents have been modified: ", myJSONStruct.Files.File)
|
||||
}
|
||||
|
||||
if resp.Bytes() != nil {
|
||||
t.Error("JSON decoding did not fully consume the response stream (Bytes)", resp.Bytes())
|
||||
}
|
||||
|
||||
if resp.String() != "" {
|
||||
t.Error("JSON decoding did not fully consume the response stream (String)", resp.String())
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
t.Error("Response returned a non-200 code")
|
||||
}
|
||||
|
||||
if myJSONStruct.Form.One != "Two" {
|
||||
t.Error("Unable to parse form properly", myJSONStruct.Form)
|
||||
}
|
||||
|
||||
// TODO: Ensure file field contains correct content-type, field, and
|
||||
// filename information as soon as
|
||||
// https://github.com/kennethreitz/httpbin/pull/388 gets merged
|
||||
// (Or figure out a way to test this case the PR is rejected)
|
||||
}
|
||||
|
||||
func TestBasicPostRequestUploadMultipleFiles(t *testing.T) {
|
||||
|
||||
fd, err := FileUploadFromGlob("testdata/*")
|
||||
|
||||
if err != nil {
|
||||
t.Error("Unable to glob file: ", err)
|
||||
}
|
||||
|
||||
resp, _ := Post("http://httpbin.org/post",
|
||||
&RequestOptions{
|
||||
Files: fd,
|
||||
Data: map[string]string{"One": "Two"},
|
||||
})
|
||||
|
||||
if resp.Error != nil {
|
||||
t.Fatal("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
myJSONStruct := &BasicMultiFileUploadResponse{}
|
||||
|
||||
if err := resp.JSON(myJSONStruct); err != nil {
|
||||
t.Error("Unable to coerce to JSON", err)
|
||||
}
|
||||
|
||||
if myJSONStruct.URL != "http://httpbin.org/post" {
|
||||
t.Error("For some reason the URL isn't the same", myJSONStruct.URL)
|
||||
}
|
||||
|
||||
if myJSONStruct.Headers.Host != "httpbin.org" {
|
||||
t.Error("The host header is invalid")
|
||||
}
|
||||
|
||||
if myJSONStruct.Files.File2 != "saucy sauce" {
|
||||
t.Error("File upload contents have been modified: ", myJSONStruct.Files.File2)
|
||||
}
|
||||
if myJSONStruct.Files.File1 != "I am just here to test the glob" {
|
||||
t.Error("File upload contents have been modified: ", myJSONStruct.Files.File1)
|
||||
}
|
||||
|
||||
if resp.Bytes() != nil {
|
||||
t.Error("JSON decoding did not fully consume the response stream (Bytes)", resp.Bytes())
|
||||
}
|
||||
|
||||
if resp.String() != "" {
|
||||
t.Error("JSON decoding did not fully consume the response stream (String)", resp.String())
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
t.Error("Response returned a non-200 code")
|
||||
}
|
||||
|
||||
if myJSONStruct.Form.One != "Two" {
|
||||
t.Error("Unable to parse form properly", myJSONStruct.Form)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestBasicPostJsonBytesRequest(t *testing.T) {
|
||||
resp, _ := Post("http://httpbin.org/post",
|
||||
&RequestOptions{JSON: []byte(`{"One":"Two"}`), IsAjax: true})
|
||||
|
||||
if resp.Error != nil {
|
||||
t.Fatal("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
myJSONStruct := &BasicPostJSONResponse{}
|
||||
|
||||
if err := resp.JSON(myJSONStruct); err != nil {
|
||||
t.Error("Unable to coerce to JSON", err)
|
||||
}
|
||||
|
||||
if myJSONStruct.URL != "http://httpbin.org/post" {
|
||||
t.Error("For some reason the URL isn't the same", myJSONStruct.URL)
|
||||
}
|
||||
|
||||
if myJSONStruct.Headers.Host != "httpbin.org" {
|
||||
t.Error("The host header is invalid")
|
||||
}
|
||||
|
||||
if myJSONStruct.JSON.One != "Two" {
|
||||
t.Error("Invalid post response: ", myJSONStruct.JSON.One)
|
||||
}
|
||||
|
||||
if strings.TrimSpace(myJSONStruct.Data) != `{"One":"Two"}` {
|
||||
t.Error("JSON not properly returned: ", myJSONStruct.Data)
|
||||
}
|
||||
|
||||
if resp.Bytes() != nil {
|
||||
t.Error("JSON decoding did not fully consume the response stream (Bytes)", resp.Bytes())
|
||||
}
|
||||
|
||||
if resp.String() != "" {
|
||||
t.Error("JSON decoding did not fully consume the response stream (String)", resp.String())
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
t.Error("Response returned a non-200 code")
|
||||
}
|
||||
|
||||
if myJSONStruct.Headers.XRequestedWith != "XMLHttpRequest" {
|
||||
t.Error("Invalid requested header: ", myJSONStruct.Headers.XRequestedWith)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestBasicPostJsonStringRequest(t *testing.T) {
|
||||
resp, _ := Post("http://httpbin.org/post",
|
||||
&RequestOptions{JSON: `{"One":"Two"}`, IsAjax: true})
|
||||
|
||||
if resp.Error != nil {
|
||||
t.Fatal("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
myJSONStruct := &BasicPostJSONResponse{}
|
||||
|
||||
if err := resp.JSON(myJSONStruct); err != nil {
|
||||
t.Error("Unable to coerce to JSON", err)
|
||||
}
|
||||
|
||||
if myJSONStruct.URL != "http://httpbin.org/post" {
|
||||
t.Error("For some reason the URL isn't the same", myJSONStruct.URL)
|
||||
}
|
||||
|
||||
if myJSONStruct.Headers.Host != "httpbin.org" {
|
||||
t.Error("The host header is invalid")
|
||||
}
|
||||
|
||||
if myJSONStruct.JSON.One != "Two" {
|
||||
t.Error("Invalid post response: ", myJSONStruct.JSON.One)
|
||||
}
|
||||
|
||||
if strings.TrimSpace(myJSONStruct.Data) != `{"One":"Two"}` {
|
||||
t.Error("JSON not properly returned: ", myJSONStruct.Data)
|
||||
}
|
||||
|
||||
if resp.Bytes() != nil {
|
||||
t.Error("JSON decoding did not fully consume the response stream (Bytes)", resp.Bytes())
|
||||
}
|
||||
|
||||
if resp.String() != "" {
|
||||
t.Error("JSON decoding did not fully consume the response stream (String)", resp.String())
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
t.Error("Response returned a non-200 code")
|
||||
}
|
||||
|
||||
if myJSONStruct.Headers.XRequestedWith != "XMLHttpRequest" {
|
||||
t.Error("Invalid requested header: ", myJSONStruct.Headers.XRequestedWith)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestBasicPostJsonRequest(t *testing.T) {
|
||||
resp, _ := Post("http://httpbin.org/post",
|
||||
&RequestOptions{JSON: map[string]string{"One": "Two"}, IsAjax: true})
|
||||
|
||||
if resp.Error != nil {
|
||||
t.Fatal("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
myJSONStruct := &BasicPostJSONResponse{}
|
||||
|
||||
if err := resp.JSON(myJSONStruct); err != nil {
|
||||
t.Error("Unable to coerce to JSON", err)
|
||||
}
|
||||
|
||||
if myJSONStruct.URL != "http://httpbin.org/post" {
|
||||
t.Error("For some reason the URL isn't the same", myJSONStruct.URL)
|
||||
}
|
||||
|
||||
if myJSONStruct.Headers.Host != "httpbin.org" {
|
||||
t.Error("The host header is invalid")
|
||||
}
|
||||
|
||||
if myJSONStruct.JSON.One != "Two" {
|
||||
t.Error("Invalid post response: ", myJSONStruct.JSON.One)
|
||||
}
|
||||
|
||||
if strings.TrimSpace(myJSONStruct.Data) != `{"One":"Two"}` {
|
||||
t.Error("JSON not properly returned: ", myJSONStruct.Data)
|
||||
}
|
||||
|
||||
if resp.Bytes() != nil {
|
||||
t.Error("JSON decoding did not fully consume the response stream (Bytes)", resp.Bytes())
|
||||
}
|
||||
|
||||
if resp.String() != "" {
|
||||
t.Error("JSON decoding did not fully consume the response stream (String)", resp.String())
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
t.Error("Response returned a non-200 code")
|
||||
}
|
||||
|
||||
if myJSONStruct.Headers.XRequestedWith != "XMLHttpRequest" {
|
||||
t.Error("Invalid requested header: ", myJSONStruct.Headers.XRequestedWith)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestPostSession(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
resp, err := session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"one": "two"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"two": "three"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"three": "four"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
resp, err = session.Post("http://httpbin.org/post", &RequestOptions{Data: map[string]string{"one": "two"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
cookieURL, err := url.Parse("http://httpbin.org")
|
||||
if err != nil {
|
||||
t.Error("We (for some reason) cannot parse the cookie URL")
|
||||
}
|
||||
|
||||
if len(session.HTTPClient.Jar.Cookies(cookieURL)) != 3 {
|
||||
t.Error("Invalid number of cookies provided: ", session.HTTPClient.Jar.Cookies(cookieURL))
|
||||
}
|
||||
|
||||
for _, cookie := range session.HTTPClient.Jar.Cookies(cookieURL) {
|
||||
switch cookie.Name {
|
||||
case "one":
|
||||
if cookie.Value != "two" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
case "two":
|
||||
if cookie.Value != "three" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
case "three":
|
||||
if cookie.Value != "four" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
default:
|
||||
t.Error("We should not have any other cookies: ", cookie)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// verifyResponse will verify the following conditions
|
||||
// 1. The request didn't return an error
|
||||
// 2. The response returned an OK (a status code within the 200 range)
|
||||
// 3. The output can be coerced to JSON (this may change later)
|
||||
// It should only be run when testing GET request to http://httpbin.org/post expecting JSON
|
||||
func verifyOkPostResponse(resp *Response, t *testing.T) *BasicPostResponse {
|
||||
if resp.Error != nil {
|
||||
t.Fatal("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
myJSONStruct := &BasicPostResponse{}
|
||||
|
||||
if err := resp.JSON(myJSONStruct); err != nil {
|
||||
t.Error("Unable to coerce to JSON", err)
|
||||
}
|
||||
|
||||
if myJSONStruct.URL != "http://httpbin.org/post" {
|
||||
t.Error("For some reason the URL isn't the same", myJSONStruct.URL)
|
||||
}
|
||||
|
||||
if myJSONStruct.Headers.Host != "httpbin.org" {
|
||||
t.Error("The host header is invalid")
|
||||
}
|
||||
|
||||
if myJSONStruct.Form.One != "Two" {
|
||||
t.Errorf("Invalid post response: %#v", myJSONStruct.Form)
|
||||
}
|
||||
|
||||
if resp.Bytes() != nil {
|
||||
t.Error("JSON decoding did not fully consume the response stream (Bytes)", resp.Bytes())
|
||||
}
|
||||
|
||||
if resp.String() != "" {
|
||||
t.Error("JSON decoding did not fully consume the response stream (String)", resp.String())
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
t.Error("Response returned a non-200 code")
|
||||
}
|
||||
|
||||
return myJSONStruct
|
||||
}
|
||||
|
||||
func TestPostInvalidURLSession(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
if _, err := session.Post("%../dir/", nil); err == nil {
|
||||
t.Error("Some how the request was valid to make request ", err)
|
||||
}
|
||||
}
|
|
@ -1,163 +0,0 @@
|
|||
package grequests
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBasicPutRequest(t *testing.T) {
|
||||
resp, err := Put("http://httpbin.org/put", nil)
|
||||
|
||||
if err != nil {
|
||||
t.Error("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestBasicPutUploadRequest(t *testing.T) {
|
||||
t.Skip("httpbin.org is broken, as of https://github.com/kennethreitz/httpbin/issues/340#issuecomment-330176449")
|
||||
|
||||
fd, err := FileUploadFromDisk("testdata/mypassword")
|
||||
|
||||
if err != nil {
|
||||
t.Error("Unable to open file: ", err)
|
||||
}
|
||||
|
||||
resp, _ := Put("http://httpbin.org/put",
|
||||
&RequestOptions{
|
||||
Files: fd,
|
||||
Data: map[string]string{"One": "Two"},
|
||||
})
|
||||
|
||||
if resp.Error != nil {
|
||||
t.Error("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestBasicPutUploadRequestInvalidURL(t *testing.T) {
|
||||
fd, err := FileUploadFromDisk("testdata/mypassword")
|
||||
|
||||
if err != nil {
|
||||
t.Error("Unable to open file: ", err)
|
||||
}
|
||||
|
||||
_, err = Put("%../dir/",
|
||||
&RequestOptions{
|
||||
Files: fd,
|
||||
Data: map[string]string{"One": "Two"},
|
||||
})
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("Somehow able to make the request")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionPutUploadRequestInvalidURL(t *testing.T) {
|
||||
fd, err := FileUploadFromDisk("testdata/mypassword")
|
||||
|
||||
if err != nil {
|
||||
t.Error("Unable to open file: ", err)
|
||||
}
|
||||
|
||||
session := NewSession(nil)
|
||||
|
||||
_, err = session.Put("%../dir/",
|
||||
&RequestOptions{
|
||||
Files: fd,
|
||||
Data: map[string]string{"One": "Two"},
|
||||
})
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("Somehow able to make the request")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutSession(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
resp, err := session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"one": "two"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"two": "three"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
resp, err = session.Get("http://httpbin.org/cookies/set", &RequestOptions{Params: map[string]string{"three": "four"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
resp, err = session.Put("http://httpbin.org/put", &RequestOptions{Data: map[string]string{"one": "two"}})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Error("Request did not return OK")
|
||||
}
|
||||
|
||||
cookieURL, err := url.Parse("http://httpbin.org")
|
||||
if err != nil {
|
||||
t.Error("We (for some reason) cannot parse the cookie URL")
|
||||
}
|
||||
|
||||
if len(session.HTTPClient.Jar.Cookies(cookieURL)) != 3 {
|
||||
t.Error("Invalid number of cookies provided: ", session.HTTPClient.Jar.Cookies(cookieURL))
|
||||
}
|
||||
|
||||
for _, cookie := range session.HTTPClient.Jar.Cookies(cookieURL) {
|
||||
switch cookie.Name {
|
||||
case "one":
|
||||
if cookie.Value != "two" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
case "two":
|
||||
if cookie.Value != "three" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
case "three":
|
||||
if cookie.Value != "four" {
|
||||
t.Error("Cookie value is not valid", cookie)
|
||||
}
|
||||
default:
|
||||
t.Error("We should not have any other cookies: ", cookie)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestPutInvalidURLSession(t *testing.T) {
|
||||
session := NewSession(nil)
|
||||
|
||||
if _, err := session.Put("%../dir/", nil); err == nil {
|
||||
t.Error("Some how the request was valid to make request ", err)
|
||||
}
|
||||
}
|
|
@ -1,323 +0,0 @@
|
|||
package grequests_test
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/levigross/grequests"
|
||||
)
|
||||
|
||||
func Example_basicGet() {
|
||||
// This is a very basic GET request
|
||||
resp, err := grequests.Get("http://httpbin.org/get", nil)
|
||||
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
log.Println("Request did not return OK")
|
||||
}
|
||||
|
||||
log.Println(resp.String())
|
||||
}
|
||||
|
||||
func Example_basicGetCustomHTTPClient() {
|
||||
// This is a very basic GET request
|
||||
resp, err := grequests.Get("http://httpbin.org/get", &grequests.RequestOptions{HTTPClient: http.DefaultClient})
|
||||
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
log.Println("Request did not return OK")
|
||||
}
|
||||
|
||||
log.Println(resp.String())
|
||||
}
|
||||
|
||||
func Example_proxy() {
|
||||
proxyURL, err := url.Parse("http://127.0.0.1:8080") // Proxy URL
|
||||
if err != nil {
|
||||
log.Panicln(err)
|
||||
}
|
||||
|
||||
resp, err := grequests.Get("http://www.levigross.com/",
|
||||
&grequests.RequestOptions{Proxies: map[string]*url.URL{proxyURL.Scheme: proxyURL}})
|
||||
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
log.Println("Request did not return OK")
|
||||
}
|
||||
|
||||
log.Println(resp)
|
||||
}
|
||||
|
||||
func Example_cookies() {
|
||||
resp, err := grequests.Get("http://httpbin.org/cookies",
|
||||
&grequests.RequestOptions{
|
||||
Cookies: []*http.Cookie{
|
||||
{
|
||||
Name: "TestCookie",
|
||||
Value: "Random Value",
|
||||
HttpOnly: true,
|
||||
Secure: false,
|
||||
}, {
|
||||
Name: "AnotherCookie",
|
||||
Value: "Some Value",
|
||||
HttpOnly: true,
|
||||
Secure: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Println("Unable to make request", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
log.Println("Request did not return OK")
|
||||
}
|
||||
|
||||
log.Println(resp.String())
|
||||
}
|
||||
|
||||
func Example_session() {
|
||||
session := grequests.NewSession(nil)
|
||||
|
||||
resp, err := session.Get("http://httpbin.org/cookies/set", &grequests.RequestOptions{Params: map[string]string{"one": "two"}})
|
||||
|
||||
if err != nil {
|
||||
log.Fatal("Cannot set cookie: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
log.Println("Request did not return OK")
|
||||
}
|
||||
|
||||
log.Println(resp.String())
|
||||
|
||||
}
|
||||
|
||||
func Example_parse_XML() {
|
||||
type GetXMLSample struct {
|
||||
XMLName xml.Name `xml:"slideshow"`
|
||||
Title string `xml:"title,attr"`
|
||||
Date string `xml:"date,attr"`
|
||||
Author string `xml:"author,attr"`
|
||||
Slide []struct {
|
||||
Type string `xml:"type,attr"`
|
||||
Title string `xml:"title"`
|
||||
} `xml:"slide"`
|
||||
}
|
||||
|
||||
resp, err := grequests.Get("http://httpbin.org/xml", nil)
|
||||
|
||||
if err != nil {
|
||||
log.Println("Unable to make request", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
log.Println("Request did not return OK")
|
||||
}
|
||||
|
||||
userXML := &GetXMLSample{}
|
||||
|
||||
// func xmlASCIIDecoder(charset string, input io.Reader) (io.Reader, error) {
|
||||
// return input, nil
|
||||
// }
|
||||
|
||||
// If the server returns XML encoded in another charset (not UTF-8) – you
|
||||
// must provide an encoder function that looks like the one I wrote above.
|
||||
|
||||
// If you an consuming UTF-8 just pass `nil` into the second arg
|
||||
if err := resp.XML(userXML, xmlASCIIDecoder); err != nil {
|
||||
log.Println("Unable to consume the response as XML: ", err)
|
||||
}
|
||||
|
||||
if userXML.Title != "Sample Slide Show" {
|
||||
log.Printf("Invalid XML serialization %#v", userXML)
|
||||
}
|
||||
}
|
||||
|
||||
func Example_customUserAgent() {
|
||||
ro := &grequests.RequestOptions{UserAgent: "LeviBot 0.1"}
|
||||
resp, err := grequests.Get("http://httpbin.org/get", ro)
|
||||
|
||||
if err != nil {
|
||||
log.Fatal("Oops something went wrong: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
log.Println("Request did not return OK")
|
||||
}
|
||||
|
||||
log.Println(resp.String())
|
||||
}
|
||||
|
||||
func Example_basicAuth() {
|
||||
ro := &grequests.RequestOptions{Auth: []string{"Levi", "Bot"}}
|
||||
resp, err := grequests.Get("http://httpbin.org/get", ro)
|
||||
// Not the usual JSON so copy and paste from below
|
||||
|
||||
if err != nil {
|
||||
log.Println("Unable to make request", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
log.Println("Request did not return OK")
|
||||
}
|
||||
}
|
||||
|
||||
func Example_customHTTPHeader() {
|
||||
ro := &grequests.RequestOptions{UserAgent: "LeviBot 0.1",
|
||||
Headers: map[string]string{"X-Wonderful-Header": "1"}}
|
||||
resp, err := grequests.Get("http://httpbin.org/get", ro)
|
||||
// Not the usual JSON so copy and paste from below
|
||||
|
||||
if err != nil {
|
||||
log.Println("Unable to make request", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
log.Println("Request did not return OK")
|
||||
}
|
||||
}
|
||||
|
||||
func Example_acceptInvalidTLSCert() {
|
||||
ro := &grequests.RequestOptions{InsecureSkipVerify: true}
|
||||
resp, err := grequests.Get("https://www.pcwebshop.co.uk/", ro)
|
||||
|
||||
if err != nil {
|
||||
log.Println("Unable to make request", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
log.Println("Request did not return OK")
|
||||
}
|
||||
}
|
||||
|
||||
func Example_urlQueryParams() {
|
||||
ro := &grequests.RequestOptions{
|
||||
Params: map[string]string{"Hello": "World", "Goodbye": "World"},
|
||||
}
|
||||
resp, err := grequests.Get("http://httpbin.org/get", ro)
|
||||
// url will now be http://httpbin.org/get?hello=world&goodbye=world
|
||||
|
||||
if err != nil {
|
||||
log.Println("Unable to make request", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
log.Println("Request did not return OK")
|
||||
}
|
||||
}
|
||||
|
||||
func Example_downloadFile() {
|
||||
resp, err := grequests.Get("http://httpbin.org/get", nil)
|
||||
|
||||
if err != nil {
|
||||
log.Println("Unable to make request", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
log.Println("Request did not return OK")
|
||||
}
|
||||
|
||||
if err := resp.DownloadToFile("randomFile"); err != nil {
|
||||
log.Println("Unable to download to file: ", err)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
log.Println("Unable to download file", err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func Example_postForm() {
|
||||
resp, err := grequests.Post("http://httpbin.org/post",
|
||||
&grequests.RequestOptions{Data: map[string]string{"One": "Two"}})
|
||||
|
||||
// This is the basic form POST. The request body will be `one=two`
|
||||
|
||||
if err != nil {
|
||||
log.Println("Cannot post: ", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
log.Println("Request did not return OK")
|
||||
}
|
||||
}
|
||||
|
||||
func Example_postXML() {
|
||||
|
||||
type XMLPostMessage struct {
|
||||
Name string
|
||||
Age int
|
||||
Height int
|
||||
}
|
||||
|
||||
resp, err := grequests.Post("http://httpbin.org/post",
|
||||
&grequests.RequestOptions{XML: XMLPostMessage{Name: "Human", Age: 1, Height: 1}})
|
||||
// The request body will contain the XML generated by the `XMLPostMessage` struct
|
||||
|
||||
if err != nil {
|
||||
log.Println("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
log.Println("Request did not return OK")
|
||||
}
|
||||
}
|
||||
|
||||
func Example_postFileUpload() {
|
||||
|
||||
fd, err := grequests.FileUploadFromDisk("test_files/mypassword")
|
||||
|
||||
if err != nil {
|
||||
log.Println("Unable to open file: ", err)
|
||||
}
|
||||
|
||||
// This will upload the file as a multipart mime request
|
||||
resp, err := grequests.Post("http://httpbin.org/post",
|
||||
&grequests.RequestOptions{
|
||||
Files: fd,
|
||||
Data: map[string]string{"One": "Two"},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Println("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
log.Println("Request did not return OK")
|
||||
}
|
||||
}
|
||||
|
||||
func Example_postJSONAJAX() {
|
||||
resp, err := grequests.Post("http://httpbin.org/post",
|
||||
&grequests.RequestOptions{
|
||||
JSON: map[string]string{"One": "Two"},
|
||||
IsAjax: true, // this adds the X-Requested-With: XMLHttpRequest header
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
log.Println("Unable to make request", resp.Error)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
log.Println("Request did not return OK")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func xmlASCIIDecoder(charset string, input io.Reader) (io.Reader, error) {
|
||||
return input, nil
|
||||
}
|
|
@ -1,53 +0,0 @@
|
|||
package grequests
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestErrorOpenFile(t *testing.T) {
|
||||
fd, err := FileUploadFromDisk("I am Not A File")
|
||||
if err == nil {
|
||||
t.Error("We are not getting an error back from our non existent file: ")
|
||||
}
|
||||
|
||||
if fd != nil {
|
||||
t.Error("We actually got back a pointer: ", fd)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGLOBFiles(t *testing.T) {
|
||||
fd, err := FileUploadFromGlob("testdata/*")
|
||||
|
||||
if err != nil {
|
||||
t.Error("Got an invalid GLOB: ", err)
|
||||
}
|
||||
|
||||
if len(fd) != 2 {
|
||||
t.Error("Some how we have more than two files in our glob", len(fd), fd)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidGlob(t *testing.T) {
|
||||
if _, err := FileUploadFromGlob("[-]"); err == nil {
|
||||
t.Error("Somehow the glob worked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoGlobFiles(t *testing.T) {
|
||||
if _, err := FileUploadFromGlob("notapath"); err == nil {
|
||||
t.Error("Somehow got a valid GLOB")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGlobWithDir(t *testing.T) {
|
||||
fd, err := FileUploadFromGlob("*test*")
|
||||
|
||||
if err != nil {
|
||||
t.Error("Glob failed", err)
|
||||
}
|
||||
|
||||
for _, f := range fd {
|
||||
if f.FileName == "test_files" {
|
||||
t.Error(f, "is a dir (which cannot be uploaded)")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,39 +0,0 @@
|
|||
package grequests
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAddQueryStringParams(t *testing.T) {
|
||||
userURL, err := buildURLParams("https://www.google.com/", map[string]string{"1": "2", "3": "4"})
|
||||
|
||||
if err != nil {
|
||||
t.Error("URL Parse Error: ", err)
|
||||
}
|
||||
|
||||
if userURL != "https://www.google.com/?1=2&3=4" {
|
||||
t.Error("URL params not properly built", userURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSortAddQueryStringParams(t *testing.T) {
|
||||
userURL, err := buildURLParams("https://www.google.com/", map[string]string{"3": "4", "1": "2"})
|
||||
|
||||
if err != nil {
|
||||
t.Error("URL Parse Error: ", err)
|
||||
}
|
||||
|
||||
if userURL != "https://www.google.com/?1=2&3=4" {
|
||||
t.Error("URL params not properly built and sorted", userURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddQueryStringParamsExistingParam(t *testing.T) {
|
||||
userURL, err := buildURLParams("https://www.google.com/?5=6", map[string]string{"3": "4", "1": "2"})
|
||||
|
||||
if err != nil {
|
||||
t.Error("URL Parse Error: ", err)
|
||||
}
|
||||
|
||||
if userURL != "https://www.google.com/?1=2&3=4&5=6" {
|
||||
t.Error("URL params not properly built and sorted", userURL)
|
||||
}
|
||||
}
|
|
@ -1,26 +0,0 @@
|
|||
package grequests
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestResponseOk(t *testing.T) {
|
||||
status := []int{200, 201, 202, 203, 204, 205, 206, 207, 208, 226}
|
||||
for _, status := range status {
|
||||
verifyResponseOkForStatus(status, t)
|
||||
}
|
||||
}
|
||||
|
||||
func verifyResponseOkForStatus(status int, t *testing.T) {
|
||||
url := "http://httpbin.org/status/" + strconv.Itoa(status)
|
||||
resp, err := Get(url, nil)
|
||||
|
||||
if err != nil {
|
||||
t.Error("Unable to make request", err)
|
||||
}
|
||||
|
||||
if resp.Ok != true {
|
||||
t.Errorf("Request did not return OK. Received status code %d rather a 2xx.", resp.StatusCode)
|
||||
}
|
||||
}
|
|
@ -1 +0,0 @@
|
|||
I am just here to test the glob
|
|
@ -1 +0,0 @@
|
|||
saucy sauce
|
|
@ -1 +0,0 @@
|
|||
package grequests
|
|
@ -0,0 +1,24 @@
|
|||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
*.test
|
||||
*.prof
|
|
@ -0,0 +1,15 @@
|
|||
language: go
|
||||
go_import_path: github.com/pkg/errors
|
||||
go:
|
||||
- 1.4.x
|
||||
- 1.5.x
|
||||
- 1.6.x
|
||||
- 1.7.x
|
||||
- 1.8.x
|
||||
- 1.9.x
|
||||
- 1.10.x
|
||||
- 1.11.x
|
||||
- tip
|
||||
|
||||
script:
|
||||
- go test -v ./...
|
|
@ -1,63 +0,0 @@
|
|||
// +build go1.7
|
||||
|
||||
package errors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
stderrors "errors"
|
||||
)
|
||||
|
||||
func noErrors(at, depth int) error {
|
||||
if at >= depth {
|
||||
return stderrors.New("no error")
|
||||
}
|
||||
return noErrors(at+1, depth)
|
||||
}
|
||||
|
||||
func yesErrors(at, depth int) error {
|
||||
if at >= depth {
|
||||
return New("ye error")
|
||||
}
|
||||
return yesErrors(at+1, depth)
|
||||
}
|
||||
|
||||
// GlobalE is an exported global to store the result of benchmark results,
|
||||
// preventing the compiler from optimising the benchmark functions away.
|
||||
var GlobalE error
|
||||
|
||||
func BenchmarkErrors(b *testing.B) {
|
||||
type run struct {
|
||||
stack int
|
||||
std bool
|
||||
}
|
||||
runs := []run{
|
||||
{10, false},
|
||||
{10, true},
|
||||
{100, false},
|
||||
{100, true},
|
||||
{1000, false},
|
||||
{1000, true},
|
||||
}
|
||||
for _, r := range runs {
|
||||
part := "pkg/errors"
|
||||
if r.std {
|
||||
part = "errors"
|
||||
}
|
||||
name := fmt.Sprintf("%s-stack-%d", part, r.stack)
|
||||
b.Run(name, func(b *testing.B) {
|
||||
var err error
|
||||
f := yesErrors
|
||||
if r.std {
|
||||
f = noErrors
|
||||
}
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
err = f(0, r.stack)
|
||||
}
|
||||
b.StopTimer()
|
||||
GlobalE = err
|
||||
})
|
||||
}
|
||||
}
|
|
@ -1,251 +0,0 @@
|
|||
package errors
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
tests := []struct {
|
||||
err string
|
||||
want error
|
||||
}{
|
||||
{"", fmt.Errorf("")},
|
||||
{"foo", fmt.Errorf("foo")},
|
||||
{"foo", New("foo")},
|
||||
{"string with format specifiers: %v", errors.New("string with format specifiers: %v")},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := New(tt.err)
|
||||
if got.Error() != tt.want.Error() {
|
||||
t.Errorf("New.Error(): got: %q, want %q", got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrapNil(t *testing.T) {
|
||||
got := Wrap(nil, "no error")
|
||||
if got != nil {
|
||||
t.Errorf("Wrap(nil, \"no error\"): got %#v, expected nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrap(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
message string
|
||||
want string
|
||||
}{
|
||||
{io.EOF, "read error", "read error: EOF"},
|
||||
{Wrap(io.EOF, "read error"), "client error", "client error: read error: EOF"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := Wrap(tt.err, tt.message).Error()
|
||||
if got != tt.want {
|
||||
t.Errorf("Wrap(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type nilError struct{}
|
||||
|
||||
func (nilError) Error() string { return "nil error" }
|
||||
|
||||
func TestCause(t *testing.T) {
|
||||
x := New("error")
|
||||
tests := []struct {
|
||||
err error
|
||||
want error
|
||||
}{{
|
||||
// nil error is nil
|
||||
err: nil,
|
||||
want: nil,
|
||||
}, {
|
||||
// explicit nil error is nil
|
||||
err: (error)(nil),
|
||||
want: nil,
|
||||
}, {
|
||||
// typed nil is nil
|
||||
err: (*nilError)(nil),
|
||||
want: (*nilError)(nil),
|
||||
}, {
|
||||
// uncaused error is unaffected
|
||||
err: io.EOF,
|
||||
want: io.EOF,
|
||||
}, {
|
||||
// caused error returns cause
|
||||
err: Wrap(io.EOF, "ignored"),
|
||||
want: io.EOF,
|
||||
}, {
|
||||
err: x, // return from errors.New
|
||||
want: x,
|
||||
}, {
|
||||
WithMessage(nil, "whoops"),
|
||||
nil,
|
||||
}, {
|
||||
WithMessage(io.EOF, "whoops"),
|
||||
io.EOF,
|
||||
}, {
|
||||
WithStack(nil),
|
||||
nil,
|
||||
}, {
|
||||
WithStack(io.EOF),
|
||||
io.EOF,
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
got := Cause(tt.err)
|
||||
if !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("test %d: got %#v, want %#v", i+1, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrapfNil(t *testing.T) {
|
||||
got := Wrapf(nil, "no error")
|
||||
if got != nil {
|
||||
t.Errorf("Wrapf(nil, \"no error\"): got %#v, expected nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrapf(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
message string
|
||||
want string
|
||||
}{
|
||||
{io.EOF, "read error", "read error: EOF"},
|
||||
{Wrapf(io.EOF, "read error without format specifiers"), "client error", "client error: read error without format specifiers: EOF"},
|
||||
{Wrapf(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := Wrapf(tt.err, tt.message).Error()
|
||||
if got != tt.want {
|
||||
t.Errorf("Wrapf(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorf(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
{Errorf("read error without format specifiers"), "read error without format specifiers"},
|
||||
{Errorf("read error with %d format specifier", 1), "read error with 1 format specifier"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := tt.err.Error()
|
||||
if got != tt.want {
|
||||
t.Errorf("Errorf(%v): got: %q, want %q", tt.err, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithStackNil(t *testing.T) {
|
||||
got := WithStack(nil)
|
||||
if got != nil {
|
||||
t.Errorf("WithStack(nil): got %#v, expected nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithStack(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
{io.EOF, "EOF"},
|
||||
{WithStack(io.EOF), "EOF"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := WithStack(tt.err).Error()
|
||||
if got != tt.want {
|
||||
t.Errorf("WithStack(%v): got: %v, want %v", tt.err, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithMessageNil(t *testing.T) {
|
||||
got := WithMessage(nil, "no error")
|
||||
if got != nil {
|
||||
t.Errorf("WithMessage(nil, \"no error\"): got %#v, expected nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithMessage(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
message string
|
||||
want string
|
||||
}{
|
||||
{io.EOF, "read error", "read error: EOF"},
|
||||
{WithMessage(io.EOF, "read error"), "client error", "client error: read error: EOF"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := WithMessage(tt.err, tt.message).Error()
|
||||
if got != tt.want {
|
||||
t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithMessagefNil(t *testing.T) {
|
||||
got := WithMessagef(nil, "no error")
|
||||
if got != nil {
|
||||
t.Errorf("WithMessage(nil, \"no error\"): got %#v, expected nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithMessagef(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
message string
|
||||
want string
|
||||
}{
|
||||
{io.EOF, "read error", "read error: EOF"},
|
||||
{WithMessagef(io.EOF, "read error without format specifier"), "client error", "client error: read error without format specifier: EOF"},
|
||||
{WithMessagef(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := WithMessagef(tt.err, tt.message).Error()
|
||||
if got != tt.want {
|
||||
t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// errors.New, etc values are not expected to be compared by value
|
||||
// but the change in errors#27 made them incomparable. Assert that
|
||||
// various kinds of errors have a functional equality operator, even
|
||||
// if the result of that equality is always false.
|
||||
func TestErrorEquality(t *testing.T) {
|
||||
vals := []error{
|
||||
nil,
|
||||
io.EOF,
|
||||
errors.New("EOF"),
|
||||
New("EOF"),
|
||||
Errorf("EOF"),
|
||||
Wrap(io.EOF, "EOF"),
|
||||
Wrapf(io.EOF, "EOF%d", 2),
|
||||
WithMessage(nil, "whoops"),
|
||||
WithMessage(io.EOF, "whoops"),
|
||||
WithStack(io.EOF),
|
||||
WithStack(nil),
|
||||
}
|
||||
|
||||
for i := range vals {
|
||||
for j := range vals {
|
||||
_ = vals[i] == vals[j] // mustn't panic
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,205 +0,0 @@
|
|||
package errors_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
func ExampleNew() {
|
||||
err := errors.New("whoops")
|
||||
fmt.Println(err)
|
||||
|
||||
// Output: whoops
|
||||
}
|
||||
|
||||
func ExampleNew_printf() {
|
||||
err := errors.New("whoops")
|
||||
fmt.Printf("%+v", err)
|
||||
|
||||
// Example output:
|
||||
// whoops
|
||||
// github.com/pkg/errors_test.ExampleNew_printf
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:17
|
||||
// testing.runExample
|
||||
// /home/dfc/go/src/testing/example.go:114
|
||||
// testing.RunExamples
|
||||
// /home/dfc/go/src/testing/example.go:38
|
||||
// testing.(*M).Run
|
||||
// /home/dfc/go/src/testing/testing.go:744
|
||||
// main.main
|
||||
// /github.com/pkg/errors/_test/_testmain.go:106
|
||||
// runtime.main
|
||||
// /home/dfc/go/src/runtime/proc.go:183
|
||||
// runtime.goexit
|
||||
// /home/dfc/go/src/runtime/asm_amd64.s:2059
|
||||
}
|
||||
|
||||
func ExampleWithMessage() {
|
||||
cause := errors.New("whoops")
|
||||
err := errors.WithMessage(cause, "oh noes")
|
||||
fmt.Println(err)
|
||||
|
||||
// Output: oh noes: whoops
|
||||
}
|
||||
|
||||
func ExampleWithStack() {
|
||||
cause := errors.New("whoops")
|
||||
err := errors.WithStack(cause)
|
||||
fmt.Println(err)
|
||||
|
||||
// Output: whoops
|
||||
}
|
||||
|
||||
func ExampleWithStack_printf() {
|
||||
cause := errors.New("whoops")
|
||||
err := errors.WithStack(cause)
|
||||
fmt.Printf("%+v", err)
|
||||
|
||||
// Example Output:
|
||||
// whoops
|
||||
// github.com/pkg/errors_test.ExampleWithStack_printf
|
||||
// /home/fabstu/go/src/github.com/pkg/errors/example_test.go:55
|
||||
// testing.runExample
|
||||
// /usr/lib/go/src/testing/example.go:114
|
||||
// testing.RunExamples
|
||||
// /usr/lib/go/src/testing/example.go:38
|
||||
// testing.(*M).Run
|
||||
// /usr/lib/go/src/testing/testing.go:744
|
||||
// main.main
|
||||
// github.com/pkg/errors/_test/_testmain.go:106
|
||||
// runtime.main
|
||||
// /usr/lib/go/src/runtime/proc.go:183
|
||||
// runtime.goexit
|
||||
// /usr/lib/go/src/runtime/asm_amd64.s:2086
|
||||
// github.com/pkg/errors_test.ExampleWithStack_printf
|
||||
// /home/fabstu/go/src/github.com/pkg/errors/example_test.go:56
|
||||
// testing.runExample
|
||||
// /usr/lib/go/src/testing/example.go:114
|
||||
// testing.RunExamples
|
||||
// /usr/lib/go/src/testing/example.go:38
|
||||
// testing.(*M).Run
|
||||
// /usr/lib/go/src/testing/testing.go:744
|
||||
// main.main
|
||||
// github.com/pkg/errors/_test/_testmain.go:106
|
||||
// runtime.main
|
||||
// /usr/lib/go/src/runtime/proc.go:183
|
||||
// runtime.goexit
|
||||
// /usr/lib/go/src/runtime/asm_amd64.s:2086
|
||||
}
|
||||
|
||||
func ExampleWrap() {
|
||||
cause := errors.New("whoops")
|
||||
err := errors.Wrap(cause, "oh noes")
|
||||
fmt.Println(err)
|
||||
|
||||
// Output: oh noes: whoops
|
||||
}
|
||||
|
||||
func fn() error {
|
||||
e1 := errors.New("error")
|
||||
e2 := errors.Wrap(e1, "inner")
|
||||
e3 := errors.Wrap(e2, "middle")
|
||||
return errors.Wrap(e3, "outer")
|
||||
}
|
||||
|
||||
func ExampleCause() {
|
||||
err := fn()
|
||||
fmt.Println(err)
|
||||
fmt.Println(errors.Cause(err))
|
||||
|
||||
// Output: outer: middle: inner: error
|
||||
// error
|
||||
}
|
||||
|
||||
func ExampleWrap_extended() {
|
||||
err := fn()
|
||||
fmt.Printf("%+v\n", err)
|
||||
|
||||
// Example output:
|
||||
// error
|
||||
// github.com/pkg/errors_test.fn
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:47
|
||||
// github.com/pkg/errors_test.ExampleCause_printf
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:63
|
||||
// testing.runExample
|
||||
// /home/dfc/go/src/testing/example.go:114
|
||||
// testing.RunExamples
|
||||
// /home/dfc/go/src/testing/example.go:38
|
||||
// testing.(*M).Run
|
||||
// /home/dfc/go/src/testing/testing.go:744
|
||||
// main.main
|
||||
// /github.com/pkg/errors/_test/_testmain.go:104
|
||||
// runtime.main
|
||||
// /home/dfc/go/src/runtime/proc.go:183
|
||||
// runtime.goexit
|
||||
// /home/dfc/go/src/runtime/asm_amd64.s:2059
|
||||
// github.com/pkg/errors_test.fn
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:48: inner
|
||||
// github.com/pkg/errors_test.fn
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:49: middle
|
||||
// github.com/pkg/errors_test.fn
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:50: outer
|
||||
}
|
||||
|
||||
func ExampleWrapf() {
|
||||
cause := errors.New("whoops")
|
||||
err := errors.Wrapf(cause, "oh noes #%d", 2)
|
||||
fmt.Println(err)
|
||||
|
||||
// Output: oh noes #2: whoops
|
||||
}
|
||||
|
||||
func ExampleErrorf_extended() {
|
||||
err := errors.Errorf("whoops: %s", "foo")
|
||||
fmt.Printf("%+v", err)
|
||||
|
||||
// Example output:
|
||||
// whoops: foo
|
||||
// github.com/pkg/errors_test.ExampleErrorf
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:101
|
||||
// testing.runExample
|
||||
// /home/dfc/go/src/testing/example.go:114
|
||||
// testing.RunExamples
|
||||
// /home/dfc/go/src/testing/example.go:38
|
||||
// testing.(*M).Run
|
||||
// /home/dfc/go/src/testing/testing.go:744
|
||||
// main.main
|
||||
// /github.com/pkg/errors/_test/_testmain.go:102
|
||||
// runtime.main
|
||||
// /home/dfc/go/src/runtime/proc.go:183
|
||||
// runtime.goexit
|
||||
// /home/dfc/go/src/runtime/asm_amd64.s:2059
|
||||
}
|
||||
|
||||
func Example_stackTrace() {
|
||||
type stackTracer interface {
|
||||
StackTrace() errors.StackTrace
|
||||
}
|
||||
|
||||
err, ok := errors.Cause(fn()).(stackTracer)
|
||||
if !ok {
|
||||
panic("oops, err does not implement stackTracer")
|
||||
}
|
||||
|
||||
st := err.StackTrace()
|
||||
fmt.Printf("%+v", st[0:2]) // top two frames
|
||||
|
||||
// Example output:
|
||||
// github.com/pkg/errors_test.fn
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:47
|
||||
// github.com/pkg/errors_test.Example_stackTrace
|
||||
// /home/dfc/src/github.com/pkg/errors/example_test.go:127
|
||||
}
|
||||
|
||||
func ExampleCause_printf() {
|
||||
err := errors.Wrap(func() error {
|
||||
return func() error {
|
||||
return errors.Errorf("hello %s", fmt.Sprintf("world"))
|
||||
}()
|
||||
}(), "failed")
|
||||
|
||||
fmt.Printf("%v", err)
|
||||
|
||||
// Output: failed: hello world
|
||||
}
|
|
@ -1,535 +0,0 @@
|
|||
package errors
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFormatNew(t *testing.T) {
|
||||
tests := []struct {
|
||||
error
|
||||
format string
|
||||
want string
|
||||
}{{
|
||||
New("error"),
|
||||
"%s",
|
||||
"error",
|
||||
}, {
|
||||
New("error"),
|
||||
"%v",
|
||||
"error",
|
||||
}, {
|
||||
New("error"),
|
||||
"%+v",
|
||||
"error\n" +
|
||||
"github.com/pkg/errors.TestFormatNew\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:26",
|
||||
}, {
|
||||
New("error"),
|
||||
"%q",
|
||||
`"error"`,
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatErrorf(t *testing.T) {
|
||||
tests := []struct {
|
||||
error
|
||||
format string
|
||||
want string
|
||||
}{{
|
||||
Errorf("%s", "error"),
|
||||
"%s",
|
||||
"error",
|
||||
}, {
|
||||
Errorf("%s", "error"),
|
||||
"%v",
|
||||
"error",
|
||||
}, {
|
||||
Errorf("%s", "error"),
|
||||
"%+v",
|
||||
"error\n" +
|
||||
"github.com/pkg/errors.TestFormatErrorf\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:56",
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatWrap(t *testing.T) {
|
||||
tests := []struct {
|
||||
error
|
||||
format string
|
||||
want string
|
||||
}{{
|
||||
Wrap(New("error"), "error2"),
|
||||
"%s",
|
||||
"error2: error",
|
||||
}, {
|
||||
Wrap(New("error"), "error2"),
|
||||
"%v",
|
||||
"error2: error",
|
||||
}, {
|
||||
Wrap(New("error"), "error2"),
|
||||
"%+v",
|
||||
"error\n" +
|
||||
"github.com/pkg/errors.TestFormatWrap\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:82",
|
||||
}, {
|
||||
Wrap(io.EOF, "error"),
|
||||
"%s",
|
||||
"error: EOF",
|
||||
}, {
|
||||
Wrap(io.EOF, "error"),
|
||||
"%v",
|
||||
"error: EOF",
|
||||
}, {
|
||||
Wrap(io.EOF, "error"),
|
||||
"%+v",
|
||||
"EOF\n" +
|
||||
"error\n" +
|
||||
"github.com/pkg/errors.TestFormatWrap\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:96",
|
||||
}, {
|
||||
Wrap(Wrap(io.EOF, "error1"), "error2"),
|
||||
"%+v",
|
||||
"EOF\n" +
|
||||
"error1\n" +
|
||||
"github.com/pkg/errors.TestFormatWrap\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:103\n",
|
||||
}, {
|
||||
Wrap(New("error with space"), "context"),
|
||||
"%q",
|
||||
`"context: error with space"`,
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatWrapf(t *testing.T) {
|
||||
tests := []struct {
|
||||
error
|
||||
format string
|
||||
want string
|
||||
}{{
|
||||
Wrapf(io.EOF, "error%d", 2),
|
||||
"%s",
|
||||
"error2: EOF",
|
||||
}, {
|
||||
Wrapf(io.EOF, "error%d", 2),
|
||||
"%v",
|
||||
"error2: EOF",
|
||||
}, {
|
||||
Wrapf(io.EOF, "error%d", 2),
|
||||
"%+v",
|
||||
"EOF\n" +
|
||||
"error2\n" +
|
||||
"github.com/pkg/errors.TestFormatWrapf\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:134",
|
||||
}, {
|
||||
Wrapf(New("error"), "error%d", 2),
|
||||
"%s",
|
||||
"error2: error",
|
||||
}, {
|
||||
Wrapf(New("error"), "error%d", 2),
|
||||
"%v",
|
||||
"error2: error",
|
||||
}, {
|
||||
Wrapf(New("error"), "error%d", 2),
|
||||
"%+v",
|
||||
"error\n" +
|
||||
"github.com/pkg/errors.TestFormatWrapf\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:149",
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatWithStack(t *testing.T) {
|
||||
tests := []struct {
|
||||
error
|
||||
format string
|
||||
want []string
|
||||
}{{
|
||||
WithStack(io.EOF),
|
||||
"%s",
|
||||
[]string{"EOF"},
|
||||
}, {
|
||||
WithStack(io.EOF),
|
||||
"%v",
|
||||
[]string{"EOF"},
|
||||
}, {
|
||||
WithStack(io.EOF),
|
||||
"%+v",
|
||||
[]string{"EOF",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:175"},
|
||||
}, {
|
||||
WithStack(New("error")),
|
||||
"%s",
|
||||
[]string{"error"},
|
||||
}, {
|
||||
WithStack(New("error")),
|
||||
"%v",
|
||||
[]string{"error"},
|
||||
}, {
|
||||
WithStack(New("error")),
|
||||
"%+v",
|
||||
[]string{"error",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:189",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:189"},
|
||||
}, {
|
||||
WithStack(WithStack(io.EOF)),
|
||||
"%+v",
|
||||
[]string{"EOF",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:197",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:197"},
|
||||
}, {
|
||||
WithStack(WithStack(Wrapf(io.EOF, "message"))),
|
||||
"%+v",
|
||||
[]string{"EOF",
|
||||
"message",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:205",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:205",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:205"},
|
||||
}, {
|
||||
WithStack(Errorf("error%d", 1)),
|
||||
"%+v",
|
||||
[]string{"error1",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:216",
|
||||
"github.com/pkg/errors.TestFormatWithStack\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:216"},
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatWithMessage(t *testing.T) {
|
||||
tests := []struct {
|
||||
error
|
||||
format string
|
||||
want []string
|
||||
}{{
|
||||
WithMessage(New("error"), "error2"),
|
||||
"%s",
|
||||
[]string{"error2: error"},
|
||||
}, {
|
||||
WithMessage(New("error"), "error2"),
|
||||
"%v",
|
||||
[]string{"error2: error"},
|
||||
}, {
|
||||
WithMessage(New("error"), "error2"),
|
||||
"%+v",
|
||||
[]string{
|
||||
"error",
|
||||
"github.com/pkg/errors.TestFormatWithMessage\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:244",
|
||||
"error2"},
|
||||
}, {
|
||||
WithMessage(io.EOF, "addition1"),
|
||||
"%s",
|
||||
[]string{"addition1: EOF"},
|
||||
}, {
|
||||
WithMessage(io.EOF, "addition1"),
|
||||
"%v",
|
||||
[]string{"addition1: EOF"},
|
||||
}, {
|
||||
WithMessage(io.EOF, "addition1"),
|
||||
"%+v",
|
||||
[]string{"EOF", "addition1"},
|
||||
}, {
|
||||
WithMessage(WithMessage(io.EOF, "addition1"), "addition2"),
|
||||
"%v",
|
||||
[]string{"addition2: addition1: EOF"},
|
||||
}, {
|
||||
WithMessage(WithMessage(io.EOF, "addition1"), "addition2"),
|
||||
"%+v",
|
||||
[]string{"EOF", "addition1", "addition2"},
|
||||
}, {
|
||||
Wrap(WithMessage(io.EOF, "error1"), "error2"),
|
||||
"%+v",
|
||||
[]string{"EOF", "error1", "error2",
|
||||
"github.com/pkg/errors.TestFormatWithMessage\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:272"},
|
||||
}, {
|
||||
WithMessage(Errorf("error%d", 1), "error2"),
|
||||
"%+v",
|
||||
[]string{"error1",
|
||||
"github.com/pkg/errors.TestFormatWithMessage\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:278",
|
||||
"error2"},
|
||||
}, {
|
||||
WithMessage(WithStack(io.EOF), "error"),
|
||||
"%+v",
|
||||
[]string{
|
||||
"EOF",
|
||||
"github.com/pkg/errors.TestFormatWithMessage\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:285",
|
||||
"error"},
|
||||
}, {
|
||||
WithMessage(Wrap(WithStack(io.EOF), "inside-error"), "outside-error"),
|
||||
"%+v",
|
||||
[]string{
|
||||
"EOF",
|
||||
"github.com/pkg/errors.TestFormatWithMessage\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:293",
|
||||
"inside-error",
|
||||
"github.com/pkg/errors.TestFormatWithMessage\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:293",
|
||||
"outside-error"},
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatGeneric(t *testing.T) {
|
||||
starts := []struct {
|
||||
err error
|
||||
want []string
|
||||
}{
|
||||
{New("new-error"), []string{
|
||||
"new-error",
|
||||
"github.com/pkg/errors.TestFormatGeneric\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:315"},
|
||||
}, {Errorf("errorf-error"), []string{
|
||||
"errorf-error",
|
||||
"github.com/pkg/errors.TestFormatGeneric\n" +
|
||||
"\t.+/github.com/pkg/errors/format_test.go:319"},
|
||||
}, {errors.New("errors-new-error"), []string{
|
||||
"errors-new-error"},
|
||||
},
|
||||
}
|
||||
|
||||
wrappers := []wrapper{
|
||||
{
|
||||
func(err error) error { return WithMessage(err, "with-message") },
|
||||
[]string{"with-message"},
|
||||
}, {
|
||||
func(err error) error { return WithStack(err) },
|
||||
[]string{
|
||||
"github.com/pkg/errors.(func·002|TestFormatGeneric.func2)\n\t" +
|
||||
".+/github.com/pkg/errors/format_test.go:333",
|
||||
},
|
||||
}, {
|
||||
func(err error) error { return Wrap(err, "wrap-error") },
|
||||
[]string{
|
||||
"wrap-error",
|
||||
"github.com/pkg/errors.(func·003|TestFormatGeneric.func3)\n\t" +
|
||||
".+/github.com/pkg/errors/format_test.go:339",
|
||||
},
|
||||
}, {
|
||||
func(err error) error { return Wrapf(err, "wrapf-error%d", 1) },
|
||||
[]string{
|
||||
"wrapf-error1",
|
||||
"github.com/pkg/errors.(func·004|TestFormatGeneric.func4)\n\t" +
|
||||
".+/github.com/pkg/errors/format_test.go:346",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for s := range starts {
|
||||
err := starts[s].err
|
||||
want := starts[s].want
|
||||
testFormatCompleteCompare(t, s, err, "%+v", want, false)
|
||||
testGenericRecursive(t, err, want, wrappers, 3)
|
||||
}
|
||||
}
|
||||
|
||||
func testFormatRegexp(t *testing.T, n int, arg interface{}, format, want string) {
|
||||
got := fmt.Sprintf(format, arg)
|
||||
gotLines := strings.SplitN(got, "\n", -1)
|
||||
wantLines := strings.SplitN(want, "\n", -1)
|
||||
|
||||
if len(wantLines) > len(gotLines) {
|
||||
t.Errorf("test %d: wantLines(%d) > gotLines(%d):\n got: %q\nwant: %q", n+1, len(wantLines), len(gotLines), got, want)
|
||||
return
|
||||
}
|
||||
|
||||
for i, w := range wantLines {
|
||||
match, err := regexp.MatchString(w, gotLines[i])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !match {
|
||||
t.Errorf("test %d: line %d: fmt.Sprintf(%q, err):\n got: %q\nwant: %q", n+1, i+1, format, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var stackLineR = regexp.MustCompile(`\.`)
|
||||
|
||||
// parseBlocks parses input into a slice, where:
|
||||
// - incase entry contains a newline, its a stacktrace
|
||||
// - incase entry contains no newline, its a solo line.
|
||||
//
|
||||
// Detecting stack boundaries only works incase the WithStack-calls are
|
||||
// to be found on the same line, thats why it is optionally here.
|
||||
//
|
||||
// Example use:
|
||||
//
|
||||
// for _, e := range blocks {
|
||||
// if strings.ContainsAny(e, "\n") {
|
||||
// // Match as stack
|
||||
// } else {
|
||||
// // Match as line
|
||||
// }
|
||||
// }
|
||||
//
|
||||
func parseBlocks(input string, detectStackboundaries bool) ([]string, error) {
|
||||
var blocks []string
|
||||
|
||||
stack := ""
|
||||
wasStack := false
|
||||
lines := map[string]bool{} // already found lines
|
||||
|
||||
for _, l := range strings.Split(input, "\n") {
|
||||
isStackLine := stackLineR.MatchString(l)
|
||||
|
||||
switch {
|
||||
case !isStackLine && wasStack:
|
||||
blocks = append(blocks, stack, l)
|
||||
stack = ""
|
||||
lines = map[string]bool{}
|
||||
case isStackLine:
|
||||
if wasStack {
|
||||
// Detecting two stacks after another, possible cause lines match in
|
||||
// our tests due to WithStack(WithStack(io.EOF)) on same line.
|
||||
if detectStackboundaries {
|
||||
if lines[l] {
|
||||
if len(stack) == 0 {
|
||||
return nil, errors.New("len of block must not be zero here")
|
||||
}
|
||||
|
||||
blocks = append(blocks, stack)
|
||||
stack = l
|
||||
lines = map[string]bool{l: true}
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
stack = stack + "\n" + l
|
||||
} else {
|
||||
stack = l
|
||||
}
|
||||
lines[l] = true
|
||||
case !isStackLine && !wasStack:
|
||||
blocks = append(blocks, l)
|
||||
default:
|
||||
return nil, errors.New("must not happen")
|
||||
}
|
||||
|
||||
wasStack = isStackLine
|
||||
}
|
||||
|
||||
// Use up stack
|
||||
if stack != "" {
|
||||
blocks = append(blocks, stack)
|
||||
}
|
||||
return blocks, nil
|
||||
}
|
||||
|
||||
func testFormatCompleteCompare(t *testing.T, n int, arg interface{}, format string, want []string, detectStackBoundaries bool) {
|
||||
gotStr := fmt.Sprintf(format, arg)
|
||||
|
||||
got, err := parseBlocks(gotStr, detectStackBoundaries)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("test %d: fmt.Sprintf(%s, err) -> wrong number of blocks: got(%d) want(%d)\n got: %s\nwant: %s\ngotStr: %q",
|
||||
n+1, format, len(got), len(want), prettyBlocks(got), prettyBlocks(want), gotStr)
|
||||
}
|
||||
|
||||
for i := range got {
|
||||
if strings.ContainsAny(want[i], "\n") {
|
||||
// Match as stack
|
||||
match, err := regexp.MatchString(want[i], got[i])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !match {
|
||||
t.Fatalf("test %d: block %d: fmt.Sprintf(%q, err):\ngot:\n%q\nwant:\n%q\nall-got:\n%s\nall-want:\n%s\n",
|
||||
n+1, i+1, format, got[i], want[i], prettyBlocks(got), prettyBlocks(want))
|
||||
}
|
||||
} else {
|
||||
// Match as message
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("test %d: fmt.Sprintf(%s, err) at block %d got != want:\n got: %q\nwant: %q", n+1, format, i+1, got[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type wrapper struct {
|
||||
wrap func(err error) error
|
||||
want []string
|
||||
}
|
||||
|
||||
func prettyBlocks(blocks []string) string {
|
||||
var out []string
|
||||
|
||||
for _, b := range blocks {
|
||||
out = append(out, fmt.Sprintf("%v", b))
|
||||
}
|
||||
|
||||
return " " + strings.Join(out, "\n ")
|
||||
}
|
||||
|
||||
func testGenericRecursive(t *testing.T, beforeErr error, beforeWant []string, list []wrapper, maxDepth int) {
|
||||
if len(beforeWant) == 0 {
|
||||
panic("beforeWant must not be empty")
|
||||
}
|
||||
for _, w := range list {
|
||||
if len(w.want) == 0 {
|
||||
panic("want must not be empty")
|
||||
}
|
||||
|
||||
err := w.wrap(beforeErr)
|
||||
|
||||
// Copy required cause append(beforeWant, ..) modified beforeWant subtly.
|
||||
beforeCopy := make([]string, len(beforeWant))
|
||||
copy(beforeCopy, beforeWant)
|
||||
|
||||
beforeWant := beforeCopy
|
||||
last := len(beforeWant) - 1
|
||||
var want []string
|
||||
|
||||
// Merge two stacks behind each other.
|
||||
if strings.ContainsAny(beforeWant[last], "\n") && strings.ContainsAny(w.want[0], "\n") {
|
||||
want = append(beforeWant[:last], append([]string{beforeWant[last] + "((?s).*)" + w.want[0]}, w.want[1:]...)...)
|
||||
} else {
|
||||
want = append(beforeWant, w.want...)
|
||||
}
|
||||
|
||||
testFormatCompleteCompare(t, maxDepth, err, "%+v", want, false)
|
||||
if maxDepth > 0 {
|
||||
testGenericRecursive(t, err, want, list, maxDepth-1)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,274 +0,0 @@
|
|||
package errors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var initpc, _, _, _ = runtime.Caller(0)
|
||||
|
||||
func TestFrameLine(t *testing.T) {
|
||||
var tests = []struct {
|
||||
Frame
|
||||
want int
|
||||
}{{
|
||||
Frame(initpc),
|
||||
9,
|
||||
}, {
|
||||
func() Frame {
|
||||
var pc, _, _, _ = runtime.Caller(0)
|
||||
return Frame(pc)
|
||||
}(),
|
||||
20,
|
||||
}, {
|
||||
func() Frame {
|
||||
var pc, _, _, _ = runtime.Caller(1)
|
||||
return Frame(pc)
|
||||
}(),
|
||||
28,
|
||||
}, {
|
||||
Frame(0), // invalid PC
|
||||
0,
|
||||
}}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := tt.Frame.line()
|
||||
want := tt.want
|
||||
if want != got {
|
||||
t.Errorf("Frame(%v): want: %v, got: %v", uintptr(tt.Frame), want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type X struct{}
|
||||
|
||||
func (x X) val() Frame {
|
||||
var pc, _, _, _ = runtime.Caller(0)
|
||||
return Frame(pc)
|
||||
}
|
||||
|
||||
func (x *X) ptr() Frame {
|
||||
var pc, _, _, _ = runtime.Caller(0)
|
||||
return Frame(pc)
|
||||
}
|
||||
|
||||
func TestFrameFormat(t *testing.T) {
|
||||
var tests = []struct {
|
||||
Frame
|
||||
format string
|
||||
want string
|
||||
}{{
|
||||
Frame(initpc),
|
||||
"%s",
|
||||
"stack_test.go",
|
||||
}, {
|
||||
Frame(initpc),
|
||||
"%+s",
|
||||
"github.com/pkg/errors.init\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go",
|
||||
}, {
|
||||
Frame(0),
|
||||
"%s",
|
||||
"unknown",
|
||||
}, {
|
||||
Frame(0),
|
||||
"%+s",
|
||||
"unknown",
|
||||
}, {
|
||||
Frame(initpc),
|
||||
"%d",
|
||||
"9",
|
||||
}, {
|
||||
Frame(0),
|
||||
"%d",
|
||||
"0",
|
||||
}, {
|
||||
Frame(initpc),
|
||||
"%n",
|
||||
"init",
|
||||
}, {
|
||||
func() Frame {
|
||||
var x X
|
||||
return x.ptr()
|
||||
}(),
|
||||
"%n",
|
||||
`\(\*X\).ptr`,
|
||||
}, {
|
||||
func() Frame {
|
||||
var x X
|
||||
return x.val()
|
||||
}(),
|
||||
"%n",
|
||||
"X.val",
|
||||
}, {
|
||||
Frame(0),
|
||||
"%n",
|
||||
"",
|
||||
}, {
|
||||
Frame(initpc),
|
||||
"%v",
|
||||
"stack_test.go:9",
|
||||
}, {
|
||||
Frame(initpc),
|
||||
"%+v",
|
||||
"github.com/pkg/errors.init\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go:9",
|
||||
}, {
|
||||
Frame(0),
|
||||
"%v",
|
||||
"unknown:0",
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
testFormatRegexp(t, i, tt.Frame, tt.format, tt.want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFuncname(t *testing.T) {
|
||||
tests := []struct {
|
||||
name, want string
|
||||
}{
|
||||
{"", ""},
|
||||
{"runtime.main", "main"},
|
||||
{"github.com/pkg/errors.funcname", "funcname"},
|
||||
{"funcname", "funcname"},
|
||||
{"io.copyBuffer", "copyBuffer"},
|
||||
{"main.(*R).Write", "(*R).Write"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := funcname(tt.name)
|
||||
want := tt.want
|
||||
if got != want {
|
||||
t.Errorf("funcname(%q): want: %q, got %q", tt.name, want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStackTrace(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
want []string
|
||||
}{{
|
||||
New("ooh"), []string{
|
||||
"github.com/pkg/errors.TestStackTrace\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go:154",
|
||||
},
|
||||
}, {
|
||||
Wrap(New("ooh"), "ahh"), []string{
|
||||
"github.com/pkg/errors.TestStackTrace\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go:159", // this is the stack of Wrap, not New
|
||||
},
|
||||
}, {
|
||||
Cause(Wrap(New("ooh"), "ahh")), []string{
|
||||
"github.com/pkg/errors.TestStackTrace\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go:164", // this is the stack of New
|
||||
},
|
||||
}, {
|
||||
func() error { return New("ooh") }(), []string{
|
||||
`github.com/pkg/errors.(func·009|TestStackTrace.func1)` +
|
||||
"\n\t.+/github.com/pkg/errors/stack_test.go:169", // this is the stack of New
|
||||
"github.com/pkg/errors.TestStackTrace\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go:169", // this is the stack of New's caller
|
||||
},
|
||||
}, {
|
||||
Cause(func() error {
|
||||
return func() error {
|
||||
return Errorf("hello %s", fmt.Sprintf("world"))
|
||||
}()
|
||||
}()), []string{
|
||||
`github.com/pkg/errors.(func·010|TestStackTrace.func2.1)` +
|
||||
"\n\t.+/github.com/pkg/errors/stack_test.go:178", // this is the stack of Errorf
|
||||
`github.com/pkg/errors.(func·011|TestStackTrace.func2)` +
|
||||
"\n\t.+/github.com/pkg/errors/stack_test.go:179", // this is the stack of Errorf's caller
|
||||
"github.com/pkg/errors.TestStackTrace\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go:180", // this is the stack of Errorf's caller's caller
|
||||
},
|
||||
}}
|
||||
for i, tt := range tests {
|
||||
x, ok := tt.err.(interface {
|
||||
StackTrace() StackTrace
|
||||
})
|
||||
if !ok {
|
||||
t.Errorf("expected %#v to implement StackTrace() StackTrace", tt.err)
|
||||
continue
|
||||
}
|
||||
st := x.StackTrace()
|
||||
for j, want := range tt.want {
|
||||
testFormatRegexp(t, i, st[j], "%+v", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func stackTrace() StackTrace {
|
||||
const depth = 8
|
||||
var pcs [depth]uintptr
|
||||
n := runtime.Callers(1, pcs[:])
|
||||
var st stack = pcs[0:n]
|
||||
return st.StackTrace()
|
||||
}
|
||||
|
||||
func TestStackTraceFormat(t *testing.T) {
|
||||
tests := []struct {
|
||||
StackTrace
|
||||
format string
|
||||
want string
|
||||
}{{
|
||||
nil,
|
||||
"%s",
|
||||
`\[\]`,
|
||||
}, {
|
||||
nil,
|
||||
"%v",
|
||||
`\[\]`,
|
||||
}, {
|
||||
nil,
|
||||
"%+v",
|
||||
"",
|
||||
}, {
|
||||
nil,
|
||||
"%#v",
|
||||
`\[\]errors.Frame\(nil\)`,
|
||||
}, {
|
||||
make(StackTrace, 0),
|
||||
"%s",
|
||||
`\[\]`,
|
||||
}, {
|
||||
make(StackTrace, 0),
|
||||
"%v",
|
||||
`\[\]`,
|
||||
}, {
|
||||
make(StackTrace, 0),
|
||||
"%+v",
|
||||
"",
|
||||
}, {
|
||||
make(StackTrace, 0),
|
||||
"%#v",
|
||||
`\[\]errors.Frame{}`,
|
||||
}, {
|
||||
stackTrace()[:2],
|
||||
"%s",
|
||||
`\[stack_test.go stack_test.go\]`,
|
||||
}, {
|
||||
stackTrace()[:2],
|
||||
"%v",
|
||||
`\[stack_test.go:207 stack_test.go:254\]`,
|
||||
}, {
|
||||
stackTrace()[:2],
|
||||
"%+v",
|
||||
"\n" +
|
||||
"github.com/pkg/errors.stackTrace\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go:207\n" +
|
||||
"github.com/pkg/errors.TestStackTraceFormat\n" +
|
||||
"\t.+/github.com/pkg/errors/stack_test.go:258",
|
||||
}, {
|
||||
stackTrace()[:2],
|
||||
"%#v",
|
||||
`\[\]errors.Frame{stack_test.go:207, stack_test.go:266}`,
|
||||
}}
|
||||
|
||||
for i, tt := range tests {
|
||||
testFormatRegexp(t, i, tt.StackTrace, tt.format, tt.want)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
logrus
|
||||
vendor
|
|
@ -0,0 +1,25 @@
|
|||
language: go
|
||||
go_import_path: github.com/sirupsen/logrus
|
||||
git:
|
||||
depth: 1
|
||||
env:
|
||||
- GO111MODULE=on
|
||||
- GO111MODULE=off
|
||||
go: [ 1.11.x, 1.12.x ]
|
||||
os: [ linux, osx ]
|
||||
matrix:
|
||||
exclude:
|
||||
- go: 1.12.x
|
||||
env: GO111MODULE=off
|
||||
- go: 1.11.x
|
||||
os: osx
|
||||
install:
|
||||
- ./travis/install.sh
|
||||
- if [[ "$GO111MODULE" == "on" ]]; then go mod download; fi
|
||||
- if [[ "$GO111MODULE" == "off" ]]; then go get github.com/stretchr/testify/assert golang.org/x/sys/unix github.com/konsorten/go-windows-terminal-sequences; fi
|
||||
script:
|
||||
- ./travis/cross_build.sh
|
||||
- export GOMAXPROCS=4
|
||||
- export GORACE=halt_on_error=1
|
||||
- go test -race -v ./...
|
||||
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then go test -race -v -tags appengine ./... ; fi
|
|
@ -0,0 +1,200 @@
|
|||
# 1.4.2
|
||||
* Fixes build break for plan9, nacl, solaris
|
||||
# 1.4.1
|
||||
This new release introduces:
|
||||
* Enhance TextFormatter to not print caller information when they are empty (#944)
|
||||
* Remove dependency on golang.org/x/crypto (#932, #943)
|
||||
|
||||
Fixes:
|
||||
* Fix Entry.WithContext method to return a copy of the initial entry (#941)
|
||||
|
||||
# 1.4.0
|
||||
This new release introduces:
|
||||
* Add `DeferExitHandler`, similar to `RegisterExitHandler` but prepending the handler to the list of handlers (semantically like `defer`) (#848).
|
||||
* Add `CallerPrettyfier` to `JSONFormatter` and `TextFormatter (#909, #911)
|
||||
* Add `Entry.WithContext()` and `Entry.Context`, to set a context on entries to be used e.g. in hooks (#919).
|
||||
|
||||
Fixes:
|
||||
* Fix wrong method calls `Logger.Print` and `Logger.Warningln` (#893).
|
||||
* Update `Entry.Logf` to not do string formatting unless the log level is enabled (#903)
|
||||
* Fix infinite recursion on unknown `Level.String()` (#907)
|
||||
* Fix race condition in `getCaller` (#916).
|
||||
|
||||
|
||||
# 1.3.0
|
||||
This new release introduces:
|
||||
* Log, Logf, Logln functions for Logger and Entry that take a Level
|
||||
|
||||
Fixes:
|
||||
* Building prometheus node_exporter on AIX (#840)
|
||||
* Race condition in TextFormatter (#468)
|
||||
* Travis CI import path (#868)
|
||||
* Remove coloured output on Windows (#862)
|
||||
* Pointer to func as field in JSONFormatter (#870)
|
||||
* Properly marshal Levels (#873)
|
||||
|
||||
# 1.2.0
|
||||
This new release introduces:
|
||||
* A new method `SetReportCaller` in the `Logger` to enable the file, line and calling function from which the trace has been issued
|
||||
* A new trace level named `Trace` whose level is below `Debug`
|
||||
* A configurable exit function to be called upon a Fatal trace
|
||||
* The `Level` object now implements `encoding.TextUnmarshaler` interface
|
||||
|
||||
# 1.1.1
|
||||
This is a bug fix release.
|
||||
* fix the build break on Solaris
|
||||
* don't drop a whole trace in JSONFormatter when a field param is a function pointer which can not be serialized
|
||||
|
||||
# 1.1.0
|
||||
This new release introduces:
|
||||
* several fixes:
|
||||
* a fix for a race condition on entry formatting
|
||||
* proper cleanup of previously used entries before putting them back in the pool
|
||||
* the extra new line at the end of message in text formatter has been removed
|
||||
* a new global public API to check if a level is activated: IsLevelEnabled
|
||||
* the following methods have been added to the Logger object
|
||||
* IsLevelEnabled
|
||||
* SetFormatter
|
||||
* SetOutput
|
||||
* ReplaceHooks
|
||||
* introduction of go module
|
||||
* an indent configuration for the json formatter
|
||||
* output colour support for windows
|
||||
* the field sort function is now configurable for text formatter
|
||||
* the CLICOLOR and CLICOLOR\_FORCE environment variable support in text formater
|
||||
|
||||
# 1.0.6
|
||||
|
||||
This new release introduces:
|
||||
* a new api WithTime which allows to easily force the time of the log entry
|
||||
which is mostly useful for logger wrapper
|
||||
* a fix reverting the immutability of the entry given as parameter to the hooks
|
||||
a new configuration field of the json formatter in order to put all the fields
|
||||
in a nested dictionnary
|
||||
* a new SetOutput method in the Logger
|
||||
* a new configuration of the textformatter to configure the name of the default keys
|
||||
* a new configuration of the text formatter to disable the level truncation
|
||||
|
||||
# 1.0.5
|
||||
|
||||
* Fix hooks race (#707)
|
||||
* Fix panic deadlock (#695)
|
||||
|
||||
# 1.0.4
|
||||
|
||||
* Fix race when adding hooks (#612)
|
||||
* Fix terminal check in AppEngine (#635)
|
||||
|
||||
# 1.0.3
|
||||
|
||||
* Replace example files with testable examples
|
||||
|
||||
# 1.0.2
|
||||
|
||||
* bug: quote non-string values in text formatter (#583)
|
||||
* Make (*Logger) SetLevel a public method
|
||||
|
||||
# 1.0.1
|
||||
|
||||
* bug: fix escaping in text formatter (#575)
|
||||
|
||||
# 1.0.0
|
||||
|
||||
* Officially changed name to lower-case
|
||||
* bug: colors on Windows 10 (#541)
|
||||
* bug: fix race in accessing level (#512)
|
||||
|
||||
# 0.11.5
|
||||
|
||||
* feature: add writer and writerlevel to entry (#372)
|
||||
|
||||
# 0.11.4
|
||||
|
||||
* bug: fix undefined variable on solaris (#493)
|
||||
|
||||
# 0.11.3
|
||||
|
||||
* formatter: configure quoting of empty values (#484)
|
||||
* formatter: configure quoting character (default is `"`) (#484)
|
||||
* bug: fix not importing io correctly in non-linux environments (#481)
|
||||
|
||||
# 0.11.2
|
||||
|
||||
* bug: fix windows terminal detection (#476)
|
||||
|
||||
# 0.11.1
|
||||
|
||||
* bug: fix tty detection with custom out (#471)
|
||||
|
||||
# 0.11.0
|
||||
|
||||
* performance: Use bufferpool to allocate (#370)
|
||||
* terminal: terminal detection for app-engine (#343)
|
||||
* feature: exit handler (#375)
|
||||
|
||||
# 0.10.0
|
||||
|
||||
* feature: Add a test hook (#180)
|
||||
* feature: `ParseLevel` is now case-insensitive (#326)
|
||||
* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308)
|
||||
* performance: avoid re-allocations on `WithFields` (#335)
|
||||
|
||||
# 0.9.0
|
||||
|
||||
* logrus/text_formatter: don't emit empty msg
|
||||
* logrus/hooks/airbrake: move out of main repository
|
||||
* logrus/hooks/sentry: move out of main repository
|
||||
* logrus/hooks/papertrail: move out of main repository
|
||||
* logrus/hooks/bugsnag: move out of main repository
|
||||
* logrus/core: run tests with `-race`
|
||||
* logrus/core: detect TTY based on `stderr`
|
||||
* logrus/core: support `WithError` on logger
|
||||
* logrus/core: Solaris support
|
||||
|
||||
# 0.8.7
|
||||
|
||||
* logrus/core: fix possible race (#216)
|
||||
* logrus/doc: small typo fixes and doc improvements
|
||||
|
||||
|
||||
# 0.8.6
|
||||
|
||||
* hooks/raven: allow passing an initialized client
|
||||
|
||||
# 0.8.5
|
||||
|
||||
* logrus/core: revert #208
|
||||
|
||||
# 0.8.4
|
||||
|
||||
* formatter/text: fix data race (#218)
|
||||
|
||||
# 0.8.3
|
||||
|
||||
* logrus/core: fix entry log level (#208)
|
||||
* logrus/core: improve performance of text formatter by 40%
|
||||
* logrus/core: expose `LevelHooks` type
|
||||
* logrus/core: add support for DragonflyBSD and NetBSD
|
||||
* formatter/text: print structs more verbosely
|
||||
|
||||
# 0.8.2
|
||||
|
||||
* logrus: fix more Fatal family functions
|
||||
|
||||
# 0.8.1
|
||||
|
||||
* logrus: fix not exiting on `Fatalf` and `Fatalln`
|
||||
|
||||
# 0.8.0
|
||||
|
||||
* logrus: defaults to stderr instead of stdout
|
||||
* hooks/sentry: add special field for `*http.Request`
|
||||
* formatter/text: ignore Windows for colors
|
||||
|
||||
# 0.7.3
|
||||
|
||||
* formatter/\*: allow configuration of timestamp layout
|
||||
|
||||
# 0.7.2
|
||||
|
||||
* formatter/text: Add configuration option for time format (#158)
|
|
@ -0,0 +1,21 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Simon Eskildsen
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
|
@ -0,0 +1,495 @@
|
|||
# Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/> [![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus) [![GoDoc](https://godoc.org/github.com/sirupsen/logrus?status.svg)](https://godoc.org/github.com/sirupsen/logrus)
|
||||
|
||||
Logrus is a structured logger for Go (golang), completely API compatible with
|
||||
the standard library logger.
|
||||
|
||||
**Seeing weird case-sensitive problems?** It's in the past been possible to
|
||||
import Logrus as both upper- and lower-case. Due to the Go package environment,
|
||||
this caused issues in the community and we needed a standard. Some environments
|
||||
experienced problems with the upper-case variant, so the lower-case was decided.
|
||||
Everything using `logrus` will need to use the lower-case:
|
||||
`github.com/sirupsen/logrus`. Any package that isn't, should be changed.
|
||||
|
||||
To fix Glide, see [these
|
||||
comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437).
|
||||
For an in-depth explanation of the casing issue, see [this
|
||||
comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276).
|
||||
|
||||
**Are you interested in assisting in maintaining Logrus?** Currently I have a
|
||||
lot of obligations, and I am unable to provide Logrus with the maintainership it
|
||||
needs. If you'd like to help, please reach out to me at `simon at author's
|
||||
username dot com`.
|
||||
|
||||
Nicely color-coded in development (when a TTY is attached, otherwise just
|
||||
plain text):
|
||||
|
||||
![Colored](http://i.imgur.com/PY7qMwd.png)
|
||||
|
||||
With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash
|
||||
or Splunk:
|
||||
|
||||
```json
|
||||
{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the
|
||||
ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"}
|
||||
|
||||
{"level":"warning","msg":"The group's number increased tremendously!",
|
||||
"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"}
|
||||
|
||||
{"animal":"walrus","level":"info","msg":"A giant walrus appears!",
|
||||
"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"}
|
||||
|
||||
{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.",
|
||||
"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"}
|
||||
|
||||
{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,
|
||||
"time":"2014-03-10 19:57:38.562543128 -0400 EDT"}
|
||||
```
|
||||
|
||||
With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not
|
||||
attached, the output is compatible with the
|
||||
[logfmt](http://godoc.org/github.com/kr/logfmt) format:
|
||||
|
||||
```text
|
||||
time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8
|
||||
time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
|
||||
time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true
|
||||
time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4
|
||||
time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009
|
||||
time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true
|
||||
```
|
||||
To ensure this behaviour even if a TTY is attached, set your formatter as follows:
|
||||
|
||||
```go
|
||||
log.SetFormatter(&log.TextFormatter{
|
||||
DisableColors: true,
|
||||
FullTimestamp: true,
|
||||
})
|
||||
```
|
||||
|
||||
#### Logging Method Name
|
||||
|
||||
If you wish to add the calling method as a field, instruct the logger via:
|
||||
```go
|
||||
log.SetReportCaller(true)
|
||||
```
|
||||
This adds the caller as 'method' like so:
|
||||
|
||||
```json
|
||||
{"animal":"penguin","level":"fatal","method":"github.com/sirupsen/arcticcreatures.migrate","msg":"a penguin swims by",
|
||||
"time":"2014-03-10 19:57:38.562543129 -0400 EDT"}
|
||||
```
|
||||
|
||||
```text
|
||||
time="2015-03-26T01:27:38-04:00" level=fatal method=github.com/sirupsen/arcticcreatures.migrate msg="a penguin swims by" animal=penguin
|
||||
```
|
||||
Note that this does add measurable overhead - the cost will depend on the version of Go, but is
|
||||
between 20 and 40% in recent tests with 1.6 and 1.7. You can validate this in your
|
||||
environment via benchmarks:
|
||||
```
|
||||
go test -bench=.*CallerTracing
|
||||
```
|
||||
|
||||
|
||||
#### Case-sensitivity
|
||||
|
||||
The organization's name was changed to lower-case--and this will not be changed
|
||||
back. If you are getting import conflicts due to case sensitivity, please use
|
||||
the lower-case import: `github.com/sirupsen/logrus`.
|
||||
|
||||
#### Example
|
||||
|
||||
The simplest way to use Logrus is simply the package-level exported logger:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log.WithFields(log.Fields{
|
||||
"animal": "walrus",
|
||||
}).Info("A walrus appears")
|
||||
}
|
||||
```
|
||||
|
||||
Note that it's completely api-compatible with the stdlib logger, so you can
|
||||
replace your `log` imports everywhere with `log "github.com/sirupsen/logrus"`
|
||||
and you'll now have the flexibility of Logrus. You can customize it all you
|
||||
want:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func init() {
|
||||
// Log as JSON instead of the default ASCII formatter.
|
||||
log.SetFormatter(&log.JSONFormatter{})
|
||||
|
||||
// Output to stdout instead of the default stderr
|
||||
// Can be any io.Writer, see below for File example
|
||||
log.SetOutput(os.Stdout)
|
||||
|
||||
// Only log the warning severity or above.
|
||||
log.SetLevel(log.WarnLevel)
|
||||
}
|
||||
|
||||
func main() {
|
||||
log.WithFields(log.Fields{
|
||||
"animal": "walrus",
|
||||
"size": 10,
|
||||
}).Info("A group of walrus emerges from the ocean")
|
||||
|
||||
log.WithFields(log.Fields{
|
||||
"omg": true,
|
||||
"number": 122,
|
||||
}).Warn("The group's number increased tremendously!")
|
||||
|
||||
log.WithFields(log.Fields{
|
||||
"omg": true,
|
||||
"number": 100,
|
||||
}).Fatal("The ice breaks!")
|
||||
|
||||
// A common pattern is to re-use fields between logging statements by re-using
|
||||
// the logrus.Entry returned from WithFields()
|
||||
contextLogger := log.WithFields(log.Fields{
|
||||
"common": "this is a common field",
|
||||
"other": "I also should be logged always",
|
||||
})
|
||||
|
||||
contextLogger.Info("I'll be logged with common and other field")
|
||||
contextLogger.Info("Me too")
|
||||
}
|
||||
```
|
||||
|
||||
For more advanced usage such as logging to multiple locations from the same
|
||||
application, you can also create an instance of the `logrus` Logger:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Create a new instance of the logger. You can have any number of instances.
|
||||
var log = logrus.New()
|
||||
|
||||
func main() {
|
||||
// The API for setting attributes is a little different than the package level
|
||||
// exported logger. See Godoc.
|
||||
log.Out = os.Stdout
|
||||
|
||||
// You could set this to any `io.Writer` such as a file
|
||||
// file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666)
|
||||
// if err == nil {
|
||||
// log.Out = file
|
||||
// } else {
|
||||
// log.Info("Failed to log to file, using default stderr")
|
||||
// }
|
||||
|
||||
log.WithFields(logrus.Fields{
|
||||
"animal": "walrus",
|
||||
"size": 10,
|
||||
}).Info("A group of walrus emerges from the ocean")
|
||||
}
|
||||
```
|
||||
|
||||
#### Fields
|
||||
|
||||
Logrus encourages careful, structured logging through logging fields instead of
|
||||
long, unparseable error messages. For example, instead of: `log.Fatalf("Failed
|
||||
to send event %s to topic %s with key %d")`, you should log the much more
|
||||
discoverable:
|
||||
|
||||
```go
|
||||
log.WithFields(log.Fields{
|
||||
"event": event,
|
||||
"topic": topic,
|
||||
"key": key,
|
||||
}).Fatal("Failed to send event")
|
||||
```
|
||||
|
||||
We've found this API forces you to think about logging in a way that produces
|
||||
much more useful logging messages. We've been in countless situations where just
|
||||
a single added field to a log statement that was already there would've saved us
|
||||
hours. The `WithFields` call is optional.
|
||||
|
||||
In general, with Logrus using any of the `printf`-family functions should be
|
||||
seen as a hint you should add a field, however, you can still use the
|
||||
`printf`-family functions with Logrus.
|
||||
|
||||
#### Default Fields
|
||||
|
||||
Often it's helpful to have fields _always_ attached to log statements in an
|
||||
application or parts of one. For example, you may want to always log the
|
||||
`request_id` and `user_ip` in the context of a request. Instead of writing
|
||||
`log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on
|
||||
every line, you can create a `logrus.Entry` to pass around instead:
|
||||
|
||||
```go
|
||||
requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})
|
||||
requestLogger.Info("something happened on that request") # will log request_id and user_ip
|
||||
requestLogger.Warn("something not great happened")
|
||||
```
|
||||
|
||||
#### Hooks
|
||||
|
||||
You can add hooks for logging levels. For example to send errors to an exception
|
||||
tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to
|
||||
multiple places simultaneously, e.g. syslog.
|
||||
|
||||
Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in
|
||||
`init`:
|
||||
|
||||
```go
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "airbrake"
|
||||
logrus_syslog "github.com/sirupsen/logrus/hooks/syslog"
|
||||
"log/syslog"
|
||||
)
|
||||
|
||||
func init() {
|
||||
|
||||
// Use the Airbrake hook to report errors that have Error severity or above to
|
||||
// an exception tracker. You can create custom hooks, see the Hooks section.
|
||||
log.AddHook(airbrake.NewHook(123, "xyz", "production"))
|
||||
|
||||
hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
|
||||
if err != nil {
|
||||
log.Error("Unable to connect to local syslog daemon")
|
||||
} else {
|
||||
log.AddHook(hook)
|
||||
}
|
||||
}
|
||||
```
|
||||
Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md).
|
||||
|
||||
A list of currently known of service hook can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks)
|
||||
|
||||
|
||||
#### Level logging
|
||||
|
||||
Logrus has seven logging levels: Trace, Debug, Info, Warning, Error, Fatal and Panic.
|
||||
|
||||
```go
|
||||
log.Trace("Something very low level.")
|
||||
log.Debug("Useful debugging information.")
|
||||
log.Info("Something noteworthy happened!")
|
||||
log.Warn("You should probably take a look at this.")
|
||||
log.Error("Something failed but I'm not quitting.")
|
||||
// Calls os.Exit(1) after logging
|
||||
log.Fatal("Bye.")
|
||||
// Calls panic() after logging
|
||||
log.Panic("I'm bailing.")
|
||||
```
|
||||
|
||||
You can set the logging level on a `Logger`, then it will only log entries with
|
||||
that severity or anything above it:
|
||||
|
||||
```go
|
||||
// Will log anything that is info or above (warn, error, fatal, panic). Default.
|
||||
log.SetLevel(log.InfoLevel)
|
||||
```
|
||||
|
||||
It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose
|
||||
environment if your application has that.
|
||||
|
||||
#### Entries
|
||||
|
||||
Besides the fields added with `WithField` or `WithFields` some fields are
|
||||
automatically added to all logging events:
|
||||
|
||||
1. `time`. The timestamp when the entry was created.
|
||||
2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after
|
||||
the `AddFields` call. E.g. `Failed to send event.`
|
||||
3. `level`. The logging level. E.g. `info`.
|
||||
|
||||
#### Environments
|
||||
|
||||
Logrus has no notion of environment.
|
||||
|
||||
If you wish for hooks and formatters to only be used in specific environments,
|
||||
you should handle that yourself. For example, if your application has a global
|
||||
variable `Environment`, which is a string representation of the environment you
|
||||
could do:
|
||||
|
||||
```go
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
init() {
|
||||
// do something here to set environment depending on an environment variable
|
||||
// or command-line flag
|
||||
if Environment == "production" {
|
||||
log.SetFormatter(&log.JSONFormatter{})
|
||||
} else {
|
||||
// The TextFormatter is default, you don't actually have to do this.
|
||||
log.SetFormatter(&log.TextFormatter{})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This configuration is how `logrus` was intended to be used, but JSON in
|
||||
production is mostly only useful if you do log aggregation with tools like
|
||||
Splunk or Logstash.
|
||||
|
||||
#### Formatters
|
||||
|
||||
The built-in logging formatters are:
|
||||
|
||||
* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise
|
||||
without colors.
|
||||
* *Note:* to force colored output when there is no TTY, set the `ForceColors`
|
||||
field to `true`. To force no colored output even if there is a TTY set the
|
||||
`DisableColors` field to `true`. For Windows, see
|
||||
[github.com/mattn/go-colorable](https://github.com/mattn/go-colorable).
|
||||
* When colors are enabled, levels are truncated to 4 characters by default. To disable
|
||||
truncation set the `DisableLevelTruncation` field to `true`.
|
||||
* All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter).
|
||||
* `logrus.JSONFormatter`. Logs fields as JSON.
|
||||
* All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter).
|
||||
|
||||
Third party logging formatters:
|
||||
|
||||
* [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can be parsed by Kubernetes and Google Container Engine.
|
||||
* [`GELF`](https://github.com/fabienm/go-logrus-formatters). Formats entries so they comply to Graylog's [GELF 1.1 specification](http://docs.graylog.org/en/2.4/pages/gelf.html).
|
||||
* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events.
|
||||
* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout.
|
||||
* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦.
|
||||
* [`nested-logrus-formatter`](https://github.com/antonfisher/nested-logrus-formatter). Converts logrus fields to a nested structure.
|
||||
|
||||
You can define your formatter by implementing the `Formatter` interface,
|
||||
requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a
|
||||
`Fields` type (`map[string]interface{}`) with all your fields as well as the
|
||||
default ones (see Entries section above):
|
||||
|
||||
```go
|
||||
type MyJSONFormatter struct {
|
||||
}
|
||||
|
||||
log.SetFormatter(new(MyJSONFormatter))
|
||||
|
||||
func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
|
||||
// Note this doesn't include Time, Level and Message which are available on
|
||||
// the Entry. Consult `godoc` on information about those fields or read the
|
||||
// source of the official loggers.
|
||||
serialized, err := json.Marshal(entry.Data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
|
||||
}
|
||||
return append(serialized, '\n'), nil
|
||||
}
|
||||
```
|
||||
|
||||
#### Logger as an `io.Writer`
|
||||
|
||||
Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it.
|
||||
|
||||
```go
|
||||
w := logger.Writer()
|
||||
defer w.Close()
|
||||
|
||||
srv := http.Server{
|
||||
// create a stdlib log.Logger that writes to
|
||||
// logrus.Logger.
|
||||
ErrorLog: log.New(w, "", 0),
|
||||
}
|
||||
```
|
||||
|
||||
Each line written to that writer will be printed the usual way, using formatters
|
||||
and hooks. The level for those entries is `info`.
|
||||
|
||||
This means that we can override the standard library logger easily:
|
||||
|
||||
```go
|
||||
logger := logrus.New()
|
||||
logger.Formatter = &logrus.JSONFormatter{}
|
||||
|
||||
// Use logrus for standard log output
|
||||
// Note that `log` here references stdlib's log
|
||||
// Not logrus imported under the name `log`.
|
||||
log.SetOutput(logger.Writer())
|
||||
```
|
||||
|
||||
#### Rotation
|
||||
|
||||
Log rotation is not provided with Logrus. Log rotation should be done by an
|
||||
external program (like `logrotate(8)`) that can compress and delete old log
|
||||
entries. It should not be a feature of the application-level logger.
|
||||
|
||||
#### Tools
|
||||
|
||||
| Tool | Description |
|
||||
| ---- | ----------- |
|
||||
|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.|
|
||||
|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) |
|
||||
|
||||
#### Testing
|
||||
|
||||
Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides:
|
||||
|
||||
* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook
|
||||
* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any):
|
||||
|
||||
```go
|
||||
import(
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/sirupsen/logrus/hooks/test"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSomething(t*testing.T){
|
||||
logger, hook := test.NewNullLogger()
|
||||
logger.Error("Helloerror")
|
||||
|
||||
assert.Equal(t, 1, len(hook.Entries))
|
||||
assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level)
|
||||
assert.Equal(t, "Helloerror", hook.LastEntry().Message)
|
||||
|
||||
hook.Reset()
|
||||
assert.Nil(t, hook.LastEntry())
|
||||
}
|
||||
```
|
||||
|
||||
#### Fatal handlers
|
||||
|
||||
Logrus can register one or more functions that will be called when any `fatal`
|
||||
level message is logged. The registered handlers will be executed before
|
||||
logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need
|
||||
to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted.
|
||||
|
||||
```
|
||||
...
|
||||
handler := func() {
|
||||
// gracefully shutdown something...
|
||||
}
|
||||
logrus.RegisterExitHandler(handler)
|
||||
...
|
||||
```
|
||||
|
||||
#### Thread safety
|
||||
|
||||
By default, Logger is protected by a mutex for concurrent writes. The mutex is held when calling hooks and writing logs.
|
||||
If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking.
|
||||
|
||||
Situation when locking is not needed includes:
|
||||
|
||||
* You have no hooks registered, or hooks calling is already thread-safe.
|
||||
|
||||
* Writing to logger.Out is already thread-safe, for example:
|
||||
|
||||
1) logger.Out is protected by locks.
|
||||
|
||||
2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing)
|
||||
|
||||
(Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/)
|
|
@ -0,0 +1,76 @@
|
|||
package logrus
|
||||
|
||||
// The following code was sourced and modified from the
|
||||
// https://github.com/tebeka/atexit package governed by the following license:
|
||||
//
|
||||
// Copyright (c) 2012 Miki Tebeka <miki.tebeka@gmail.com>.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
// this software and associated documentation files (the "Software"), to deal in
|
||||
// the Software without restriction, including without limitation the rights to
|
||||
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
// the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
// subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
var handlers = []func(){}
|
||||
|
||||
func runHandler(handler func()) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err)
|
||||
}
|
||||
}()
|
||||
|
||||
handler()
|
||||
}
|
||||
|
||||
func runHandlers() {
|
||||
for _, handler := range handlers {
|
||||
runHandler(handler)
|
||||
}
|
||||
}
|
||||
|
||||
// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)
|
||||
func Exit(code int) {
|
||||
runHandlers()
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
// RegisterExitHandler appends a Logrus Exit handler to the list of handlers,
|
||||
// call logrus.Exit to invoke all handlers. The handlers will also be invoked when
|
||||
// any Fatal log entry is made.
|
||||
//
|
||||
// This method is useful when a caller wishes to use logrus to log a fatal
|
||||
// message but also needs to gracefully shutdown. An example usecase could be
|
||||
// closing database connections, or sending a alert that the application is
|
||||
// closing.
|
||||
func RegisterExitHandler(handler func()) {
|
||||
handlers = append(handlers, handler)
|
||||
}
|
||||
|
||||
// DeferExitHandler prepends a Logrus Exit handler to the list of handlers,
|
||||
// call logrus.Exit to invoke all handlers. The handlers will also be invoked when
|
||||
// any Fatal log entry is made.
|
||||
//
|
||||
// This method is useful when a caller wishes to use logrus to log a fatal
|
||||
// message but also needs to gracefully shutdown. An example usecase could be
|
||||
// closing database connections, or sending a alert that the application is
|
||||
// closing.
|
||||
func DeferExitHandler(handler func()) {
|
||||
handlers = append([]func(){handler}, handlers...)
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
version: "{build}"
|
||||
platform: x64
|
||||
clone_folder: c:\gopath\src\github.com\sirupsen\logrus
|
||||
environment:
|
||||
GOPATH: c:\gopath
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
install:
|
||||
- set PATH=%GOPATH%\bin;c:\go\bin;%PATH%
|
||||
- go version
|
||||
build_script:
|
||||
- go get -t
|
||||
- go test
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue