1// Copyright (C) MongoDB, Inc. 2014-present.
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may
4// not use this file except in compliance with the License. You may obtain
5// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6
7package mongofiles
8
9import (
10	"fmt"
11	"testing"
12
13	"github.com/mongodb/mongo-tools/common/db"
14	"github.com/mongodb/mongo-tools/common/options"
15	. "github.com/smartystreets/goconvey/convey"
16)
17
18// Regression test for TOOLS-1741
19func TestWriteConcernWithURIParsing(t *testing.T) {
20	Convey("With an IngestOptions and ToolsOptions", t, func() {
21
22		// create an 'EnabledOptions' to determine what options should be able to be
23		// parsed and set form the input.
24		enabled := options.EnabledOptions{URI: true}
25
26		// create a new tools options to hold the parsed options
27		opts := options.New("", "", enabled)
28
29		// create a 'StorageOptions', which holds the value of the write concern
30		// for mongofiles.
31		storageOpts := &StorageOptions{}
32		opts.AddOptions(storageOpts)
33
34		// Specify that a write concern set on the URI is not an error and is a known
35		// possible option.
36		opts.URI.AddKnownURIParameters(options.KnownURIOptionsWriteConcern)
37
38		Convey("Parsing with no value should leave write concern empty", func() {
39			_, err := opts.ParseArgs([]string{})
40			So(err, ShouldBeNil)
41			So(storageOpts.WriteConcern, ShouldEqual, "")
42			Convey("and building write concern object, WMode should be majority", func() {
43				sessionSafety, err := db.BuildWriteConcern(storageOpts.WriteConcern, "",
44					opts.ParsedConnString())
45				So(err, ShouldBeNil)
46				So(sessionSafety.WMode, ShouldEqual, "majority")
47			})
48		})
49
50		Convey("Parsing with no writeconcern in URI should not error", func() {
51			args := []string{
52				"--uri", "mongodb://localhost:27017/test",
53			}
54			_, err := opts.ParseArgs(args)
55			So(err, ShouldBeNil)
56			So(storageOpts.WriteConcern, ShouldEqual, "")
57			Convey("and parsing write concern, WMode should be majority", func() {
58				sessionSafety, err := db.BuildWriteConcern(storageOpts.WriteConcern, "",
59					opts.ParsedConnString())
60				So(err, ShouldBeNil)
61				So(sessionSafety, ShouldNotBeNil)
62				So(sessionSafety.WMode, ShouldEqual, "majority")
63			})
64		})
65		Convey("Parsing with both writeconcern in URI and command line should error", func() {
66			args := []string{
67				"--uri", "mongodb://localhost:27017/test",
68				"--writeConcern", "majority",
69			}
70			_, err := opts.ParseArgs(args)
71			So(err, ShouldBeNil)
72			So(storageOpts.WriteConcern, ShouldEqual, "majority")
73			Convey("and parsing write concern, WMode should be majority", func() {
74				_, err := db.BuildWriteConcern(storageOpts.WriteConcern, "",
75					opts.ParsedConnString())
76				So(err, ShouldResemble, fmt.Errorf("cannot specify writeConcern string and connectionString object"))
77			})
78		})
79	})
80}
81