From e98836cc3f31aaa36a010942c4e7c6d58d505496 Mon Sep 17 00:00:00 2001 From: Jamie Hurst Date: Wed, 8 Jan 2025 20:59:17 +0000 Subject: [PATCH] Remove giphy adapter and all usages --- .github/workflows/test.yml | 1 - Dockerfile | 6 +- Dockerfile.test | 6 +- README.md | 11 +-- api/README.md | 4 +- internal/app/app.go | 6 -- internal/app/controller/apiv1/create.go | 2 +- internal/app/controller/apiv1/list.go | 2 +- internal/app/controller/apiv1/single.go | 2 +- internal/app/controller/apiv1/update.go | 2 +- internal/app/controller/web/edit.go | 2 +- internal/app/controller/web/index.go | 2 +- internal/app/controller/web/new.go | 2 +- internal/app/controller/web/sitemap.go | 2 +- internal/app/controller/web/view.go | 4 +- internal/app/model/giphy.go | 98 ------------------------- internal/app/model/giphy_test.go | 67 ----------------- internal/app/model/journal.go | 8 +- internal/app/model/journal_test.go | 8 +- journal.go | 11 --- journal_test.go | 16 ---- pkg/adapter/giphy/giphy.go | 50 ------------- pkg/adapter/giphy/giphy_test.go | 49 ------------- pkg/adapter/json/json.go | 33 --------- pkg/adapter/json/json_test.go | 36 --------- test/mocks/adapter/adapter.go | 17 ----- test/mocks/database/database.go | 35 --------- 27 files changed, 28 insertions(+), 454 deletions(-) delete mode 100644 internal/app/model/giphy.go delete mode 100644 internal/app/model/giphy_test.go delete mode 100644 pkg/adapter/giphy/giphy.go delete mode 100644 pkg/adapter/giphy/giphy_test.go delete mode 100644 pkg/adapter/json/json.go delete mode 100644 pkg/adapter/json/json_test.go diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 618999c..6f5036d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13,7 +13,6 @@ env: GOPATH: /home/runner/work/journal/journal/go J_ARTICLES_PER_PAGE: '' J_DB_PATH: '' - J_GIPHY_API_KEY: '' J_PORT: '' J_TITLE: '' diff --git a/Dockerfile b/Dockerfile index 54e9dc2..e665387 100644 --- a/Dockerfile +++ b/Dockerfile @@ -19,9 +19,13 @@ RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install --no-instal ENV GOPATH "/go" ENV J_ARTICLES_PER_PAGE "" +ENV J_CREATE "" ENV J_DB_PATH "" -ENV J_GIPHY_API_KEY "" +ENV J_DESCRIPTION "" +ENV J_EDIT "" +ENV J_GA_CODE "" ENV J_PORT "" +ENV J_THEME "" ENV J_TITLE "" VOLUME /go/data diff --git a/Dockerfile.test b/Dockerfile.test index 5b98d2d..69a5729 100644 --- a/Dockerfile.test +++ b/Dockerfile.test @@ -2,9 +2,13 @@ FROM golang:1.22-bookworm LABEL org.opencontainers.image.source=https://github.com/jamiefdhurst/journal ENV J_ARTICLES_PER_PAGE "" +ENV J_CREATE "" ENV J_DB_PATH "" -ENV J_GIPHY_API_KEY "" +ENV J_DESCRIPTION "" +ENV J_EDIT "" +ENV J_GA_CODE "" ENV J_PORT "" +ENV J_THEME "" ENV J_TITLE "" WORKDIR /go/src/github.com/jamiefdhurst/journal diff --git a/README.md b/README.md index 6528757..6d7ba3b 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,9 @@ _Please note: you will need Docker installed on your local machine._ docker run --rm -v ./data:/go/data -p 3000:3000 -it journal:latest ``` -## Environment Variables +## Configuration through Environment Variables + +The application uses environment variables to configure all aspects. * `J_ARTICLES_PER_PAGE` - Articles to display per page, default `20` * `J_CREATE` - Set to `0` to disable article creation @@ -51,17 +53,10 @@ _Please note: you will need Docker installed on your local machine._ * `J_DESCRIPTION` - Set the HTML description of the Journal * `J_EDIT` - Set to `0` to disable article modification * `J_GA_CODE` - Google Analytics tag value, starts with `UA-`, or ignore to disable Google Analytics -* `J_GIPHY_API_KEY` - Set to a GIPHY API key to use, or ignore to disable GIPHY * `J_PORT` - Port to expose over HTTP, default is `3000` * `J_THEME` - Theme to use from within the _web/themes_ folder, defaults to `default` * `J_TITLE` - Set the title of the Journal -To use the API key within your Docker setup, include it as follows: - -```bash -docker run --rm -e J_GIPHY_API_KEY=... -v ./data:/go/data -p 3000:3000 -it journal:latest -``` - ## Layout The project layout follows the standard set out in the following document: diff --git a/api/README.md b/api/README.md index a699874..062a9f4 100644 --- a/api/README.md +++ b/api/README.md @@ -39,7 +39,7 @@ Contains all current post reources in reverse date order. "slug": "example-post", "title": "An Example Post", "date": "2018-05-18T12:53:22Z", - "content": "

TEST

:gif:id:cE1qRt8nl6Neo:

" + "content": "

TEST

" } ] ``` @@ -66,7 +66,7 @@ Contains the single post. "slug": "example-post", "title": "An Example Post", "date": "2018-05-18T12:53:22Z", - "content": "

TEST

:gif:id:cE1qRt8nl6Neo:

" + "content": "

TEST

" } ``` diff --git a/internal/app/app.go b/internal/app/app.go index 63858f9..8aaec01 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -16,16 +16,10 @@ type Database interface { Query(sql string, args ...interface{}) (rows.Rows, error) } -// GiphyAdapter Interface for API -type GiphyAdapter interface { - SearchForID(s string) (string, error) -} - // Container Define the main container for the application type Container struct { Configuration Configuration Db Database - Giphy GiphyAdapter Version string } diff --git a/internal/app/controller/apiv1/create.go b/internal/app/controller/apiv1/create.go index 1c1e8a6..38bc12e 100644 --- a/internal/app/controller/apiv1/create.go +++ b/internal/app/controller/apiv1/create.go @@ -32,7 +32,7 @@ func (c *Create) Run(response http.ResponseWriter, request *http.Request) { response.WriteHeader(http.StatusBadRequest) } else { journal := model.Journal{ID: 0, Slug: model.Slugify(journalRequest.Title), Title: journalRequest.Title, Date: journalRequest.Date, Content: journalRequest.Content} - js := model.Journals{Container: container, Gs: model.GiphyAdapter(container)} + js := model.Journals{Container: container} journal = js.Save(journal) response.WriteHeader(http.StatusCreated) encoder := json.NewEncoder(response) diff --git a/internal/app/controller/apiv1/list.go b/internal/app/controller/apiv1/list.go index 2c9d8f9..d92eb99 100644 --- a/internal/app/controller/apiv1/list.go +++ b/internal/app/controller/apiv1/list.go @@ -17,7 +17,7 @@ type List struct { // Run List action func (c *List) Run(response http.ResponseWriter, request *http.Request) { - js := model.Journals{Container: c.Super.Container.(*app.Container), Gs: model.GiphyAdapter(c.Super.Container.(*app.Container))} + js := model.Journals{Container: c.Super.Container.(*app.Container)} journals := js.FetchAll() response.Header().Add("Content-Type", "application/json") encoder := json.NewEncoder(response) diff --git a/internal/app/controller/apiv1/single.go b/internal/app/controller/apiv1/single.go index 4b3c9f0..bb1dc2f 100644 --- a/internal/app/controller/apiv1/single.go +++ b/internal/app/controller/apiv1/single.go @@ -17,7 +17,7 @@ type Single struct { // Run Single action func (c *Single) Run(response http.ResponseWriter, request *http.Request) { - js := model.Journals{Container: c.Super.Container.(*app.Container), Gs: model.GiphyAdapter(c.Super.Container.(*app.Container))} + js := model.Journals{Container: c.Super.Container.(*app.Container)} journal := js.FindBySlug(c.Params[1]) response.Header().Add("Content-Type", "application/json") diff --git a/internal/app/controller/apiv1/update.go b/internal/app/controller/apiv1/update.go index 9ab15ad..3ef7f30 100644 --- a/internal/app/controller/apiv1/update.go +++ b/internal/app/controller/apiv1/update.go @@ -22,7 +22,7 @@ func (c *Update) Run(response http.ResponseWriter, request *http.Request) { return } - js := model.Journals{Container: container, Gs: model.GiphyAdapter(container)} + js := model.Journals{Container: container} journal := js.FindBySlug(c.Params[1]) response.Header().Add("Content-Type", "application/json") diff --git a/internal/app/controller/web/edit.go b/internal/app/controller/web/edit.go index 2649e67..1579eb7 100644 --- a/internal/app/controller/web/edit.go +++ b/internal/app/controller/web/edit.go @@ -24,7 +24,7 @@ func (c *Edit) Run(response http.ResponseWriter, request *http.Request) { return } - js := model.Journals{Container: c.Super.Container.(*app.Container), Gs: model.GiphyAdapter(c.Super.Container.(*app.Container))} + js := model.Journals{Container: c.Super.Container.(*app.Container)} c.Journal = js.FindBySlug(c.Params[1]) if c.Journal.ID == 0 { diff --git a/internal/app/controller/web/index.go b/internal/app/controller/web/index.go index f68c1b7..76eb6e1 100644 --- a/internal/app/controller/web/index.go +++ b/internal/app/controller/web/index.go @@ -24,7 +24,7 @@ type Index struct { func (c *Index) Run(response http.ResponseWriter, request *http.Request) { container := c.Super.Container.(*app.Container) - js := model.Journals{Container: container, Gs: model.GiphyAdapter(container)} + js := model.Journals{Container: container} paginationQuery := database.PaginationQuery{Page: 1, ResultsPerPage: container.Configuration.ArticlesPerPage} query := request.URL.Query() diff --git a/internal/app/controller/web/new.go b/internal/app/controller/web/new.go index e041478..1d7c5a3 100644 --- a/internal/app/controller/web/new.go +++ b/internal/app/controller/web/new.go @@ -48,7 +48,7 @@ func (c *New) Run(response http.ResponseWriter, request *http.Request) { return } - js := model.Journals{Container: container, Gs: model.GiphyAdapter(container)} + js := model.Journals{Container: container} journal := model.Journal{ID: 0, Slug: model.Slugify(request.FormValue("title")), Title: request.FormValue("title"), Date: request.FormValue("date"), Content: request.FormValue("content")} js.Save(journal) diff --git a/internal/app/controller/web/sitemap.go b/internal/app/controller/web/sitemap.go index 9b7daf9..b53aae0 100644 --- a/internal/app/controller/web/sitemap.go +++ b/internal/app/controller/web/sitemap.go @@ -20,7 +20,7 @@ type Sitemap struct { func (c *Sitemap) Run(response http.ResponseWriter, request *http.Request) { container := c.Super.Container.(*app.Container) - js := model.Journals{Container: container, Gs: model.GiphyAdapter(container)} + js := model.Journals{Container: container} c.Journals = js.FetchAll() diff --git a/internal/app/controller/web/view.go b/internal/app/controller/web/view.go index fe297b7..3302bc5 100644 --- a/internal/app/controller/web/view.go +++ b/internal/app/controller/web/view.go @@ -20,7 +20,7 @@ type View struct { // Run View action func (c *View) Run(response http.ResponseWriter, request *http.Request) { - js := model.Journals{Container: c.Super.Container.(*app.Container), Gs: model.GiphyAdapter(c.Super.Container.(*app.Container))} + js := model.Journals{Container: c.Super.Container.(*app.Container)} c.Journal = js.FindBySlug(c.Params[1]) if c.Journal.ID == 0 { @@ -28,8 +28,6 @@ func (c *View) Run(response http.ResponseWriter, request *http.Request) { } else { c.Next = js.FindNext(c.Journal.ID) c.Prev = js.FindPrev(c.Journal.ID) - gs := model.Giphys{} - c.Journal.Content = gs.ConvertIDsToIframes(c.Journal.Content) template, _ := template.ParseFiles( "./web/templates/_layout/default.html.tmpl", "./web/templates/view.html.tmpl") diff --git a/internal/app/model/giphy.go b/internal/app/model/giphy.go deleted file mode 100644 index ecb57a9..0000000 --- a/internal/app/model/giphy.go +++ /dev/null @@ -1,98 +0,0 @@ -package model - -import ( - "regexp" - "strings" - - "github.com/jamiefdhurst/journal/internal/app" -) - -type giphyContent struct { - IDs []string - searches []string -} - -// GiphysExtractor Interface for extracting a Giphy search -type GiphysExtractor interface { - ExtractContentsAndSearchAPI(s string) string -} - -// GiphyAdapter Get the correct adapter to use depending on wither an API key is available -func GiphyAdapter(c *app.Container) GiphysExtractor { - if c.Giphy == nil { - return &GiphysDisabled{Container: c} - } - return &Giphys{Container: c} -} - -// GiphysDisabled Whne no API key available, perform no action -type GiphysDisabled struct { - Container *app.Container -} - -// ExtractContentsAndSearchAPI Perform no action without an API key -func (gs *GiphysDisabled) ExtractContentsAndSearchAPI(s string) string { - return s -} - -// Giphys Common resource link for Giphy actions -type Giphys struct { - Container *app.Container -} - -// ConvertIDsToIframes Convert any IDs in the content into ", 1) - } - } - - return s -} - -// ExtractContentsAndSearchAPI Convert any searches, connecting to Giphy where required -func (gs *Giphys) ExtractContentsAndSearchAPI(s string) string { - content := gs.findTags(s) - if len(content.searches) > 0 { - for _, i := range content.searches { - id, err := gs.Container.Giphy.SearchForID(i) - if err == nil { - s = strings.Replace(s, ":gif:"+i, ":gif:id:"+id, 1) - } else { - s = strings.Replace(s, ":gif:"+i, "", 1) - } - } - } - - return s -} - -func (gs Giphys) findIds(s string) []string { - reIDs := regexp.MustCompile(":gif:id:(\\w+)") - onlyIDs := []string{} - IDs := reIDs.FindAllStringSubmatch(s, -1) - for _, i := range IDs { - onlyIDs = append(onlyIDs, i[1]) - } - - return onlyIDs -} - -func (gs Giphys) findSearches(s string) []string { - reSearches := regexp.MustCompile("gif:([\\w\\-]+)") - onlySearches := []string{} - searches := reSearches.FindAllStringSubmatch(s, -1) - for _, j := range searches { - if j[1] != "id" { - onlySearches = append(onlySearches, j[1]) - } - } - - return onlySearches -} - -func (gs Giphys) findTags(s string) giphyContent { - return giphyContent{gs.findIds(s), gs.findSearches(s)} -} diff --git a/internal/app/model/giphy_test.go b/internal/app/model/giphy_test.go deleted file mode 100644 index 2584c8a..0000000 --- a/internal/app/model/giphy_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package model - -import ( - "reflect" - "testing" - - "github.com/jamiefdhurst/journal/internal/app" - - "github.com/jamiefdhurst/journal/test/mocks/adapter" -) - -func TestGiphyAdapter_NoAdapterInContainer(t *testing.T) { - - // Test no adapter - container := &app.Container{} - gs := GiphyAdapter(container) - if reflect.TypeOf(gs).String() != "*model.GiphysDisabled" { - t.Errorf("Expected GiphysDisabled type, got '%s'", reflect.TypeOf(gs).String()) - } - - // Test adapter - client := &adapter.MockGiphyAdapter{} - container = &app.Container{Giphy: client} - gs = GiphyAdapter(container) - if reflect.TypeOf(gs).String() != "*model.Giphys" { - t.Errorf("Expected Giphys type, got '%s'", reflect.TypeOf(gs).String()) - } -} - -func TestGiphysDisabled_ExtractContentsAndSearchAPI(t *testing.T) { - testString := "Hello\n:gif:id:1234567\n:gif:testsearch\n" - gs := GiphysDisabled{} - newString := gs.ExtractContentsAndSearchAPI(testString) - if newString != "Hello\n:gif:id:1234567\n:gif:testsearch\n" { - t.Errorf("Expected no string changes to have happened") - } -} - -func TestGiphys_ConvertIDsToIframes(t *testing.T) { - testString := "Hello\n:gif:id:1234567\n:gif:testsearch" - gs := Giphys{} - newString := gs.ConvertIDsToIframes(testString) - if newString != "Hello\n\n:gif:testsearch" { - t.Errorf("Expected iframe substitution did not occur") - } -} - -func TestGiphys_ExtractContentsAndSearchAPI(t *testing.T) { - - // Test without error - testString := "Hello\n:gif:id:1234567\n:gif:testsearch\n" - client := &adapter.MockGiphyAdapter{} - container := &app.Container{Giphy: client} - gs := Giphys{Container: container} - newString := gs.ExtractContentsAndSearchAPI(testString) - if newString != "Hello\n:gif:id:1234567\n:gif:id:9991234\n" { - t.Errorf("Expected search to have been converted") - } - - // Test with error - client.ErrorMode = true - gs = Giphys{Container: container} - newString = gs.ExtractContentsAndSearchAPI(testString) - if newString != "Hello\n:gif:id:1234567\n\n" { - t.Errorf("Expected search to have been converted and error to have been handled") - } -} diff --git a/internal/app/model/journal.go b/internal/app/model/journal.go index 2473f90..1095f05 100644 --- a/internal/app/model/journal.go +++ b/internal/app/model/journal.go @@ -27,7 +27,7 @@ type Journal struct { // GetDate Get the friendly date for the Journal func (j Journal) GetDate() string { - re := regexp.MustCompile("\\d{4}\\-\\d{2}\\-\\d{2}") + re := regexp.MustCompile(`\d{4}\-\d{2}\-\d{2}`) date := re.FindString(j.Date) timeObj, err := time.Parse("2006-01-02", date) if err != nil { @@ -38,7 +38,7 @@ func (j Journal) GetDate() string { // GetEditableDate Get the date string for editing func (j Journal) GetEditableDate() string { - re := regexp.MustCompile("\\d{4}\\-\\d{2}\\-\\d{2}") + re := regexp.MustCompile(`\d{4}\-\d{2}\-\d{2}`) return re.FindString(j.Date) } @@ -59,7 +59,6 @@ func (j Journal) GetExcerpt() string { // Journals Common database resource link for Journal actions type Journals struct { Container *app.Container - Gs GiphysExtractor } // CreateTable Create the actual table @@ -144,7 +143,6 @@ func (js *Journals) Save(j Journal) Journal { var res sql.Result // Convert content for saving - j.Content = js.Gs.ExtractContentsAndSearchAPI(j.Content) if j.Slug == "" { j.Slug = Slugify(j.Title) } @@ -192,7 +190,7 @@ func (js *Journals) loadSingle(rows rows.Rows, err error) Journal { // Slugify Utility to convert a string into a slug func Slugify(s string) string { - re := regexp.MustCompile("[\\W+]") + re := regexp.MustCompile(`[\W+]`) return strings.ToLower(re.ReplaceAllString(s, "-")) } diff --git a/internal/app/model/journal_test.go b/internal/app/model/journal_test.go index 0a0c8ac..789e38d 100644 --- a/internal/app/model/journal_test.go +++ b/internal/app/model/journal_test.go @@ -282,9 +282,8 @@ func TestJournals_FindPrev(t *testing.T) { func TestJournals_Save(t *testing.T) { db := &database.MockSqlite{Result: &database.MockResult{}} db.Rows = &database.MockRowsEmpty{} - gs := &database.MockGiphyExtractor{} container := &app.Container{Db: db} - js := Journals{Container: container, Gs: gs} + js := Journals{Container: container} // Test with new Journal journal := js.Save(Journal{ID: 0, Title: "Testing"}) @@ -297,11 +296,6 @@ func TestJournals_Save(t *testing.T) { if journal.ID != 2 || journal.Title != "Testing 2" { t.Error("Expected same Journal to have been returned with new ID") } - - // Check Giphy calls - if gs.CalledTimes != 2 { - t.Error("Expected Giphy to have been called 2 times within test scope") - } } func TestSlugify(t *testing.T) { diff --git a/journal.go b/journal.go index ce66bba..a8cfaf4 100644 --- a/journal.go +++ b/journal.go @@ -7,8 +7,6 @@ import ( "os" "github.com/akrylysov/algnhsa" - "github.com/jamiefdhurst/journal/pkg/adapter/giphy" - "github.com/jamiefdhurst/journal/pkg/adapter/json" "github.com/jamiefdhurst/journal/internal/app" "github.com/jamiefdhurst/journal/internal/app/model" @@ -51,14 +49,6 @@ func loadDatabase() func() { } } -func loadGiphy() { - giphyAPIKey := os.Getenv("J_GIPHY_API_KEY") - if giphyAPIKey != "" { - log.Println("Enabling GIPHY client...") - container.Giphy = &giphy.Client{APIKey: giphyAPIKey, Client: &json.Client{}} - } -} - func main() { const version = "0.9.6" @@ -74,7 +64,6 @@ func main() { closeFunc := loadDatabase() defer closeFunc() - loadGiphy() router := router.NewRouter(container) diff --git a/journal_test.go b/journal_test.go index 6e6884e..e20cc1b 100644 --- a/journal_test.go +++ b/journal_test.go @@ -9,9 +9,6 @@ import ( "strings" "testing" - "github.com/jamiefdhurst/journal/pkg/adapter/giphy" - "github.com/jamiefdhurst/journal/pkg/adapter/json" - "github.com/jamiefdhurst/journal/internal/app" "github.com/jamiefdhurst/journal/internal/app/model" "github.com/jamiefdhurst/journal/internal/app/router" @@ -33,7 +30,6 @@ func init() { } func fixtures(t *testing.T) { - adapter := giphy.Client{Client: &json.Client{}} db := &database.Sqlite{} if err := db.Connect("test/data/test.db"); err != nil { t.Error("Could not open test database for writing...") @@ -41,7 +37,6 @@ func fixtures(t *testing.T) { // Setup container container.Db = db - container.Giphy = adapter js := model.Journals{Container: container} db.Exec("DROP TABLE journal") @@ -75,17 +70,6 @@ func TestLoadDatabase(t *testing.T) { closeFunc() } -func TestLoadGiphy(t *testing.T) { - existing := os.Getenv("J_GIPHY_API_KEY") - os.Setenv("J_GIPHY_API_KEY", "foobar") - loadGiphy() - os.Setenv("J_GIPHY_API_KEY", existing) - - if container.Giphy == nil { - t.Error("Expected Giphy adapter to be setup") - } -} - func TestApiv1List(t *testing.T) { fixtures(t) diff --git a/pkg/adapter/giphy/giphy.go b/pkg/adapter/giphy/giphy.go deleted file mode 100644 index c78444d..0000000 --- a/pkg/adapter/giphy/giphy.go +++ /dev/null @@ -1,50 +0,0 @@ -package giphy - -import ( - "errors" - - "github.com/jamiefdhurst/journal/pkg/adapter/json" -) - -// APIResponse Response holder for GIPHY API call -type APIResponse struct { - Data APIResponseData `json:"data"` -} - -// APIResponseData Data object within API response -type APIResponseData struct { - ID string `json:"id"` -} - -// Adapter Interface for API -type Adapter interface { - SearchForID(s string) (string, error) -} - -// Client Actual API client -type Client struct { - Adapter - APIKey string - Client json.Adapter -} - -// SearchForID Search the Giphy API for a given tag and return the resulting ID -func (c Client) SearchForID(s string) (string, error) { - if c.APIKey == "" { - return "", errors.New("No API key was found for GIPHY") - } - - // Perform search - url := "https://api.giphy.com/v1/gifs/random?api_key=" + c.APIKey + "&tag=" + s + "&rating=G" - response := APIResponse{} - err := c.Client.Get(url, &response) - if err != nil { - return "", err - } - - if response.Data.ID != "" { - return response.Data.ID, nil - } - - return "", errors.New("No response was provided") -} diff --git a/pkg/adapter/giphy/giphy_test.go b/pkg/adapter/giphy/giphy_test.go deleted file mode 100644 index fc78ebd..0000000 --- a/pkg/adapter/giphy/giphy_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package giphy - -import ( - "testing" - - "github.com/jamiefdhurst/journal/test/mocks/adapter" -) - -func TestGiphy_SearchForID(t *testing.T) { - - var ( - response string - err error - ) - - // Test no API key - client := Client{} - _, err = client.SearchForID("test 1") - if err == nil { - t.Error("Expected API key error was not achieved") - } - - // Test error - mockClient := &adapter.MockClient{} - mockClient.ErrorMode = true - client.APIKey = "API123456" - client.Client = mockClient - _, err = client.SearchForID("test 2") - if err == nil { - t.Error("Expected clietn error was not achieved") - } - - // Test valid response - validJSON := "{\"data\":{\"id\":\"testing123\"}}" - mockClient.ErrorMode = false - mockClient.Response = validJSON - response, err = client.SearchForID("test 3") - if err != nil || response != "testing123" { - t.Error("Expected ID to be returned") - } - - // Test invalid response - invalidJSON := "{\"data\":{}}" - mockClient.Response = invalidJSON - response, err = client.SearchForID("test 4") - if err == nil || response != "" { - t.Error("Expected error to be returned with invalid response") - } -} diff --git a/pkg/adapter/json/json.go b/pkg/adapter/json/json.go deleted file mode 100644 index 72827d0..0000000 --- a/pkg/adapter/json/json.go +++ /dev/null @@ -1,33 +0,0 @@ -package json - -import ( - "encoding/json" - "net/http" -) - -// Adapter Common interface for a JSON client -type Adapter interface { - Get(url string, destination interface{}) error -} - -// Client for interacting with JSON over HTTP -type Client struct{} - -// Get Perform a GET request to retrieve JSON -func (j Client) Get(url string, destination interface{}) error { - req, err := http.NewRequest("GET", url, nil) - if err != nil { - return err - } - req.Header.Add("Accept", "application/json") - req.Header.Add("User-Agent", "Journal") - client := &http.Client{} - rs, err := client.Do(req) - if err != nil { - return err - } - defer rs.Body.Close() - json.NewDecoder(rs.Body).Decode(&destination) - - return nil -} diff --git a/pkg/adapter/json/json_test.go b/pkg/adapter/json/json_test.go deleted file mode 100644 index 8c42145..0000000 --- a/pkg/adapter/json/json_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package json - -import "testing" - -type TestResponse struct { - UserID int `json:"userId"` - ID int `json:"id"` - Title string `json:"title"` - Completed bool `json:"completed"` -} - -const testURL = "https://jsonplaceholder.typicode.com/todos/1" - -func TestGet(t *testing.T) { - response := &TestResponse{} - jsonAdapter := Client{} - err := jsonAdapter.Get(testURL, response) - if err != nil { - t.Error("Expected no error from test API call") - } - if response.ID != 1 && response.Title != "delectus aut autem" { - t.Error("Expected result from JSON decode was not achieved") - } - - // Create error in request - err = jsonAdapter.Get("://Not a URL", response) - if err == nil { - t.Error("Expected error with blank request was not achieved") - } - - // Create error in response - err = jsonAdapter.Get("https://not-a-url.com", response) - if err == nil { - t.Error("Expected error with invalid request was not achieved") - } -} diff --git a/test/mocks/adapter/adapter.go b/test/mocks/adapter/adapter.go index e668b18..6f3b5f7 100644 --- a/test/mocks/adapter/adapter.go +++ b/test/mocks/adapter/adapter.go @@ -6,23 +6,6 @@ import ( "errors" ) -// MockGiphyAdapter Mock the Giphy adapter -type MockGiphyAdapter struct { - ErrorMode bool -} - -// SearchForID Present to search -func (m MockGiphyAdapter) SearchForID(s string) (string, error) { - if m.ErrorMode { - return "", errors.New("Simulating error") - } - if s == "testsearch" { - return "9991234", nil - } - - return "0000000", nil -} - // MockClient Mock an HTTP client type MockClient struct { ErrorMode bool diff --git a/test/mocks/database/database.go b/test/mocks/database/database.go index 30ec7fa..9199bed 100644 --- a/test/mocks/database/database.go +++ b/test/mocks/database/database.go @@ -28,41 +28,6 @@ func (m *MockDatabase) Query(sql string, args ...interface{}) (rows.Rows, error) return nil, nil } -// MockGiphyExtractor Mock the Giphy Extractor interface -type MockGiphyExtractor struct { - CalledTimes int -} - -// ExtractContentsAndSearchAPI Mock the full call -func (m *MockGiphyExtractor) ExtractContentsAndSearchAPI(s string) string { - m.CalledTimes++ - return s -} - -// MockGiphy_SingleRow Mock single row for the Giphy API -type MockGiphy_SingleRow struct { - MockRowsEmpty - RowNumber int -} - -// Next Mock 1 row -func (m *MockGiphy_SingleRow) Next() bool { - m.RowNumber++ - if m.RowNumber < 2 { - return true - } - return false -} - -// Scan Return the data -func (m *MockGiphy_SingleRow) Scan(dest ...interface{}) error { - if m.RowNumber == 1 { - *dest[0].(*int) = 1 - *dest[1].(*string) = "API123456" - } - return nil -} - // MockJournal_MultipleRows Mock multiple rows returned for a Journal type MockJournal_MultipleRows struct { MockRowsEmpty