<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by H. Enes Gökdağ on Medium]]></title>
        <description><![CDATA[Stories by H. Enes Gökdağ on Medium]]></description>
        <link>https://medium.com/@henesgokdag?source=rss-4b7f00e49ed9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VFddPg4VlBa6q_L10dl6dw.jpeg</url>
            <title>Stories by H. Enes Gökdağ on Medium</title>
            <link>https://medium.com/@henesgokdag?source=rss-4b7f00e49ed9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 17:41:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@henesgokdag/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Golang Object Creation With Protobuf]]></title>
            <link>https://blog.stackademic.com/golang-object-creation-with-protobuf-99e10b1b70ae?source=rss-4b7f00e49ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/99e10b1b70ae</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[protocol-buffers]]></category>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[H. Enes Gökdağ]]></dc:creator>
            <pubDate>Mon, 04 Dec 2023 06:13:14 GMT</pubDate>
            <atom:updated>2023-12-07T01:34:56.872Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nD0h76J8mE196tVgBnBL7Q.jpeg" /></figure><p>In this article, I will be talking about my experience with generating request response structures using protobuf in Go language. I wrote this article to share the problems I encountered in this experience and what I learned in case anyone wants to use Proto in their own Golang projects. The documentation on the protobuf side did not seem very sufficient to me, but this may be related to me.</p><p>You can access the repo I created below.</p><p><a href="https://github.com/henesgokdag/request-response-generate-with-golang">GitHub - henesgokdag/request-response-generate-with-golang</a></p><p>To start, we had to write proto files. There were two different language options: proto2 and proto3. I preferred proto2 because the optional and required fields have been removed in proto3.</p><p>proto2 keywords:</p><ul><li>nullable field → optional</li><li>mandatory field → required</li><li>map → map&lt;field1,field2&gt;</li><li>array → repeated</li></ul><p>Apart from this, we need to number the fields in the message. Below is an example of all these fields being used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zwrA73i7HRAYaOHk26n5uQ.png" /></figure><p>After completing the proto side, we generated our structs with the protoc-gen-go library in the makefile file. In our provider API project, we saw that the slices generated were created as pointers, while the slices were not pointers in our model. While marshalling the struct in our current flow, if slice is nil, we turn it into a structure that returns empty slice. You can see the struct created by protobuf below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdKAKeyiVQCkQuagfMQ-Rw.png" /></figure><p>We encountered the cannot parse invalid wire-format data error, so we researched on how to generate slices without pointers and learned that slices can be created without pointers when we generate them with protoc-gen-gogofaster in the <a href="https://github.com/gogo/protobuf/tree/master">https://github.com/gogo/protobuf/tree/master</a> project.</p><p>While writing the tests, we received errors when we used the unmarshal and marshal methods under “github.com/gogo/protobuf/proto” and “google.golang.org/protobuf/proto”. The reason for this is the import changes we made in the makefile to be able to use protoc-gen-gogofaster. I added an example for both of them in the product_gogo_test.go file.</p><pre>regenerate: install<br>    (protoc -I=. -I=$(GOPATH)/src/github.com/gogo/protobuf/protobuf -I=$(GOPATH)/src --gogofaster_out=Mgoogle/protobuf/descriptor.proto=github.com/gogo/protobuf/protoc-gen-gogo/descriptor,Mgoogle/protobuf/duration.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/struct.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/timestamp.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/wrappers.proto=github.com/gogo/protobuf/types,Mgoogle/protobuf/any.proto=github.com/gogo/protobuf/types:./generated_gogo/response gogo_proto/response.proto)</pre><p>After meeting with the someone with experience, we learned that we needed to use jsonpb as marshaler and unmarshaler and we implemented the implementation accordingly. We set emitDefaults to true in marshals so that if bool fields were false, JSON would not be returned. For instance, if we have an int field and its value is 0, it is not added to the JSON.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eL4oNqjV7XWNoSKg-wLTpA.png" /></figure><p>During our tests, we noticed that the name values of the fields in the JSON were not as we wanted. For example, the field we expected to be productId was ProductId. We used the json_data key to fix this, and the final version of our proto file was as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmof00slmYXX4YQrD3YeGA.png" /></figure><p>You can see the struct created by protobuf below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xErFu3kxQwDoASCS2uQR6g.png" /></figure><p>We used int32 because there was no int on the proto side, and these fields were created as int32 on the go side, and we added code to convert it.</p><p>Additionally, the fields we wrote int64 in proto were created as strings when creating JSON. After examining this issue, we saw that this was not a bug but a feature included in the documentation. There is no problem in marshal and unmarshal operations since they are handled by the generator.</p><p>On the project side, we had to add codes that perform conversion operations between response objects and domain objects. You can check out the codes that make the necessary conversions related to the struct I used while playing with proto files. I’m adding the cycles I used for the Gogo side below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bzJ5knaYiNQzpJbILhiBsw.png" /></figure><p>Thank you for reading.</p><p>Resources</p><ul><li><a href="https://protobuf.dev/getting-started/gotutorial/">Protocol Buffer Basics: Go</a></li><li><a href="https://github.com/protocolbuffers/protobuf-go">GitHub - protocolbuffers/protobuf-go: Go support for Google&#39;s protocol buffers</a></li><li><a href="https://github.com/gogo/protobuf/">GitHub - gogo/protobuf: [Deprecated] Protocol Buffers for Go with Gadgets</a></li></ul><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99e10b1b70ae" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/golang-object-creation-with-protobuf-99e10b1b70ae">Golang Object Creation With Protobuf</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[log/slog Library And Golang Logger Comparision]]></title>
            <link>https://henesgokdag.medium.com/log-slog-library-and-golang-logger-comparision-9e2c3de3d515?source=rss-4b7f00e49ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e2c3de3d515</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[logs]]></category>
            <category><![CDATA[slog]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[logging]]></category>
            <dc:creator><![CDATA[H. Enes Gökdağ]]></dc:creator>
            <pubDate>Wed, 11 Oct 2023 11:37:22 GMT</pubDate>
            <atom:updated>2023-10-11T11:37:22.618Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mNYsbRRFrRHd-0TF.png" /></figure><p>Golang standard library had a logger package called log. But structural logging has become increasingly important for go developers and various 3rd party logging libraries have been created and used by people. For example, logrus has been used in 100,000 different libraries. Standard logging library with support for structured logging library <strong>log/slog</strong> is published with Go 1.21 version.</p><p>As the Trendyol Indexing team, we use zap as a logger library in our golang projects. Since we were curious about the performance of the log/slog library, I started researching the log/slog library during special interest time sessions. In light of the information we have obtained, we will try to find the answer to the question of whether we should change our logger library to log/slog.</p><p>In this article, I will provide information on the features, advantages, and disadvantages of the log/slog library.</p><h3>Table Of Contents</h3><ul><li><a href="#8de2">log/slog Features</a><br>- <a href="#8538">Handler Options</a><br>- <a href="#4711">Add Custom Field</a><br>- <a href="#7323">Child Logger</a><br>- <a href="#d7c6">Hiding Sensitive Data</a><br>- <a href="#8881">Use slog as a Frontend</a><br>- <a href="#c26e">Use slog as a Default Logger</a></li><li><a href="#5c0e">Benchmark Results</a><br>- <a href="#d638">Pros</a><br>- <a href="#da76">Cons</a></li><li><a href="#c067">Conclusion</a></li></ul><p>You can look examples on my github repo.</p><p><a href="https://github.com/henesgokdag/golang-logger-compare">GitHub - henesgokdag/golang-logger-compare</a></p><h3>log/slog Features</h3><h4>Handler Options</h4><p>The library is divided into frontend as Logger and backend interface as Handler. The log/slog feature comes with two different Handlers that are used to format the logs. One of these Handlers is a text handler, and the other is a JSON handler. Additionally, you can create your custom handler by using the Handler interface to implement it. Also, golang has published a guide on how to write log/slog handlers. You can reach it from <a href="https://github.com/golang/example/blob/master/slog-handler-guide/README.md">here.</a></p><pre>type Handler interface {<br> Enabled(context.Context, Level) bool<br> Handle(context.Context, Record) error<br> WithAttrs(attrs []Attr) Handler<br> WithGroup(name string) Handler<br>}</pre><p><strong>Json Handler</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lN9FpYfBtTBex7m7S24iTw.png" /></figure><p>Output</p><p>We didn’t see debug message in logs because we set log level to info.</p><pre><br>{“time”:”2023–09–02T10:06:23.682743+03:00&quot;,”level”:”INFO”,”msg”:”This is an Info message”}<br>{“time”:”2023–09–02T10:06:23.682747+03:00&quot;,”level”:”WARN”,”msg”:”This is a Warning message”}<br>{“time”:”2023–09–02T10:06:23.68275+03:00&quot;,”level”:”ERROR”,”msg”:”This is an Error message”}</pre><p><strong>TextHandler</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ml0mH_4lJYvdMc96DmcMnw.png" /></figure><p>Output</p><pre><br>time=2023–09–02T10:06:19.906+03:00 level=INFO msg=”This is an Info message”<br>time=2023–09–02T10:06:19.906+03:00 level=WARN msg=”This is a Warning message”<br>time=2023–09–02T10:06:19.906+03:00 level=ERROR msg=”This is an Error message”</pre><h4>Add Custom Field</h4><p>You can add custom fields to your log. If we want to add a custom field to a log, there are two ways to do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KWcqSOSTU9smmjl4sabUQA.png" /></figure><p>Output</p><pre><br>{“time”:”2023–09–02T10:09:25.279457+03:00&quot;,”level”:”INFO”,”msg”:”hello”,”test”:1}<br>{“time”:”2023–09–02T10:09:25.280265+03:00&quot;,”level”:”INFO”,”msg”:”This is an Info message”,”test”:1}<br></pre><h4>Child Logger</h4><p>If you need to choose specific attributes for all logs, you can utilize a child logger. These loggers are useful because they establish a new logging context inherited from their parent logger while also allowing for the inclusion of extra fields. In Slog, you can create child loggers by using the Logger.With() method. This method receives one or multiple key/value pairs, and generates a new Logger that includes the designated attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPlXACRW5PEgV2Ms4awnxg.png" /></figure><h4>Output</h4><pre><br>{“time”:”2023–09–02T10:09:25.280315+03:00&quot;,”level”:”INFO”,”msg”:”image upload successful”,”program_info”:{“pid”:92036,”go_version”:”go1.21rc4&quot;},”image_id”:”39ud88&quot;}<br>{“time”:”2023–09–02T10:09:25.28032+03:00&quot;,”level”:”WARN”,”msg”:”storage is 90% full”,”program_info”:{“pid”:92036,”go_version”:”go1.21rc4&quot;},”available_space”:”900.1 mb”}<br>{&quot;time&quot;:&quot;2023–09–02T10:09:25.280315+03:00&quot;,&quot;level&quot;:&quot;INFO&quot;,&quot;msg&quot;:&quot;image upload successful&quot;,&quot;program_info&quot;:{&quot;pid&quot;:92036,&quot;go_version&quot;:&quot;go1.21rc4&quot;},&quot;image_id&quot;:&quot;39ud88&quot;}<br>{&quot;time&quot;:&quot;2023–09–02T10:09:25.28032+03:00&quot;,&quot;level&quot;:&quot;WARN&quot;,&quot;msg&quot;:&quot;storage is 90% full&quot;,&quot;program_info&quot;:{&quot;pid&quot;:92036,&quot;go_version&quot;:&quot;go1.21rc4&quot;},&quot;available_space&quot;:&quot;900.1 mb&quot;}</pre><h4>Hiding Sensitive Data</h4><p>The LogValuer interface lets you choose the type of output you want to generate, instead of logging certain fields. This interface can be used to hiding sensitive data. By doing so, you can prevent personal details like name, surname, and password from being displayed in the logs.</p><pre><br>type LogValuer interface {<br>LogValue() Value<br>}</pre><p>Example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOydTTusy9YvW3-MQgiV-Q.png" /></figure><p>Output</p><pre><br>{“time”:”2023–09–14T10:04:51.272601+03:00&quot;,”level”:”INFO”,”msg”:”info”,”user”:”user-12234&quot;}</pre><h4>Use slog as a Frontend</h4><p>I mentioned above that the library uses the logger interface for the frontend and the handler interface for the backend. That way, existing logging packages can talk to a common backend, so the packages that use them can interoperate without having to be rewritten. Handlers are written or in progress for many common logging packages, including Zap, logr and hclog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mjbYI061nHnFsAlYUeociQ.png" /></figure><p>Output</p><pre><br>{“level”:”info”,”ts”:1694675091.2726688,”msg”:”Using Slog frontend with Zap backend!”,”process_id”:71993}</pre><h4>Use slog as a Default Logger</h4><p>Also, you can use slog as a default logger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YIwNy12D9LQprE60OW48ZA.png" /></figure><p>Output</p><pre><br>{“time”:”2023–09–02T10:09:25.280487+03:00&quot;,”level”:”INFO”,”msg”:”Hello from old logger”}</pre><h3>Benchmark Results</h3><p>I used 5 different logger libraries in benchmark tests and I did 2 different tests with struct and without struct.</p><p><strong>With Struct Benchmark Result</strong></p><p>I used the following struct in the tests.</p><pre>package util<br><br>type Person struct {<br> Name    string<br> Age     int<br> Address string<br>}<br><br>type Car struct {<br> Brand string<br> Model string<br> Year  int<br>}<br><br>type ExampleStruct struct {<br> PeopleList []Person<br> CarList    []Car<br> Field1     int64<br> Field2     string<br> Field3     float64<br> Field4     bool<br> Field5     []byte<br> Field6     map[string]int<br> Field7     [1000]int<br> Field8     []*ExampleStruct<br> Field9     interface{}<br> Field10    int<br>}<br><br>func getExampleData() ExampleStruct {<br> people := []Person{<br>  {Name: &quot;John&quot;, Age: 30, Address: &quot;London&quot;},<br>  {Name: &quot;Michael&quot;, Age: 25, Address: &quot;Manchester&quot;},<br>  {Name: &quot;Jane&quot;, Age: 28, Address: &quot;Liverpool&quot;},<br>  {Name: &quot;Jane&quot;, Age: 28, Address: &quot;Liverpool&quot;},<br>  {Name: &quot;Jane&quot;, Age: 28, Address: &quot;Liverpool&quot;},<br>  {Name: &quot;Jane&quot;, Age: 28, Address: &quot;Liverpool&quot;},<br>  {Name: &quot;Jane&quot;, Age: 28, Address: &quot;Liverpool&quot;},<br> }<br><br> cars := []Car{<br>  {Brand: &quot;Toyota&quot;, Model: &quot;Corolla&quot;, Year: 2020},<br>  {Brand: &quot;Honda&quot;, Model: &quot;Civic&quot;, Year: 2019},<br>  {Brand: &quot;Honda&quot;, Model: &quot;Civic&quot;, Year: 2019},<br>  {Brand: &quot;Honda&quot;, Model: &quot;Civic&quot;, Year: 2019},<br>  {Brand: &quot;Honda&quot;, Model: &quot;Civic&quot;, Year: 2019},<br>  {Brand: &quot;Honda&quot;, Model: &quot;Civic&quot;, Year: 2019},<br>  {Brand: &quot;Honda&quot;, Model: &quot;Civic&quot;, Year: 2019},<br>  {Brand: &quot;Honda&quot;, Model: &quot;Civic&quot;, Year: 2019},<br> }<br><br> return ExampleStruct{<br>  PeopleList: people,<br>  CarList:    cars,<br>  Field1:     1234567890,<br>  Field2:     &quot;This is a huge struct example&quot;,<br>  Field3:     3.141592653589793,<br>  Field4:     true,<br>  Field5:     []byte{1, 2, 3, 4, 5},<br>  Field6:     map[string]int{&quot;a&quot;: 1, &quot;b&quot;: 2, &quot;c&quot;: 3},<br>  Field7:     [1000]int{}, // Initializing an array with 1000 elements<br>  Field8:     []*ExampleStruct{},<br>  Field9:     nil,<br>  Field10:    1,<br> }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KR4DSBaA7_EHPmQ_Vno90w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*sMQXfgVNT5glJXD-aIWPWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*MeY-7iaSd4ixBc4oYnO4lA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*gTqssMI-RTF1gMsqWvOWOw.png" /></figure><p><strong>Without Struct Benchmark Results</strong></p><p>I used the following model in the tests.</p><pre>logger.Debug(&quot;This is a Debug message&quot;)<br>logger.Info(&quot;This is an Info message&quot;)<br>logger.Warn(&quot;This is a Warning message&quot;)<br>logger.Error(&quot;This is an Error message&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MHQ81RFZYnyTJo3sheao_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*BiUp8b_CktwB_6Z_TOkgrg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*YgLV8F3QCLm-mrHHXq_uGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*8bFtYUErMYGfNWl3k_6bMw.png" /></figure><p>You can also take a look at the benchmark made by the Zap library <a href="https://github.com/uber-go/zap#performance">here</a>.</p><h3>Pros</h3><p><em>- A </em>more performant handler can be written because it has its own interface.</p><p><em>- </em>log/slog golang’s stlib.</p><p><em>- </em>In benchmarks, log/slog is more performant than apex and logrus libraries.</p><p><em>- </em>SlogJsonHandler’s number of allocations per operation value in tests with struct is much lower than other libraries.</p><h3>Cons</h3><p>- Extremely slow compared to Zap in benchmarks tests without structs. (This is very big problem because google said <a href="https://go.dev/blog/slog">“We found that over 95% of calls to logging methods pass five or fewer attributes.”</a>)</p><h3>Conclucion</h3><p>As a result, if you are going to start a new project, you can try the log/slog package or if you are using logrus, etc. as a log package in an existing project, you can consider converting to log/slog. Since we have zap in our current projects, which is more performant, I will not recommend a change to my team. Maybe in the future, I can recommend a structure where we use zap as a backend with a more performant handler.</p><p>I would like to thank the indexing team members for making the article better with their feedback.</p><h3>Sources</h3><ul><li><a href="https://www.highlight.io/blog/5-best-logging-libraries-for-go">https://www.highlight.io/blog/5-best-logging-libraries-for-go</a></li><li><a href="https://betterstack.com/community/guides/logging/logging-framework/">https://betterstack.com/community/guides/logging/logging-framework/</a></li><li><a href="https://betterstack.com/community/guides/logging/logging-in-go/#creating-and-using-child-loggers">https://betterstack.com/community/guides/logging/logging-in-go/#creating-and-using-child-loggers</a></li><li><a href="https://github.com/uber-go/zap#performance">https://github.com/uber-go/zap#performance</a></li><li><a href="https://go.dev/blog/slog">https://go.dev/blog/slog</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e2c3de3d515" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Tracing]]></title>
            <link>https://henesgokdag.medium.com/distributed-tracing-9300d55e7245?source=rss-4b7f00e49ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9300d55e7245</guid>
            <category><![CDATA[distributed-tracing]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[tracing]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[H. Enes Gökdağ]]></dc:creator>
            <pubDate>Sat, 15 Apr 2023 09:05:38 GMT</pubDate>
            <atom:updated>2023-04-28T10:41:48.587Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, me and my colleague Yağızhan Kerim Değer will try to give you information about distributed tracing. You can access the Turkish version of the article at <a href="https://medium.com/@yagizhankerim/distributed-tracing-7b43b45a72b9">https://medium.com/@yagizhankerim/distributed-tracing-7b43b45a72b9</a></p><p><strong>Distributed Tracing</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dok6pO5RPtY0E8fsVqhmoA.png" /></figure><p>Distributed Tracing traces the flow of a system from frontend devices to backend services and the database level, providing telemetry data. This data can help detect performance issues in different components of an application, as well as identify their root causes.</p><p>In this technique, there is a trace and span structure to ensure tracking. Trace shows us the path that a request follows between all services it passes through. Also, each trace has an ID and spans are contained within the trace. A span represents different parts of the request. For example, a request made from Service A can be defined as a span. The message that will be sent to Kafka as a result of this request can be a different span, consuming this message by Service B can be a different span, and performing a DB operation as a result of this can be evaluated as a different span. The data in the spans can include information such as the start and end times of the process, which components are involved in the process, which process steps are taken, how long it takes to complete which process steps, and which errors occur. This data can be used to monitor the application’s performance and detect performance issues.</p><p>Distributed tracing systems are typically used in heavy processing, large-scale applications, and microservices. These systems are designed to track transactions between different components of an application and are very useful for monitoring application performance.</p><blockquote>Advantages:</blockquote><p>Reducing MTTD (Mean Time to Detect) and MTTR (Mean Time to Resolve) times: Distributed tracing provides complete flow visibility, helping to reduce the time spent identifying and solving the main causes of encountered problems.</p><p>Learning System Architecture: Thanks to distributed tracing, we get detailed information about which services are communicating with each other. This information helps us optimize system performance.</p><p>Inter-Team Collaboration and Increased Productivity: In microservice architecture, different teams can communicate with each other to perform a request. Thanks to Distributed Tracing, we can see which team is responsible for errors and which team is responsible for solving them.</p><blockquote>Disadvantages:</blockquote><p>Manual Instrumentation: In distributed tracing, you need to manually add code to your application to start tracing requests, which can consume time.</p><p>I will give you information about some distributed tracing tools.</p><h3>Open Tracing</h3><p>A system needs to be instrumented to make it observable. OpenTelemetry is an open source project aimed at making systems more observable. To achieve this, the code needs to emit traces, metrics, and logs. In the past, there was a lack of standardization because different observability tools used different libraries. To address this, two open source projects were created: OpenTracing, which was a Cloud Native Computing Foundation (CNCF) project that provided an API for sending telemetry data to an observability tool, and OpenCensus, which was a Google open source community project that provided a set of language-specific libraries that developers could use to instrument their code and submit it to any of the supported observability tools. These two projects were merged in May 2019 under the name OpenTelemetry (OTel), creating a single standard.</p><h3><strong>Jaeger</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gMMKOSKAWwZHru9pytl51A.jpeg" /></figure><p>Jaeger is an open source distributed tracing tool inspired by Dapper and OpenZipkin, created by Uber Technologies and donated to CNCF. Its advantages include being a free tool with an easy-to-use UI, supported and developed by a large community, and it offers support for many different programming languages. It can also easily integrate with Kubernetes and other cloud-based environments. However, it may cause performance issues for large-scale systems.</p><h3>Zipkin</h3><p>Zipkin is another open source distributed tracing tool that has support for many different programming languages. It has basic features such as a UI, data storage, and query tools. It was developed by Twitter in 2010 and handed over to the open source community in 2016 under the name OpenZipkin. Its advantages include being a free tool with an easy-to-use UI, and support for many different programming languages. However, integration with Kubernetes and other cloud-based environments can be difficult and it may cause performance issues for large-scale systems.</p><h3>AppDynamics</h3><p>AppDynamics is a distributed tracing tool for large-scale systems, but it is a paid tool. Its advantages include excellent performance for high-scale systems, a rich UI, and advanced analysis features. However, it is costly to use and not open source.</p><h3>Datadog</h3><p>Datadog is a scalable distributed tracing tool that offers a UI, analysis, and alarm features, and can integrate with other monitoring tools. Its advantages include being scalable and suitable for large-scale systems, having an easy-to-use UI, and easy integration with other monitoring tools. However, it is also a paid tool and not open source.</p><h3>AWS X-Ray</h3><p>AWS X-Ray is a distributed tracing tool for AWS-based applications that provides full integration with other AWS tools and offers UI, analysis, and reporting features. Its advantages include being a distributed tracing tool suitable for AWS-based applications, providing full integration with other AWS tools, and having an easy-to-use UI. However, it is only available for AWS-based applications, and integration with other tools is somewhat limited.</p><p>Sources</p><ul><li><a href="https://www.dynatrace.com/support/help/observe-and-explore/purepath-distributed-traces">Distributed tracing by PurePath® technology</a></li><li><a href="https://www.datadoghq.com/knowledge-center/distributed-tracing/">What is Distributed Tracing? How it Works &amp; Use Cases | Datadog</a></li><li><a href="https://www.aspecto.io/blog/jaeger-tracing-the-ultimate-guide/">Jaeger Tracing: The Ultimate Guide | Aspecto</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9300d55e7245" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Logic of Mocking and Wiremock]]></title>
            <link>https://blog.stackademic.com/the-logic-of-mocking-and-wiremock-e712c7af02db?source=rss-4b7f00e49ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e712c7af02db</guid>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[api-testing]]></category>
            <category><![CDATA[api-test-automation]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[H. Enes Gökdağ]]></dc:creator>
            <pubDate>Fri, 11 Nov 2022 18:38:59 GMT</pubDate>
            <atom:updated>2023-12-18T01:50:29.810Z</atom:updated>
            <content:encoded><![CDATA[<p>Greetings, today I will try to give you information about the logic of mocking and using Wiremock.</p><p>Mock objects are simulated objects that emulate the behavior of natural objects in a controlled manner. To test the behavior of an object, we need to mock the dependencies of that object. In addition, while testing an API, we can mock the components it depends on, and prevent faulty situations in other APIs from destabilizing our API.</p><p>First of all, I will write a simple API that requests an API, and then I will talk about how to mock this request with wiremock. I chose The Star Wars API as the API that I’m requesting. You can learn about its use at <a href="https://swapi.dev/documentation.">https://swapi.dev/documentation.</a></p><p>You can review the 2 projects I used in my article below.</p><ul><li><a href="https://github.com/henesgokdag/basic-order-api">GitHub - henesgokdag/basic-order-api</a></li><li><a href="https://github.com/henesgokdag/basic-order-api-acceptance-test">GitHub - henesgokdag/basic-order-api-acceptance-test</a></li></ul><p>I wrote our API in java and used spring boot. The API has a single endpoint and the orderRequest requested from the user on my endpoint that performs this post /createOrder operation is as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0384c22d4b58c35662d0ef75789dfc9c/href">https://medium.com/media/0384c22d4b58c35662d0ef75789dfc9c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVeNTlLNoVWcw-F0229fHg.png" /></figure><p>I call swapi with taking the value in the peopleId field here. For example, when entered 1 to peopleId, it goes to <a href="https://swapi.dev/api/people/1">https://swapi.dev/api/people/1</a> and returns the following response.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/289539d82946b5d8296e2a8fd2517ed4/href">https://medium.com/media/289539d82946b5d8296e2a8fd2517ed4/href</a></iframe><p>Then, as a response, I will return the PeopleResponse object that the swap above returns and the entered peopleId, orderName, and orderDescription values. I didn’t need to use DB as this is a very simple API. Below is an example of orderResponse.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e82fa450e9b026f65e1603c12af0126a/href">https://medium.com/media/e82fa450e9b026f65e1603c12af0126a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QwUzL2EendR6eWoD_t5-Wg.jpeg" /></figure><p>Also, I have added an error message that returns 400: “Darth Vader cannot create an order.”, if the name value in the incoming PeopleResponse object is Darth Vader. Response Example appears below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e6b0fe5ad03af2059b69a4f85c6fec0/href">https://medium.com/media/4e6b0fe5ad03af2059b69a4f85c6fec0/href</a></iframe><p>Let’s say I deploy this API in an isolated environment. When I send request the /createOrder endpoint, it will send a request to the swapi, but since the swap is not found in this isolated environment, it will get an error, so I will not be able to check whether my API is working correctly. I need to mock the swapi so I can check if it works correctly. Here wiremock comes to our rescue.</p><p>Wiremock is a library that can be used to mock web services. It is easy to use. It looks at <a href="http://localhost:8083/,">http://localhost:8083/,</a> which I deployed from docker with the command below.</p><p>docker run -it — rm -p 8083:8083 wiremock/wiremock — port 8083</p><p>In the basic-order-API project, I write <a href="http://localhost:8083/">http://localhost:8083/</a> as baseUrl variable at the createSwapiService method. This method uses retrofit and returns swapiService. Thanks to Wiremock, I will simulate a call to the /people/{customer_id} endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4BTj6WUfYxVSqvTAxx-LQ.png" /></figure><p>For this, I first create the basic-order-API-acceptance-test project. I add the models that use in our API to this project. Here I am calling our API using RestAssured. Then I start writing my tests. I have 2 tests, shouldCreateOrder and shouldNotCreateOrderWhenPeopleIsDarthVader. For the API to work properly here, for example, when I send peopleId 1 in my OrderRequest, I need to create a People response object at <a href="http://localhost:8083/people/1">http://localhost:8083/people/1</a> in wiremock. I do this with the method I wrote below. I specify that I will create a mock with the StubFor method. In the get method, I give the endpoint to which I will return, and in the willReturn method, there is the HTTP status code value that I want to return withStatus, the Header value to which I will return withHeader and the Body value to which I will return withBody.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f6207fcb8785bc5def70a24e340edc8/href">https://medium.com/media/4f6207fcb8785bc5def70a24e340edc8/href</a></iframe><p>If there are special cases that I want to cover with the mock here, I can handle that too. If you remember, in our API, if the person&#39;s name is DarthVader, “Darth Vader cannot create an order.” I wrote a control that sends a message and returns 400. To test this, I added a boolean isDarthVader control to the method, if this value is true, Darth Vader is set to the name value in the PeopleResponse, so I can handle this situation.</p><p>In our shouldCreateOrder test, I send the isDarthVader flag false to the mock, so because of the randomDataProvider I wrote, a PeopleResponse whose name is Luke Skywalker returns, and when I call our ap, I see that the peopleResponse returns 200 and my other assertions are passed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91868795a8a37b232617a017a5354821/href">https://medium.com/media/91868795a8a37b232617a017a5354821/href</a></iframe><p>In our shouldNotCreateOrderWhenPeopleIsDarthVader test, I return the above-mentioned isDarthVader flag true, so I assert that 400 is returned from our API and the message value of ErrorResponse is “Darth Vader cannot create order”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89b0db92a4f5554c6fd80d50d70a5310/href">https://medium.com/media/89b0db92a4f5554c6fd80d50d70a5310/href</a></iframe><p>If I want to see the response object returned by wiremock on localhost, I can see the object created by entering the value <a href="http://localhost:8083/people/%7BpeopleId%7D">http://localhost:8083/people/{peopleId}</a> into my browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*WzLacQfMyvBBpvDxIoEXpA.png" /></figure><p>I go to <a href="http://localhost:8083/__admin/mappings">http://localhost:8083/__admin/mappings</a> to see all the mocks that have been created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wcudIC5AuUWeAGebyzx_oQ.png" /></figure><p>For more detailed information about Wiremock, you can check <a href="https://wiremock.org/docs.">https://wiremock.org/docs.</a></p><p>As an example of the difficulties that mocking will create, we can give the change of the contract of the objects we mocked. In this case, according to our mock-up, the API will continue to work in the isolated environment, but will receive an error in the environment where the real dependency is present. To prevent this situation, we should write a contract test. When the contract test fails, we notice a change in the models of the relevant API.</p><p>I tried to give information about the logic of mocking and the use of Wiremock in a simple way, I hope it was useful. Take care and see you in my next post.</p><p>Resources:</p><p><a href="https://en.wikipedia.org/wiki/Mock_object">https://en.wikipedia.org/wiki/Mock_object</a> <a href="https://wiremock.org/docs/stubbing/">https://wiremock.org/docs/stubbing/</a></p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e712c7af02db" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/the-logic-of-mocking-and-wiremock-e712c7af02db">The Logic of Mocking and Wiremock</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testcontainers]]></title>
            <link>https://henesgokdag.medium.com/testcontainers-74c204d4146e?source=rss-4b7f00e49ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/74c204d4146e</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[testcontainer]]></category>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[couchbase]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[H. Enes Gökdağ]]></dc:creator>
            <pubDate>Mon, 01 Aug 2022 15:58:07 GMT</pubDate>
            <atom:updated>2022-08-01T15:58:07.132Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mrdvj1pb-nRoSR0_DJk0LQ.png" /></figure><p>Selamlar bugün size testcontainers hakkında bilgi vermeye çalışacağım. <br>Projelerimize unit test yazarız ama sadece unit test yazmak yeterli olmayabilir. Örneğin bir database methodunun kullanıldığı bir methoda ilgili database methodunu mocklayıp unit test yazıldığında yazdığımız kodun istediğimiz şekilde çalıştığını görebiliriz ama database’in davranışını göremeyiz.</p><p>Testcontainers sayesinde dockerla istediğimiz db öğesini kaldırıp db ile projemizin entegrasyon testini yapabiliriz. Bunun dışında testcontainers ile entegrasyon testleri için kafka ve rabbitmq gibi message queuelarını kaldırıp entegrasyon testleri yapabilir ayrıca browser kaldırıp ui ve acceptance testlerimizi koşabiliriz.</p><p>Ben bugün yapacağım projede spring boot ile couchbase’e data yazan basit bir uygulama yazacağım ardından önce unit testleri daha sonrasında da Testcontainers ile entegrasyon testlerini yazacağım.</p><p>Proje Linki:</p><p><a href="https://github.com/henesgokdag/test-container-example">GitHub - henesgokdag/test-container-example</a></p><p>Projede String title ve String text alanlarına sahip Message isimli objemiz bulunmakta. MessageService’de sendMessage ve getMessageById şeklinde 2 methodumuz bulunuyor.<br> <br> sendMessage methodunda gelen message objesini messageRepository.save(message); şeklinde kaydediyoruz. Aşağıda bu method için yazdığım unit test bulunuyor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3af9eb27c6cd23f32b408a474d90dec7/href">https://medium.com/media/3af9eb27c6cd23f32b408a474d90dec7/href</a></iframe><p>Bu unit testte sadece messageRepositorynin save methoduna gidip gitmediğini kontrol ediyoruz, methodun çalışmasıyla alakalı bir test yapamadık.</p><p>getMessageById methodunda da gelen id değeriyle messageRepository.findMessageById(id) şeklinde bir arama yapıp varolan dökümanlarda bu idli bir değer varsa onu dönüyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a15f5e3e77d76665adaa2aa1aeee62d/href">https://medium.com/media/4a15f5e3e77d76665adaa2aa1aeee62d/href</a></iframe><p>Bu unit testte ise mockladığımız service’ten istediğimiz objenin döndüğünü kabul ettik ve mock olarak bunu döndük ve bu methodun da unit testini yazmış olduk.</p><p>Bu 2 unit testi yazmış olmamıza rağmen projeyi ayağa kaldırıp test etmeye başladığımızda save ettiğimiz message objesini getById ile elde edemeyebilirdik.</p><p>Bu gibi durumlarda db ile olan entegrasayonumuzu test etmek için Testcontainers’a başvurabiliriz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a34136983b146300f8fc287581d12ac/href">https://medium.com/media/9a34136983b146300f8fc287581d12ac/href</a></iframe><p>CouchbaseTestContainer classımızda <a href="http://twitter.com/Testcontainers">@Testcontainers</a>, <a href="http://twitter.com/ActiveProfiles">@ActiveProfiles</a>(“container”), <a href="http://twitter.com/SpringBootTest">@SpringBootTest</a> annotationları ekli.<br>DockerImageName olarak couchbase:enterprise ve tag değeri olarak 7.1.0 değerini veriyoruz. <br><a href="http://twitter.com/ClassRule">@ClassRule</a> olarak da yukardaki DockerImageName değerini alıp Message Bucket’ı ve istediğimiz username password değerleriyle oluşturuyoruz. Before Class methodunda containerımızı start ediyoruz. <br>bindCouchbaseProperties methodunda ise kaldırdığımız couchbase’in port bilgisini application-container.yml dosyasının içine ekliyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13f7dc0f12be7ce54a6a59c9735d1d60/href">https://medium.com/media/13f7dc0f12be7ce54a6a59c9735d1d60/href</a></iframe><p>MessageServiceIT classımız CouchbaseTestContainer’dan extends alıyor. shouldSendAndGetMessage methodunda önce sendMessage methodunu çağırarak couchbaseimize bir kayıt atıyoruz ardından getById ile bu kaydı çekerek daha sonrasında id, text ve title değerlerini kontrol ediyoruz. Bu şekilde apimizin database’imiz ile entegrasyon testini yapmış oluyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TtMZCCGgF2ocRnePrmq3xw.png" /></figure><p>Testcontainers hakkında daha fazla bilgi edinmek için kendi dökümastasyonunu inceleyebilirsiniz. Basitçe Testcontainers hakkında bilgi vermeye çalıştım umarım faydalı olmuştur. Bir sonraki yazımda görüşmek üzere hoşçakalın.</p><p>Not: Bana mentörlük yapan ve bu teknoloji ile tanışmamı sağlayan Cemal Önder’e teşekkür ederim.</p><p>Kaynakça</p><p><a href="https://www.testcontainers.org/">https://www.testcontainers.org</a><br><a href="https://www.swtestacademy.com/couchbase-testcontainers-in-spring-boot-tests-with-junit-5/">https://www.swtestacademy.com/couchbase-testcontainers-in-spring-boot-tests-with-junit-5/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74c204d4146e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mocklama Mantığı Ve Wiremock]]></title>
            <link>https://henesgokdag.medium.com/mocklama-mant%C4%B1%C4%9F%C4%B1-ve-wiremock-57a1f8a56ffe?source=rss-4b7f00e49ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/57a1f8a56ffe</guid>
            <category><![CDATA[api-testing]]></category>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[mocking]]></category>
            <dc:creator><![CDATA[H. Enes Gökdağ]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 10:07:52 GMT</pubDate>
            <atom:updated>2022-04-24T10:07:52.013Z</atom:updated>
            <content:encoded><![CDATA[<p>Selamlar, bugün size mocklama mantığı ve Wiremock kullanımı hakkında bilgi vermeye çalışacağım.</p><p>Mock(sahte) nesneler gerçek nesnelerin davranışını kontrollü olarak taklit eden benzetilmiş nesnelerdir. Bir nesnenin davranışını test etmek için o nesnenin bağımlılıklarının mocklanmasına ihtiyacımız vardır. Ayrıca bir apiyi test ederken bağımlı olduğu bileşenleri mocklayarak diğer apilerdeki hatalı durumların bizim apimizin stabilitesini bozmasının da önüne geçebiliriz.</p><p>Öncelikle bir apiye istek atıp işlem yapan basit bir api yazacağım ardından bu isteği wiremock ile nasıl mocklayacağımıza değineceğim. İstek atacağım api olarak The Star Wars Api’yi seçtim. <a href="https://swapi.dev/documentation">https://swapi.dev/documentation</a> adresinden kullanımı hakkında bilgi sahibi olabilirsiniz.</p><p>Makalemde kullanmış olduğum 2 projeyi aşağıdan inceleyebilirsiniz.</p><ul><li><a href="https://github.com/henesgokdag/basic-order-api">GitHub - henesgokdag/basic-order-api</a></li><li><a href="https://github.com/henesgokdag/basic-order-api-acceptance-test">GitHub - henesgokdag/basic-order-api-acceptance-test</a></li></ul><p>Apimizi java dilinde yazdım ve spring boot kullandım. Apinin tek bir endpoint’i var ve bu post /createOrder işlemini yapan endpointimde kullanıcıdan istenilen orderRequest aşağıdaki gibidir.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0384c22d4b58c35662d0ef75789dfc9c/href">https://medium.com/media/0384c22d4b58c35662d0ef75789dfc9c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVeNTlLNoVWcw-F0229fHg.png" /></figure><p>Burdaki peopleId alanındaki değeri alarak swapi’ye call atıyorum. Örneğin peopleId 1 girildiğinde<a href="https://swapi.dev/"> https://swapi.dev/</a>api/people/1 adresine gidip aşağıdaki response’u dönüyor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/289539d82946b5d8296e2a8fd2517ed4/href">https://medium.com/media/289539d82946b5d8296e2a8fd2517ed4/href</a></iframe><p>Daha sonrasında response olarak yukarıdaki swapinin döndüğü PeopleResponse objesini ve girilen peopleId, orderName ve orderDescription değerlerini döneceğim. Bu çok basit bir api olduğu için db kullanmaya ihtiyaç duymadım. Aşağıda örnek bir orderResponse bulunmaktadır.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e82fa450e9b026f65e1603c12af0126a/href">https://medium.com/media/e82fa450e9b026f65e1603c12af0126a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QwUzL2EendR6eWoD_t5-Wg.jpeg" /></figure><p>Ayrıca apime eğer gelen PeopleResponse objesindeki name değeri Darth Vader ise “Darth Vader cannot create an order.” şeklinde 400 dönen bir hata mesajı da ekledim. Örnek Response aşağıda görünmektedir.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e6b0fe5ad03af2059b69a4f85c6fec0/href">https://medium.com/media/4e6b0fe5ad03af2059b69a4f85c6fec0/href</a></iframe><p>Benim bu apiyi izole bir ortamda kaldırdığımı varsayalım. Ben /createOrder işlemini yaptığımda swapi’ye istek atacak fakat swapi bu izole ortamda bulunmadığı için hata alacak dolayısıyla ben apimin doğru şekilde çalışıp çalışmadığını kontrol edemeyeceğim. Doğru bir şekilde çalışıp çalışmadığını kontrol edebilmem için benim swapi’yi mocklamam gerekmektedir. Burada imdadımıza wiremock yetişmektedir.</p><p>Wiremock web servislerini mocklamak için kullanılabilecek bir kütüphanedir. Kullanımı oldukça basittir. Localde aşağıdaki komutla docker üzerinden kaldırdığım <a href="http://localhost:8083/">http://localhost:8083/</a> adresine bakmaktadır.</p><blockquote>docker run -it — rm -p 8083:8083 wiremock/wiremock — port 8083</blockquote><p>basic-order-api projesinde SwapiServiceClient class’ındaki retrofit’e baseUrl’in <a href="http://localhost:8083/">http://localhost:8083/</a> olduğunu yazıyorum ve apiyi ayağa kaldırıyorum. Wiremock sayesinde /people/{customer_id} endpoint’ine call atmasını simüle edebileceğim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4BTj6WUfYxVSqvTAxx-LQ.png" /></figure><p>Bunun için öncelikle basic-order-api-acceptance-test projesini oluşturuyorum. Apimizde kullandığım modelleri bu projeye ekliyorum. Burda RestAssured kullanarak apimize call atıyorum. Ardından testlerimi yazmaya başlıyorum. shouldCreateOrder ve shouldNotCreateOrderWhenPeopleIsDarthVader şeklinde 2 testim var. Burda apinin düzgün çalışması için örneğin OrderRequest’imde peopleId 1 gönderdiğimde wiremockta <a href="http://localhost:8083/">http://localhost:8083/</a>people/1 adresinde bir People response objesi oluşturmam gerekiyor. Bunu da aşağıda yazdığım method ile sağlıyorum. StubFor methodu ile bir mock oluşturacağımı belirtiyorum. Get methodu içine döneceğim endpoint’i veriyorum ve willReturn methodu içinde de withStatus dönmek istediğim http status kod değeri, withHeader döneceğim Header değeri ve withBody döneceğim Body değeri bulunmakta.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f6207fcb8785bc5def70a24e340edc8/href">https://medium.com/media/4f6207fcb8785bc5def70a24e340edc8/href</a></iframe><p>Burda mockla kapsamak istediğim özel durumlar olursa onu da handle edebilirim. Hatırlasanız ben apimizde eğer people name’i DarthVader ise “Darth Vader cannot create an order.” şeklinde mesaj atan ve 400 dönen bir kontrol yazmıştım. Bunun testini yapmak için methoda bir boolean isDarthVader kontrolü ekledim eğer bu değer true ise PeopleResponse’daki name değerine Darth Vader setleniyor böylece bende bu durumu handle edebiliyorum.</p><p>shouldCreateOrder testimizde mock’a isDarthVader flag’ini false gönderiyorum böylece elimde yazdığım randomDataProviderdan dolayı name değeri Luke Skywalker olan bir PeopleResponse dönüyor ve ben de apimize call attığımda peopleResponse’un 200 döndüğünü ve diğer assertionlarımın geçtiğini görüyorum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91868795a8a37b232617a017a5354821/href">https://medium.com/media/91868795a8a37b232617a017a5354821/href</a></iframe><p>shouldNotCreateOrderWhenPeopleIsDarthVader testimizde ise yukarıda bahsettiğim isDarthVader flagini true dönüyorum ve böylece apimizden 400 döndüğünü ve ErrorResponse’un message değerinin “Darth Vader cannot create order” olduğunu assert ediyorum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89b0db92a4f5554c6fd80d50d70a5310/href">https://medium.com/media/89b0db92a4f5554c6fd80d50d70a5310/href</a></iframe><p>localhosttaki wiremock’un döndüğü response objesini görmek istersem <a href="http://localhost:8083/">http://localhost:8083/</a>people/{peopleId} değerini tarayıcıma girerek oluşan objeyi görebilirim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*WzLacQfMyvBBpvDxIoEXpA.png" /></figure><p>Oluşan tüm mockları görmek için <a href="http://localhost:8083/__admin/mappings">http://localhost:8083/__admin/mappings</a> adresine girerim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wcudIC5AuUWeAGebyzx_oQ.png" /></figure><p>Wiremock hakkında daha detaylı bilgi için <a href="https://wiremock.org/docs">https://wiremock.org/docs</a> adresine göz atabilirsiniz.</p><p>Mocklamanın yaratacağı sıkıntılara örnek olarak mockladığımız objelerin kontratınının değişmesini verebiliriz. Bu durumda bizim mockumuza göre izole ortamda api çalışmaya devam edecek fakat gerçek bağımlılığın bulunduğu ortamda hata alacaktır. Bu durumun önüne geçebilmek için kontrat testi yazmalıdır. Kontrat testi hata aldığında ilgili apinin modellerinde bir değişiklik olduğunu farkederiz.</p><p>Basit bir şekilde mocklama mantığı ve Wiremock kullanımı hakkında bilgi vermeye çalıştım umarım faydalı olmuştur. Bir sonraki yazımda görüşmek üzere kendinize iyi bakın.</p><h3>Kaynaklar</h3><p><a href="https://en.wikipedia.org/wiki/Mock_object">https://en.wikipedia.org/wiki/Mock_object</a></p><p><a href="https://wiremock.org/docs/stubbing/">https://wiremock.org/docs/stubbing/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57a1f8a56ffe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Data Elasticsearch]]></title>
            <link>https://henesgokdag.medium.com/spring-data-elasticsearch-17fe1f803412?source=rss-4b7f00e49ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/17fe1f803412</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[H. Enes Gökdağ]]></dc:creator>
            <pubDate>Sat, 08 Jan 2022 09:27:06 GMT</pubDate>
            <atom:updated>2022-01-08T09:27:06.257Z</atom:updated>
            <content:encoded><![CDATA[<p>Selamlar, projemizde Spring Boot ve Spring Data Elasticsearch kullanarak bir ürün objesini Elasticsearch’e kaydetme, güncelleme, silme ve getirme işlemlerini bir rest api yardımıyla yapacağız.</p><p>Projeyi aşağıdaki adresten inceleyebilirsiniz.</p><p><a href="https://github.com/henesgokdag/spring-boot-elastic-api">GitHub - henesgokdag/spring-boot-elastic-api</a></p><p><strong>Elasticsearch</strong> yüksek düzeyde ölçeklenebilir açık kaynak bir full-text arama ve analiz motorudur. Büyük verileri hızlı ve neredeyse gerçek zamanlı olarak depolamanızı, aramanızı ve analiz etmenizi sağlar. Elasticsearch Netflix, Slack, Microsoft ve Uber gibi çeşitli firmalar tarafından kullanılmaktadır.</p><p>Elasticsearch’ün temel kavramları:</p><ul><li>Near Real-Time(NRT): NRT bir döküman indexlendiğinde gerçek zamanlıya yakın bir sürede aranabilir bir duruma gelir.</li><li>Cluster: Verileri bir arada tutan ve bir ya da daha fazla node’u birbirine bağlayan ve arama yetenekleri sağlayan bir koleksiyondur.</li><li>Node: Cluster’ın bir parçası olan ve verileri depolayan, indexleme ve arama işlemine yardımcı olan sunucudur.</li><li>Index: Benzer özelliklere sahip belge koleksiyonu.</li><li>Document(Belge): Indexlenebilen temel data. Json formatındadır.</li><li>Shard ve Replica: Her index birden çok shard’a bölünebilir. Ayrıca bir index 0 replica yani kopyasız veya birden çok replicaya sahip olabilir. Bir dizinin replicası olduğunda primary shard ve replica shardlara(primary shardların kopyası) sahip olacaktır. Bu da örneğin primary shard’da donanımsal bir sıkıntı olduğunda replica shard işimize yarayacaktır.</li></ul><p>Docker’da sırasıyla alttaki 2 komutu çalıştırarak bir Elasticsearch ayağa kaldırmış olacağız.</p><pre>docker pull docker.elastic.co/elasticsearch/elasticsearch:7.16.2</pre><pre>docker run -p 127.0.0.1:9200:9200 -p 127.0.0.1:9300:9300 -e &quot;discovery.type=single-node&quot; docker.elastic.co/elasticsearch/elasticsearch:7.16.2</pre><p>Docker’da ilgili container’ın running statüsünde olduğu gördükten sonra <a href="http://localhost:9200/">http://localhost:9200</a> adresinde aşağıdaki gibi bir json dosyası görüyor olmalıyız. Bu elasticsearch’ün ayakta olduğu anlamına gelir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*sNfUv77lpBEDV8W-EYKlPQ.png" /></figure><p>Daha sonra Spring Boot ile bir java projesi oluşturuyorum. Projemin pom.xml dosyası aşağıdaki gibi. spring-data-elasticsearch dependencysi ile Spring Boot ve Elasticsearch’ü birbirine bağlayabiliriz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99d968b48ebe29853bd05f031223f3dd/href">https://medium.com/media/99d968b48ebe29853bd05f031223f3dd/href</a></iframe><p>Application.java dosyamda SpringApplication.run methodu bulunmakta.Ayrıca @EnableElasticsearchRepositories(basePackages = “org.example”) annotation’ı ile ,Spring Data Elasticsearch’ün Spring Data repositorylerini taramasını sağlıyor. Bunun dışında @EnableSwagger2 annotation’ınını swagger için ekliyorum ve api methodunda da swagger’ın çalışmasını sağlayan kod bulunuyor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43dbd02225a2307daad256af92ade164/href">https://medium.com/media/43dbd02225a2307daad256af92ade164/href</a></iframe><p>ElasticClient.java dosyasında AbstractElasticsearchConfiguration classından extend alıyorum ve ClientConfiguration objesini kullanarak bir RestHighLevelClient objesi oluşturuyorum. Bu obje localhost:9200 adresine bağlantı kuruyor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aec4d6c92fdde80dd12aa671d299f458/href">https://medium.com/media/aec4d6c92fdde80dd12aa671d299f458/href</a></iframe><p>Product.java dosyasında @Document anatasyonu ile eğer indexName değerindeki index mevcut değilse index create işlemini sağlıyoruz. Burda objemizin içindeki fieldları @Field notasyonu ile giriyoruz type değerine field’ın type değerini name değerine de name değerini giriyoruz. id isimli field’a ise @Id notasyonunu kullanıyoruz.</p><p><em>Mapping Annotationları için daha fazla bilgiye </em><a href="https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.mapping.meta-model"><em>https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.mapping.meta-model</em></a><em> adresinden ulaşabilirsiniz.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03edf1d4d98e75d6e3dc75eaf5edda24/href">https://medium.com/media/03edf1d4d98e75d6e3dc75eaf5edda24/href</a></iframe><p>ProductRepository interface’inde ise ElasticsearchRepository’den extend alıyor ve generic olarak&lt;Product,String&gt; değerlerini giriyoruz. Burda ElasticsearchRepository’nin sağladığı methodlara ek olarak kendi yazdığımız findProductByName methodu var. Bu method @Query annotation’ı içindeki değer sayesinde aşağıdaki query’yi Elasticsearch’e gönderir ve List&lt;Product&gt; sonucu bekler.</p><pre>{<br>  &quot;query&quot;: {<br>    &quot;match&quot;: {<br>      &quot;name&quot;: {<br>        &quot;query&quot;: &quot;name&quot;<br>      }<br>    }<br>  }<br>}</pre><p><em>Query örneklerine </em><a href="https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.repositories.autocreation"><em>https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.repositories.autocreation</em></a><em> adresinden ulaşabilirsiniz.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f3db3da4c4dfd865a7cafa42df6a5eb/href">https://medium.com/media/5f3db3da4c4dfd865a7cafa42df6a5eb/href</a></iframe><p>ProductService.java classında üstte bahsettiğimiz ProductRepository classını autowired ile çekerek tüm productları dönen allProducts,Product kayıt etmemizi sağlayan saveProduct, id ile productGet etmemizi sağlayan getproductById, girilen isim değerine göre liste olarak product dönen findProductByName ilgili ürünü update etmemizi sağlayan updateProductById ve ürün silmemizi sağlayan deleteProductById methodları var. Burada productRepositorynin bize sağladığı methodları kullanıyoruz sadece updateProductById’de aşağıdaki kod bloğu var.</p><pre>NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()<br>.withQuery(<em>matchQuery</em>(&quot;id&quot;, id).minimumShouldMatch(&quot;100%&quot;))<br>.build();</pre><pre>SearchHits&lt;Product&gt; products =elasticsearchOperations.search(searchQuery, Product.class, IndexCoordinates.<em>of</em>(&quot;productindex&quot;));</pre><pre>Product product=  products.getSearchHit(0).getContent();</pre><p>Bu kod bloğuna göre öncelikle dışardan gelen değerin id değeriyle match olduğunu kontrol eden bir NativeSearchQuery ‘imiz var . Daha sonrasında bu query’yi gönderip SearchHits&lt;Product&gt; tipinde bir değişken alıyoruz ve burdaki products.getSearchHit(0).getContent() bizim update etmek istediğimiz product objesini bize dönüyor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7c6a55bc8ee3628ee61c65cdd9847de/href">https://medium.com/media/f7c6a55bc8ee3628ee61c65cdd9847de/href</a></iframe><p>ProductController classında ise ProductService’de yazmış olduğumuz methodların rest endpointine dönüştüğü yer diyebiliriz. Örneğin @GetMapping(“/products/{id}”) için productService.getProductById methodunu çağırıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2982d46b04a72f4f548f7e3627f4cfc/href">https://medium.com/media/e2982d46b04a72f4f548f7e3627f4cfc/href</a></iframe><p>Şimdi apiyi ve elastic’i kaldırıp swagger üzerinden endpointlerimizi test edelim.</p><p><a href="http://localhost:8080/swagger-ui.html#">http://localhost:8080/swagger-ui.html</a> adresine giriyorum ve POST /api/products endpointine aşağıdaki json dosyasını execute ediyorum.</p><pre>{<br>  &quot;id&quot;: &quot;17&quot;,<br>  &quot;name&quot;: &quot;test ürünü 17&quot;,<br>  &quot;price&quot;: 17<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Ph9OfnOBWBTmHQ-wg2rIg.png" /></figure><p>Benim örneğimde <a href="http://localhost:9200/productindex/_doc/17">http://localhost:9200/productindex/_doc/17</a> (localhost:9200/(indexAdı)/_doc/idDeğeri)adresine gidip baktığımızda aşağıdaki kaydın eklendiğini görüyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*ucDExBwL50ZBD3GyNJgmew.png" /></figure><p>Daha sonra sırasıyla allProducts, getProductById ve findProductByName methodlarımı çağırıp create ettiğim product’ın geldiğini görüyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I3H9ipMOAHhd7-4OiDlv-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZosfKFsTaxQaNxYduINog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eWVlbt_BRqlYlV45KIxTdg.png" /></figure><p>Oluşturduğum product’ı update ediyorum ardından get endpointleriyle get ederek update olduğunu görüyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4m6_kbNpTnvZ0KKCCcigaw.png" /></figure><p>Oluşturduğum product’ı delete ediyorum ardından get endpointleriyle get ederek product’ın silindiğini görüyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*DBNVj-TR4JB3RI5T940CgQ.png" /></figure><p>Bu yazımda size spring boot elasticsearch hakkında bilgi vermeye çalıştım. Bir sonraki yazımda bu apiye nasıl test yazabiliriz onunla alakalı bir yazı yazmayı planlıyorum görüşmek üzere.</p><p>Kaynak:</p><p><a href="https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.clients">https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.clients</a></p><p><a href="https://www.baeldung.com/spring-data-elasticsearch-tutorial">https://www.baeldung.com/spring-data-elasticsearch-tutorial</a></p><p><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html">https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html</a></p><p><a href="https://medium.com/inside-freenow/centralized-logs-with-elastic-stack-and-apache-kafka-7db576044fe7">https://medium.com/inside-freenow/centralized-logs-with-elastic-stack-and-apache-kafka-7db576044fe7</a></p><p><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/scalability.html">https://www.elastic.co/guide/en/elasticsearch/reference/current/scalability.html</a></p><p><a href="http://www.ilkaygunel.com/spring-data-elasticsearch-demo/">http://www.ilkaygunel.com/spring-data-elasticsearch-demo/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17fe1f803412" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Specflow ve Selenium İle UI Testi Yazımı]]></title>
            <link>https://henesgokdag.medium.com/specflow-ve-selenium-i%CC%87le-ui-testi-yaz%C4%B1m%C4%B1-b040cefa0271?source=rss-4b7f00e49ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b040cefa0271</guid>
            <category><![CDATA[ui-test-automation]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[specflow]]></category>
            <category><![CDATA[ui-testing]]></category>
            <category><![CDATA[uitest]]></category>
            <dc:creator><![CDATA[H. Enes Gökdağ]]></dc:creator>
            <pubDate>Tue, 20 Jul 2021 16:32:12 GMT</pubDate>
            <atom:updated>2021-07-20T16:35:19.688Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhaba, bugün size C# dilinde SpecFlow ve Selenium kullanarak UI testi yazımı hakkında bilgi vermeye çalışacağım.</p><p>Specflow bir BDD(Behavior Driven Development — Davranışa Dayalı Geliştirme) frameworküdür. Senaryoları Gherkin diliyle yazmamızı sağlar. BDD somut örneklerle bir uygulamanın nasıl davranması gerektiği hakkında bilgi sahibi olmamızı sağlar. BDD ile tüm ekibin aynı dili konuşması sağlanır. Yazdığımız testlerin bakımını ve okunmasını kolaylaştırır. Raporlamayı kolaylaştırır. BDD ile yazmış olduğumuz senaryolar yaşayan dökümanlar haline gelecektir.</p><p>Selenium web tarayıcılarını kontrol etmemizi sağlayan bir tarayıcı otomasyon aracıdır. Son kullanıcılar tarafında gerçekleştirilen faaliyetleri simüle etmemizi sağlar. Ayrıca javascript çalıştırma gibi özellikleri de bulunmaktadır. Frontend testleri için kullanılabilir. Selenium Grid sayesinde testlerimizi birden çok makinede paralel olarak çalıştırabiliriz.</p><p>Projeyi Github’da incelemek isterseniz aşağıdaki adresten inceleyebilirsiniz.</p><p><a href="https://github.com/henesgokdag/UITestProjeTrendyol">henesgokdag/UITestProjeTrendyol</a></p><p>.Net Framework sürümü 4.7.2 olan bir Class Library projesi oluşturdum. Ve Solution’a aşağıdaki dosyaları ekledim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*2DCYhGTn3yd6550_ZDqXWQ.png" /><figcaption>Solution yapısı</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0946772fea243750da600edc3e5bd60f/href">https://medium.com/media/0946772fea243750da600edc3e5bd60f/href</a></iframe><p>Projeden kısaca bahsetmek gerekirse Utilities klasörünün altındaki BrowserUtility classında ChromeDriver methodunda yeni bir ChromeDriver oluşturuyorum. GoToUrl methodunda WebDriver ile istenilen url’e gidiyorum. DriverClose methodunda driver’ı kapatıyorum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf2e2d646cde16ea3e91a13fa37f8cee/href">https://medium.com/media/cf2e2d646cde16ea3e91a13fa37f8cee/href</a></iframe><p>Features klasörünün altında 2 adet feature dosyamız var. Senaryolarımız Trendyol.feature dosyasında ürün eklemek için bir senaryo ve sepetten ürün çıkarmak için bir senaryo şeklinde. Specflow Feature dosyasını aşağıdaki şekilde oluşturuyorum. Diğer feature dosyasına daha sonra değineceğim.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf42a33189f0afaaa1435fc94b3c62a0/href">https://medium.com/media/bf42a33189f0afaaa1435fc94b3c62a0/href</a></iframe><p>Test klasöründe Trendyol.cs var bu class için feature dosyalarıyla binding yaptığımız ve step definitionları tanımlayıp feature dosyasındaki steplerle bağladığımız class diyebiliriz. StepDefinition’da yazılan methodlarda PageModel’den ilgili methodu çağırarak istenilen işlemi yaptırıyoruz.</p><p>Feature ile class’ı bind etme işlemini class’ın üstüne alttaki annotation’u ekleyerek yapıyoruz.</p><p><em>[Binding, Scope(Feature = “Trendyol”)]</em></p><p>Senaryomuzun ilk stepinde tarayıcımızı ayağa kaldırıyoruz ve istenilen url adresine gitmesini sağlıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6c4c3695a9b2bf6e95c66d78921ccfa/href">https://medium.com/media/f6c4c3695a9b2bf6e95c66d78921ccfa/href</a></iframe><p>Bir step içerisinde bir değişken göndermek istiyorsak ‘’ içerisine yazmamız gerekir. Örneğin<em> “* Arama alanına ‘bilgisayar’ yazılır” </em>şeklinde bir stepimiz varsa step definition’ımızı da alttaki gibi yazdığımızı düşünürsek string search değeri bilgisayar olacaktır. Step Definitiondaki (.*) değeri değişken demektir.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01ee918916856727ac2947092021a8a8/href">https://medium.com/media/01ee918916856727ac2947092021a8a8/href</a></iframe><p>PageModels klasöründe BasePage.cs ve Trendyol.cs adında 2 class var. BasePage.cs’te sık kullanacağımız methodları yazıyorum. Trendyol.cs dosyası ise BasePage’ten kalıtım alıyor ve selenium kodlarımı bu 2 classa yazıyorum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e6593e2dd5fdd80555ad0dd85bdc92f/href">https://medium.com/media/5e6593e2dd5fdd80555ad0dd85bdc92f/href</a></iframe><p>UI testi yazarken öncelikle elementleri yakalamak gerekir bunu yapmak için farklı yöntemler vardır. Ben genellikler id, class ve xpath kullanıyorum. Id sadece bir tane olabileceği için id varsa onu kullanmak en mantıklıdır daha sonra class ve xpath gelir.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a378bd992725182b8a7a2bdade703cbb/href">https://medium.com/media/a378bd992725182b8a7a2bdade703cbb/href</a></iframe><p>Bunun dışında By ile de WebElementlerimizi yakalayabiliriz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c772c03fa57254c2897d5892d32720b9/href">https://medium.com/media/c772c03fa57254c2897d5892d32720b9/href</a></iframe><p>Bu elementleri yakaladıktan sonra ilgili methodda bu element’e istediğimiz işi yaptırabiliriz.</p><p>Mesela alttaki methodda txtSearch elementine BaseModel’da yazmış olduğumuz EnterSearch methodunu kullanarak search değerini yazdırıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a80d449cfbf04bc09e3cde1aec8e33a/href">https://medium.com/media/4a80d449cfbf04bc09e3cde1aec8e33a/href</a></iframe><p>Bu şekilde senaryomuzu oluşturup elementlerimizi bulduk ve methodları istediğimiz şekilde doldurduktan sonra Test Explorerdan ilgili feature’a tıklayıp run dedikten sonra testlerimizin çalıştığını görürüz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*8v8qIAZln8PnQRQ1ITQ8jQ.png" /></figure><p>Farkettiyseniz 2 senaryomuzda da aşağıdaki adımlar ortak, eğer birden fazla senaryoda ortak adımlar varsa SpecFlow’un Background özelliğini kullanabiliriz. Background sayesinde ortak stepleri bir sefer yazmamız yeterli olacaktır.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ca2f2c4a5a24ffd259f573fef4fb713/href">https://medium.com/media/4ca2f2c4a5a24ffd259f573fef4fb713/href</a></iframe><p>Bunun dışında SepeteUrunEkle senaryomuzda sadece bilgisayar aratmıştık fakat başka kategorilerden de ürünü sepete eklediğimiz bir senaryo yazmamız gerekebilir. Bunu da Examples özelliği ile sağlıyoruz. Örneğin aşağıdaki örnekte Sepete Ürün Ekle senaryomuzda bilgisayar ve telefon kategorilerinden ürünler ekliyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbab278546ec5a6766e97d6689f74454/href">https://medium.com/media/dbab278546ec5a6766e97d6689f74454/href</a></iframe><p>Bu yaptığım değişiklikleri Trendyol2 adında bir Feature ekleyip oraya ekliyorum. Feature’ın son hali aşağıdaki şekilde.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b8b7c1cdf79df5591d5afdebf6fcebd/href">https://medium.com/media/0b8b7c1cdf79df5591d5afdebf6fcebd/href</a></iframe><p>Daha sonra Tests klasörü altındaki Trendyol classına gidip binding’i aşağıdaki şekilde değiştiriyorum.</p><p><em>[Binding, Scope(Feature = “Trendyol2”)]</em></p><p>Bu şekilde Test Explorerdan Trendyol2Feature’ı run ettiğimde aşağıdaki şekilde testlerin başarıyla çalıştığını görüyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*IKp_EMRHgXLDIfcWTm-h1w.png" /></figure><p>Bir sonraki yazımda görüşmek üzere hoşçakalın.</p><p>Not: Testlerin çalışabilmesi için Google Chrome ve Chrome Driver versiyonlarının aynı olması gerekmektedir. Eğer test çalışmazsa Google Chrome’u açtıktan sonra Ayarlar -&gt; Chrome Hakkında adımlarını izleyerek Google Chrome versiyonunuzu öğrenip projede Solution’a sağ tıklayıp Manage Nuget For Solution diyerek Selenium.WebDriver.ChromeDriver paketi için uygun versiyonu seçip install ederseniz testlerin çalışacağını düşünüyorum.</p><p><strong>Kaynaklar</strong></p><ul><li><a href="https://specflow.org/">BDD Framework for .NET - SpecFlow - Find Bugs before they happen</a></li><li><a href="https://www.selenium.dev/documentation/en/">The Selenium Browser Automation Project</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b040cefa0271" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rest Assured ile API Testi]]></title>
            <link>https://henesgokdag.medium.com/rest-assured-ile-api-testi-384be4b70ad4?source=rss-4b7f00e49ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/384be4b70ad4</guid>
            <category><![CDATA[rest-assured-ile-api-test]]></category>
            <category><![CDATA[api-testing]]></category>
            <category><![CDATA[api-test]]></category>
            <category><![CDATA[api-test-automation]]></category>
            <category><![CDATA[restassured]]></category>
            <dc:creator><![CDATA[H. Enes Gökdağ]]></dc:creator>
            <pubDate>Mon, 08 Mar 2021 14:55:29 GMT</pubDate>
            <atom:updated>2021-03-08T15:39:42.295Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhabalar bugün Rest Assured ile API testi hakkında bilgi vermeye çalışacağım.</p><p>Rest Assured Java dilinde API testlerimizi yazmamızı sağlayan bir teknolojidir. Bugünkü senaryomuzda Rick And Morty API’ı kullanarak 2 test yazacağız. Rick And Morty API’ı Rick And Morty dizisindeki karakterler ve mekanlar ve bölümler hakkında bilgilerin bulunduğu bir API. Öncelikle API’daki /character endpoint’i ile tüm karakterleri çekeceğiz ve daha sonra bunu bir objeye atayıp location bilgisi “Earth (Replacement Dimension)” olanların toplam sayısını bulacağız ve bu karakterleri bir listeye atıp ekrana yazdıracağız.</p><p>2. testimizde ise /character endpoint’ine name parametresi ekleyerek ismi rick olan karakterleri çekip adı Rick Sanchez olan karakteri seçerek bu karakterin id, status, gender ve location bilgilerinin beklenen değerlerle eşit olup olmadığını kontrol edeceğiz.</p><p>Projemizde kullandığımız bağımlılıklar bu şekilde. Rest Assured 4.3.0 versiyonunu kullanıyorum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dab6019a9231f0648bcd3ffd2fd44ba8/href">https://medium.com/media/dab6019a9231f0648bcd3ffd2fd44ba8/href</a></iframe><p>Rick And Morty API’ını ve dönen json değerleri inceleyebilmeniz için API’ın dökümantasyonundan yararlanabilirsiniz.</p><p><a href="https://rickandmortyapi.com/documentation/">Documentation</a></p><p>Ben API’ın /character endpointini ve aynı endpoint’in name parametreli versiyonunu kullanacağım. Endpointten dönen json’ı Character objesine çevirmek için Jackson kullanıyorum.</p><p>Burda json properties ile id, name, status, gender ve location değerlerini alıyorum ve geri kalan değerlerle bir işlem yapmayacağım için @JsonIgnoreProperties(ingoneUnknown=true) annotation’ını kullanıyorum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3919c670500f499b2b9764c3a833689/href">https://medium.com/media/c3919c670500f499b2b9764c3a833689/href</a></iframe><p>Burdaki Location değeri de bir obje olduğu için onun için de Location modelini oluşturuyorum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc119e199ed26a1586bbb75aafe29a04/href">https://medium.com/media/fc119e199ed26a1586bbb75aafe29a04/href</a></iframe><p>Bir BaseService açıyorum ve içinde RequestSpecification dönen setupRequestSpecification methodunu yazıyorum. Bu Methodda API’ımızın Url’i bulunuyor</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35a667248f8cd80f4815de06c4fdcfd0/href">https://medium.com/media/35a667248f8cd80f4815de06c4fdcfd0/href</a></iframe><p>Daha sonra CharacterServices classında BaseServices classından kalıtım aldım ve getAllCharacters methodunu yazdım. Bu method ile BaseService’teki setupRequestSpecification methodundan RequestSpecification değerini alıyorum daha sonra character endpointi ile tüm gelen karakter listesini alıyorum ve yazmış olduğumuz Character modelinin listesine ekliyorum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51f78a1184202da27c512e018fe63fe7/href">https://medium.com/media/51f78a1184202da27c512e018fe63fe7/href</a></iframe><p>İkinci testim için de getAllCharactersByName methodunu yazıyorum bu method dışardan name bilgisi alıyor ve yapacağı isteğin içine bu name bilgisini parametere olarak ekliyor buna göre de bir karakter listesi dönüyor ve Character modelinin listesine bunu da ekliyorum.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/581408360e2126bc32997cf64e7388ac/href">https://medium.com/media/581408360e2126bc32997cf64e7388ac/href</a></iframe><p>Test Classımızda da 2 tane test var bunlardan biri numberOfLocationEarth methodu burda yazmış olduğumuz getAllCharacters methodunu çağırıyoruz ve dönen listeden Location Name’i “Earth (Replacement Dimension)” olanların sayısını ve isimlerini dönüyoruz. Burda toplam sayının 9 olduğunu kontrol ediyoruz.</p><p>Diğer testimizde de getAllCharactersByName methodunu “Rick” parametresi ile çağırıyoruz. Ve dönen listeden Name değeri Rick Sanchez’e eşit olan Character Nesnesinin location name, gender, id ve Status değerlerinin beklenen değerlerle eşit olup olmadığını kontrol ediyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03c28cc1ba2002f4bb4873cde0618932/href">https://medium.com/media/03c28cc1ba2002f4bb4873cde0618932/href</a></iframe><p>Run All diyerek testleri çalıştırdığımızda çıktının aşağıdaki gibi olduğunu ve 2 testimizin de pass olduğunu görüyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*FRyG7Ys17x1HUooRhtFL4Q.png" /></figure><p>Projeyi Github’da incelemek isterseniz aşağıdaki adresten inceleyebilirsiniz.</p><p><a href="https://github.com/henesgokdag/RestAssured-RickAndMortyApi">henesgokdag/RestAssured-RickAndMortyApi</a></p><p>Bu yazımda size Rest Assured hakkında bilgi vermeye çalıştım. Bir sonraki yazımda görüşmek üzere hoşçakalın.</p><p>Kaynaklar:</p><ul><li>h<a href="https://www.tutorialspoint.com/jackson_annotations/jackson_annotations_jsonignoreproperties.htm">ttps://www.tutorialspoint.com/jackson_annotations/jackson_annotations_jsonignoreproperties.htm</a></li><li><a href="https://rickandmortyapi.com/documentation/">https://rickandmortyapi.com/documentation/</a></li><li><a href="https://rest-assured.io/">https://rest-assured.io</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=384be4b70ad4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Postman İle API Testi]]></title>
            <link>https://henesgokdag.medium.com/postman-i%CC%87le-api-testi-8fc807f28b5e?source=rss-4b7f00e49ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fc807f28b5e</guid>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[api-test-postman]]></category>
            <category><![CDATA[postman-ile-api-testi]]></category>
            <dc:creator><![CDATA[H. Enes Gökdağ]]></dc:creator>
            <pubDate>Thu, 21 Jan 2021 14:29:16 GMT</pubDate>
            <atom:updated>2021-01-22T17:57:19.799Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhaba,</p><p>Bu yazımda Postman ile API Testi hakkında bilgi vermeye çalışacağım.</p><p>Basit şekilde (Application Programming Interface) yani Uygulama Programlama Arayüzü, bir uygulamanın/servisin/platformun sahip olduğu özelliklerin dışarıdan izin verilen sınırlandırmalar dahilinde kullanılabilmesini sağlayan bir arayüzdür.</p><p>Postman sayesinde API’larımızla iletişim kurabiliriz ve API’larımızı test edebiliriz.</p><p>Burada daha önce yazılmış bir api kullanacağım. Api testinde senaryom:</p><p>- POST ../Authenticate Requesti ile yeni bir token oluşturmak ve bu token değerini Environment’a atamak.</p><p>- Bu token değeriyle GET ../Api/Movies/Top10 Requestiyle 10 adet kayıt getirmek.</p><p>şeklinde olacak.</p><p>Postman’de Environment Requestlerimizde tekrar eden alanları değişken olarak oluşturup kullanmamıza yarıyor. Environment’a atanmış x değişkenini {{x}} şeklinde çağırarak kullanabiliriz.</p><p>Benim Api testlerimde kullanacağım environment bu şekilde.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*o4nDlSLsPVeeKWmR6VQULg.png" /></figure><p>POST ../Authenticate Requestinde Environment’tan gelen username ve password değerleriyle yeni bir token üretilir. Burada yaptığım 3 test bulunmakta. Bu testlerden birincisi Response Status değerinin 200(başarılı) olması. İkinci test response’un 200 ms’ten daha kısa sürede dönmesi. Üçüncü test ise token değerinin undefined’dan farklı olduğunun kontrolü.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XBDcYVo0E2zzKtRxWmrA_w.png" /></figure><p>Request’i çalıştırdığımızda 3 testin pass olduğunu görüyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TVP_hQu7-6Q3pkwkLSSpug.png" /></figure><p>Üretilen Token değeri yukarda görünür.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*Y3NDra6vjgATMGsg-RWmyw.png" /></figure><p>Örneğin password’u boş bırakıp Request’i çalıştırdığımda Login olamaz ve token üretemez bu yüzden testlerden birinin fail olduğunu görürüz.</p><p>GET ../Api/Movies/Top10 Requestinde ise yazdığım 4 tane test var. Bunlardan 2’si yine aynı şekilde Response Status kodunun 200 olması ve Response Time’ın 200 msten az olması. 3. testim responsetan dönen ilk değerin title değerinin “Pulp Fiction” olduğu. 4. testim ise dönen dizinin eleman sayısının 10 olması.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZwpCrOziBnN8RRuwGJseHA.png" /></figure><p>Testlerin başarılı bir şekilde çalıştığı görülür.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFEmlP0oemQN9kfWPBjkXQ.png" /></figure><p>İlk gelen değerin title değerinin Pulp Fiction olduğu görülmektedir.</p><p>Ayrıca Postman’de bulunan Snippets yardımıyla requestlerimize kolaylıkla test ekleyebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*oTwNksEPq8chjoQDHwjzBQ.png" /></figure><p>Postman’de bulunan Collection Runner sayesinde birbiriyle bağlantılı requestleri sırayla çalıştırabiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hh8xslg1Ei8zQ6bvYBSxyg.png" /></figure><p>Ben burada yukarıda bahsettiğim 2 senaryoyu çalıştıracağım Environment değeri olarak oluşturduğum Environment’ı seçiyorum. Iterations değerini de testlerin 3 kere çalışmasını istediğim için 3 değerini giriyorum. Ardından Run My Api Tests butonuna tıklıyorum.</p><p>Testler çalıştırılırken Run Resultları bu şekilde görebiliriz. Toplam 21 testin pass olduğunu görüyoruz.</p><p>Bir sonraki yazımda görüşmek üzere, hoşçakalın.</p><p>Kaynaklar:</p><p><a href="https://www.milliyet.com.tr/gundem/api-nedir-ne-ise-yarar-yazilimda-ne-icin-api-kullanilir-6269096">https://www.milliyet.com.tr/gundem/api-nedir-ne-ise-yarar-yazilimda-ne-icin-api-kullanilir-6269096</a></p><p><a href="https://learning.postman.com/docs/getting-started/introduction/">https://learning.postman.com/docs/getting-started/introduction/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fc807f28b5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>