github.com/mattermosttest/mattermost-server/v5@v5.0.0-20200917143240-9dfa12e121f9/manualtesting/manual_testing.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package manualtesting
     5  
     6  import (
     7  	"hash/fnv"
     8  	"math/rand"
     9  	"net/http"
    10  	"net/url"
    11  	"strconv"
    12  	"time"
    13  
    14  	"github.com/mattermost/mattermost-server/v5/api4"
    15  	"github.com/mattermost/mattermost-server/v5/app"
    16  	"github.com/mattermost/mattermost-server/v5/mlog"
    17  	"github.com/mattermost/mattermost-server/v5/model"
    18  	"github.com/mattermost/mattermost-server/v5/utils"
    19  	"github.com/mattermost/mattermost-server/v5/web"
    20  )
    21  
    22  // TestEnvironment is a helper struct used for tests in manualtesting.
    23  type TestEnvironment struct {
    24  	Params        map[string][]string
    25  	Client        *model.Client4
    26  	CreatedTeamID string
    27  	CreatedUserID string
    28  	Context       *web.Context
    29  	Writer        http.ResponseWriter
    30  	Request       *http.Request
    31  }
    32  
    33  // Init adds manualtest endpoint to the API.
    34  func Init(api4 *api4.API) {
    35  	api4.BaseRoutes.Root.Handle("/manualtest", api4.ApiHandler(manualTest)).Methods("GET")
    36  }
    37  
    38  func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) {
    39  	// Let the world know
    40  	mlog.Info("Setting up for manual test...")
    41  
    42  	// URL Parameters
    43  	params, err := url.ParseQuery(r.URL.RawQuery)
    44  	if err != nil {
    45  		c.Err = model.NewAppError("/manual", "manaultesting.manual_test.parse.app_error", nil, "", http.StatusBadRequest)
    46  		return
    47  	}
    48  
    49  	// Grab a uuid (if available) to seed the random number generator so we don't get conflicts.
    50  	uid, ok := params["uid"]
    51  	if ok {
    52  		hasher := fnv.New32a()
    53  		hasher.Write([]byte(uid[0] + strconv.Itoa(int(time.Now().UTC().UnixNano()))))
    54  		hash := hasher.Sum32()
    55  		rand.Seed(int64(hash))
    56  	} else {
    57  		mlog.Debug("No uid in URL")
    58  	}
    59  
    60  	// Create a client for tests to use
    61  	client := model.NewAPIv4Client("http://localhost" + *c.App.Config().ServiceSettings.ListenAddress)
    62  
    63  	// Check for username parameter and create a user if present
    64  	username, ok1 := params["username"]
    65  	teamDisplayName, ok2 := params["teamname"]
    66  	var teamID string
    67  	var userID string
    68  	if ok1 && ok2 {
    69  		mlog.Info("Creating user and team")
    70  		// Create team for testing
    71  		team := &model.Team{
    72  			DisplayName: teamDisplayName[0],
    73  			Name:        "zz" + utils.RandomName(utils.Range{Begin: 20, End: 20}, utils.LOWERCASE),
    74  			Email:       "success+" + model.NewId() + "simulator.amazonses.com",
    75  			Type:        model.TEAM_OPEN,
    76  		}
    77  
    78  		createdTeam, err := c.App.Srv().Store.Team().Save(team)
    79  		if err != nil {
    80  			c.Err = err
    81  			return
    82  		}
    83  
    84  		channel := &model.Channel{DisplayName: "Town Square", Name: "town-square", Type: model.CHANNEL_OPEN, TeamId: createdTeam.Id}
    85  		if _, err := c.App.CreateChannel(channel, false); err != nil {
    86  			c.Err = err
    87  			return
    88  		}
    89  
    90  		teamID = createdTeam.Id
    91  
    92  		// Create user for testing
    93  		user := &model.User{
    94  			Email:    "success+" + model.NewId() + "simulator.amazonses.com",
    95  			Nickname: username[0],
    96  			Password: app.USER_PASSWORD}
    97  
    98  		user, resp := client.CreateUser(user)
    99  		if resp.Error != nil {
   100  			c.Err = resp.Error
   101  			return
   102  		}
   103  
   104  		c.App.Srv().Store.User().VerifyEmail(user.Id, user.Email)
   105  		c.App.Srv().Store.Team().SaveMember(&model.TeamMember{TeamId: teamID, UserId: user.Id}, *c.App.Config().TeamSettings.MaxUsersPerTeam)
   106  
   107  		userID = user.Id
   108  
   109  		// Login as user to generate auth token
   110  		_, resp = client.LoginById(user.Id, app.USER_PASSWORD)
   111  		if resp.Error != nil {
   112  			c.Err = resp.Error
   113  			return
   114  		}
   115  
   116  		// Respond with an auth token this can be overridden by a specific test as required
   117  		sessionCookie := &http.Cookie{
   118  			Name:     model.SESSION_COOKIE_TOKEN,
   119  			Value:    client.AuthToken,
   120  			Path:     "/",
   121  			MaxAge:   *c.App.Config().ServiceSettings.SessionLengthWebInDays * 60 * 60 * 24,
   122  			HttpOnly: true,
   123  		}
   124  		http.SetCookie(w, sessionCookie)
   125  		http.Redirect(w, r, "/channels/town-square", http.StatusTemporaryRedirect)
   126  	}
   127  
   128  	// Setup test environment
   129  	env := TestEnvironment{
   130  		Params:        params,
   131  		Client:        client,
   132  		CreatedTeamID: teamID,
   133  		CreatedUserID: userID,
   134  		Context:       c,
   135  		Writer:        w,
   136  		Request:       r,
   137  	}
   138  
   139  	// Grab the test ID and pick the test
   140  	testname, ok := params["test"]
   141  	if !ok {
   142  		c.Err = model.NewAppError("/manual", "manaultesting.manual_test.parse.app_error", nil, "", http.StatusBadRequest)
   143  		return
   144  	}
   145  
   146  	switch testname[0] {
   147  	case "autolink":
   148  		c.Err = testAutoLink(env)
   149  		// ADD YOUR NEW TEST HERE!
   150  	case "general":
   151  	}
   152  }
   153  
   154  func getChannelID(a app.AppIface, channelname string, teamid string, userid string) (string, bool) {
   155  	// Grab all the channels
   156  	channels, err := a.Srv().Store.Channel().GetChannels(teamid, userid, false, 0)
   157  	if err != nil {
   158  		mlog.Debug("Unable to get channels")
   159  		return "", false
   160  	}
   161  
   162  	for _, channel := range *channels {
   163  		if channel.Name == channelname {
   164  			return channel.Id, true
   165  		}
   166  	}
   167  	mlog.Debug("Could not find channel", mlog.String("Channel name", channelname), mlog.Int("Possibilities searched", len(*channels)))
   168  	return "", false
   169  }